diff --git "a/4270.jsonl" "b/4270.jsonl" new file mode 100644--- /dev/null +++ "b/4270.jsonl" @@ -0,0 +1,770 @@ +{"seq_id":"80018071","text":"import re\nimport string\nimport json\nfrom operator import itemgetter\n\n\nfrequency = {}\nwith open(input('Название файла с леммами: '), 'r') as text_file:\n text_str = text_file.read().lower()\n q_pattern = re.findall(r'\"lemma\": \"([\\s\\S]+?)\",', text_str)\n\n for word in q_pattern:\n count = frequency.get(word, 0)\n frequency[word] = count + 1\n\n frequency_list = frequency.keys()\n my_dict = {}\n for words in frequency_list:\n my_dict[words] = [frequency[words]]\n\n sorted_dict = sorted(my_dict.items(), key=itemgetter(1), reverse=True)\n\n with open(\"freqfreqlist.json\", \"a\", encoding=\"utf-8\") as f:\n json.dump(sorted_dict, f, ensure_ascii=False, indent=1)\n","sub_path":"visualization/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81550326","text":"import inspect\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.utils.module_loading import import_module\n\nfrom post_office import models\n\nfrom lcdmarket.api import utils\nfrom lcdmarket.api.core import TemplatedEmail\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n templates = self.get_apps()\n self.create_templates(templates)\n\n def get_apps(self):\n \"\"\"\n Get the list of installed apps\n and return the apps that have\n an emails module\n \"\"\"\n templates = []\n for app in settings.INSTALLED_APPS:\n try:\n app = import_module(app + '.emails')\n templates += self.get_solomail_subs(app)\n except ImportError:\n pass\n return templates\n\n def get_solomail_subs(self, app):\n \"\"\"\n Returns a list of tuples, but it should\n return a list of dicts\n \"\"\"\n classes = []\n members = inspect.getmembers(app)\n for member in members:\n name, cls = member\n if inspect.isclass(cls) and issubclass(cls, TemplatedEmail) and name != 'TemplatedEmail':\n try:\n subject = cls.subject\n description = cls.description\n location = app.__file__\n classes.append((name, location, subject, description))\n except AttributeError:\n raise AttributeError('Email class must specify email subject and description.')\n return classes\n\n def create_templates(self, templates):\n \"\"\"\n Gets a list of templates to insert into the database\n \"\"\"\n for template in templates:\n name, location, subject, description = template\n if not self.template_exists_db(name):\n # create template if it does not exists\n # if does not exist, try to find a default template\n dir_ = location[:-9] + 'templates/emails/'\n file_ = dir_ + utils.camel_to_snake(name) + '.html'\n text = self.open_file(file_)\n data = {\n 'name': utils.camel_to_snake(name).upper(),\n 'html_content': text,\n 'content': self.text_version(text),\n 'subject': subject,\n 'description': description\n }\n models.EmailTemplate.objects.create(**data)\n\n def text_version(self, html):\n \"\"\"\n Uses util to create a text email template\n from a html one\n \"\"\"\n return utils.html_to_text(html)\n\n def open_file(self, file_):\n \"\"\"\n Receives a file path has input and returns a\n string with the contents of the file\n \"\"\"\n with open(file_, 'r', encoding='utf-8') as file:\n text = ''\n for line in file:\n text += line\n return text\n\n def template_exists_db(self, template):\n \"\"\"\n Receives a template name and sees if it exists in the database\n \"\"\"\n template = utils.camel_to_snake(template).upper()\n try:\n models.EmailTemplate.objects.get(name=template)\n except models.EmailTemplate.DoesNotExist:\n return False\n return True\n","sub_path":"lcdmarket/api/management/commands/load_email_templates.py","file_name":"load_email_templates.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"409346993","text":"# Copyright 2021 The Kubeflow Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for kfp.dsl.pipeline_channel.\"\"\"\n\nimport unittest\n\nfrom absl.testing import parameterized\nfrom kfp import dsl\nfrom kfp.dsl import pipeline_channel\n\n\nclass PipelineChannelTest(parameterized.TestCase):\n\n def test_instantiate_pipline_channel(self):\n with self.assertRaisesRegex(\n TypeError, \"Can't instantiate abstract class PipelineChannel\"):\n p = pipeline_channel.PipelineChannel(\n name='channel',\n channel_type='String',\n )\n\n def test_invalid_name(self):\n with self.assertRaisesRegex(\n ValueError,\n 'Only letters, numbers, spaces, \"_\", and \"-\" are allowed in the '\n 'name. Must begin with a letter. Got name: 123_abc'):\n p = pipeline_channel.create_pipeline_channel(\n name='123_abc',\n channel_type='String',\n )\n\n def test_task_name_and_value_both_set(self):\n with self.assertRaisesRegex(ValueError,\n 'task_name and value cannot be both set.'):\n p = pipeline_channel.create_pipeline_channel(\n name='abc',\n channel_type='Integer',\n task_name='task1',\n value=123,\n )\n\n def test_invalid_type(self):\n with self.assertRaisesRegex(TypeError,\n 'Artifact is not a parameter type.'):\n p = pipeline_channel.PipelineParameterChannel(\n name='channel1',\n channel_type='Artifact',\n )\n\n with self.assertRaisesRegex(TypeError,\n 'String is not an artifact type.'):\n p = pipeline_channel.PipelineArtifactChannel(\n name='channel1',\n channel_type='String',\n task_name='task1',\n is_artifact_list=False,\n )\n\n @parameterized.parameters(\n {\n 'pipeline_channel':\n pipeline_channel.create_pipeline_channel(\n name='channel1',\n task_name='task1',\n channel_type='String',\n ),\n 'str_repr':\n '{{channel:task=task1;name=channel1;type=String;}}',\n },\n {\n 'pipeline_channel':\n pipeline_channel.create_pipeline_channel(\n name='channel2',\n channel_type='Integer',\n ),\n 'str_repr':\n '{{channel:task=;name=channel2;type=Integer;}}',\n },\n {\n 'pipeline_channel':\n pipeline_channel.create_pipeline_channel(\n name='channel3',\n channel_type={'type_a': {\n 'property_b': 'c'\n }},\n task_name='task3',\n ),\n 'str_repr':\n '{{channel:task=task3;name=channel3;type={\"type_a\": {\"property_b\": \"c\"}};}}',\n },\n {\n 'pipeline_channel':\n pipeline_channel.create_pipeline_channel(\n name='channel4',\n channel_type='Float',\n value=1.23,\n ),\n 'str_repr':\n '{{channel:task=;name=channel4;type=Float;}}',\n },\n {\n 'pipeline_channel':\n pipeline_channel.create_pipeline_channel(\n name='channel5',\n channel_type='system.Artifact@0.0.1',\n task_name='task5',\n ),\n 'str_repr':\n '{{channel:task=task5;name=channel5;type=system.Artifact@0.0.1;}}',\n },\n )\n def test_str_repr(self, pipeline_channel, str_repr):\n self.assertEqual(str_repr, str(pipeline_channel))\n\n def test_extract_pipeline_channels(self):\n p1 = pipeline_channel.create_pipeline_channel(\n name='channel1',\n channel_type='String',\n value='abc',\n )\n p2 = pipeline_channel.create_pipeline_channel(\n name='channel2',\n channel_type='customized_type_b',\n task_name='task2',\n )\n p3 = pipeline_channel.create_pipeline_channel(\n name='channel3',\n channel_type={'customized_type_c': {\n 'property_c': 'value_c'\n }},\n task_name='task3',\n )\n stuff_chars = ' between '\n payload = str(p1) + stuff_chars + str(p2) + stuff_chars + str(p3)\n params = pipeline_channel.extract_pipeline_channels_from_string(payload)\n self.assertListEqual([p1, p2, p3], params)\n\n # Expecting the extract_pipelineparam_from_any to dedup pipeline channels\n # among all the payloads.\n payload = [\n str(p1) + stuff_chars + str(p2),\n str(p2) + stuff_chars + str(p3)\n ]\n params = pipeline_channel.extract_pipeline_channels_from_any(payload)\n self.assertListEqual([p1, p2, p3], params)\n\n\nclass TestCanAccessTask(unittest.TestCase):\n\n def test(self):\n\n @dsl.component\n def comp() -> str:\n return 'text'\n\n @dsl.pipeline\n def my_pipeline():\n op1 = comp()\n self.assertEqual(op1.output.task, op1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"sdk/python/kfp/dsl/pipeline_channel_test.py","file_name":"pipeline_channel_test.py","file_ext":"py","file_size_in_byte":5967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529921233","text":"# -*- coding: utf-8 -*-\n\n#%% Creating classes\n\n#class ElectricCar:\n \nclass Car:\n pass\n\ncar1 = Car()\ncar2 = Car()\ncar3 = Car()\n\nprint(type(car1))\n\n#%% constructing objects\n\nclass Car:\n \n def __init__(self, brand, model):\n self.brand = brand\n self.model = model\n \n \nford_fiesta = Car(\"Ford\", \"Fiesta\")\ntesla_modelx = Car(\"Tesla\", \"Model X\")\n\nprint(ford_fiesta.model)\n \nprint(tesla_modelx.brand)\n\nprint(dir(ford_fiesta))\n \n#%% validation on construction\n \nclass Car:\n \n def __init__(self, brand, model):\n \n if brand != \"Tesla\":\n raise ValueError(\"Only Tesla accepted, we're green!\")\n \n self.brand = brand\n self.model = model\n \ncar1 = Car(\"Tesla\", \"Model S\")\n\ncar2 = Car(\"Ford\", \"Mondeo\")\n \n#%% \n\nclass Clock:\n \n def __init__(self, hours, minutes):\n \n if type(hours) != int or type(minutes) != int:\n raise TypeError(\"hours and minutes need to be ints\")\n \n if hours < 0 or hours > 23:\n raise ValueError(\"hours need to be in the 0-23 range\")\n \n if minutes < 0 or minutes > 59:\n raise ValueError(\"minutes need to be in the 0-59 range\")\n \n self.hours = hours\n self.minutes = minutes\n \n \n\nclock1 = Clock(1, 55)\n# clock_wrong = Clock(\"hello\", \"my friends\")\n#clock_wrong = Clock(3,-6)\n\n#%%\n\nclass Car:\n \n def __init__(self, brand, model):\n self.brand = brand\n self.model = model\n self.started = False\n \n def start_engine(self):\n self.started = True\n \n def honk(self):\n print(\"BEEEEEP\")\n \n \ncar = Car(\"Audi\", \"A3\")\n\nprint(car.started)\n\ncar.start_engine()\n\nprint(car.started)\n\ncar.honk()\n\n#%%\n\nclass Member:\n \n def __init__(self, name, instrument):\n self.name = name\n self.instrument = instrument\n \n def play(self):\n print(self.name + \" is playing the \" + self.instrument)\n \njohn = Member(\"John\", \"voice\")\npaul = Member(\"Paul\", \"bass guitar\")\ngeorge = Member(\"George\", \"guitar\")\nringo = Member(\"Ringo\", \"drums\")\n\n \nclass RockBand:\n\n def __init__(self):\n self.members = []\n \n def add_member(self, member):\n self.members.append(member)\n \n def rehearse(self):\n for member in self.members:\n member.play()\n \n \nbeatles = RockBand()\n\nbeatles.add_member(john)\nbeatles.add_member(paul)\nbeatles.add_member(george)\nbeatles.add_member(ringo)\n\nbeatles.rehearse()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n ","sub_path":"session18.py","file_name":"session18.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"113686864","text":"#!/bin/env python\n\nimport extruct\nimport json\nimport itertools\nimport os\nfrom tqdm import tqdm\nfrom collections import defaultdict\n\n\nimport utils\nimport claimreview\n\nsubfolder_path = utils.data_location / 'datacommons_factcheck'\nsource_file_path = subfolder_path / 'source' / 'fact_checks_20180930.txt'\nintermediate_path = subfolder_path / 'intermediate'\nintermediate_file = intermediate_path / 'datacommons_claimReviews.json'\n\ndef load_jsonld():\n # read the file\n with open(source_file_path) as f:\n content = f.read()\n\n # extract the embedded metadata https://github.com/scrapinghub/extruct\n data = extruct.extract(content)\n\n claimReviews = data['json-ld']\n\n # some analysis of the labels to see how they are annotated\n labels = set([el['reviewRating']['alternateName'] for el in claimReviews])\n lambda_source = lambda el: el['author']['name']\n\n # group the labels by the author of the review, to see how each one of them uses the alternateName\n labels_by_sources = {k:set([el['reviewRating']['alternateName'] for el in v]) for k, v in itertools.groupby(sorted(claimReviews, key=lambda_source), key=lambda_source)}\n\n print('#claimReviews', len(claimReviews))\n print('#labels', len(labels))\n #print('labels', labels)\n print('#label for each source', {k:len(v) for k,v in labels_by_sources.items()})\n\n # save the original claimReviews\n utils.write_json_with_path(claimReviews, intermediate_path, 'datacommons_claimReviews.json')\n\n return claimReviews\n\ndef get_claimreviews_from_factcheckers(original_claimReviews):\n result = {}\n\n # retrieve the full claimReview from the fact checking website\n for idx, c in enumerate(tqdm(claimReviews)):\n # get the correct URL (some of them are wrong in the original dataset)\n fixed_url = claimreview.get_corrected_url(c['url'])\n\n # this part with id and file saving is just to be able to restore the operation after a failure so that the single claims are saved onto disk on by one\n id = utils.string_to_md5(fixed_url)\n partial_file_name = '{}.json'.format(id)\n partial_file_path = subfolder_path / 'intermediate' / 'single_claims' / partial_file_name\n if os.path.isfile(partial_file_path):\n # if it's been already saved, read it\n partial = utils.read_json(partial_file_path)\n else:\n # otherwise download the original claimReview from the fact checker\n url, partial = claimreview.retrieve_claimreview(c['url'])\n # and save it to disk\n utils.write_json_with_path(partial, subfolder_path / 'intermediate' / 'single_claims', partial_file_name)\n if not partial:\n # in this case there is no claimReview metadata on the fact checker website\n #print(c['url'])\n pass\n if len(partial):\n # there can be multiple claimReviews in a single fact checking page\n for j, claimReview in enumerate(partial):\n # save this in the result\n result['{}::{}'.format(fixed_url, j)] = claimReview\n\n return result\n\n\nif __name__ == '__main__':\n claimReviews = load_jsonld()\n\n # if you share a fact checking site, the fact checking site is true\n urls = [{'url': c['url'], 'label': 'true', 'source': 'datacommons_factcheck'} for c in claimReviews]\n\n # retrieve the claimReviews with more properties\n claimReviews_full = get_claimreviews_from_factcheckers(claimReviews)\n # save to file\n utils.write_json_with_path(claimReviews_full, subfolder_path, 'claimReviews.json')\n\n # rebuttals is a dict that associates each URL with other URLs that are related. In this case it is for suggesting to read the fact checking article\n rebuttals = defaultdict(lambda: defaultdict(list))\n for key, claimReview in claimReviews_full.items():\n # retrieve the URL of the source of the claim (not always there)\n claim_urls = claimreview.get_claim_urls(claimReview)\n if claim_urls:\n print('claim', claim_urls)\n if 'properties' in claimReview:\n fixed_url = claimreview.get_corrected_url(claimReview['properties']['url'])\n else:\n fixed_url = claimreview.get_corrected_url(claimReview['url'])\n\n # save the found mapping between the claim URL and the factchecking URL\n rebuttals[claim_urls][fixed_url] = ['datacommons_factcheck']\n score = claimreview.get_claim_rating(claimReview)\n print(score)\n label = None\n if score != None:\n # convert to fake/true\n if score <= 0.30:\n label = 'fake'\n if score >= 0.8:\n label = 'true'\n if label:\n # save the label for the URL of the claim\n urls.append({'url': claim_urls, 'label': label, 'source': 'datacommons_factcheck'})\n\n print(len(rebuttals))\n\n utils.write_json_with_path(rebuttals, subfolder_path, 'rebuttals.json')\n\n\n utils.write_json_with_path(urls, subfolder_path, 'urls.json')\n\n # aggregate by domain\n by_domain = utils.compute_by_domain(urls)\n utils.write_json_with_path(by_domain, subfolder_path, 'domains.json')\n\n\n","sub_path":"datacommons_factcheck.py","file_name":"datacommons_factcheck.py","file_ext":"py","file_size_in_byte":5254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"367300700","text":"import logging\nfrom random import random, randint\n\nfrom os import path\n\nfrom SupplementaryFiles.GameDataHandler import GameDataHandler\nfrom SupplementaryFiles.LoadGraph import load_py_graph\nfrom SupplementaryFiles.Utils import Utils\nfrom KivyFiles.GraphTabletDisplay import GraphTabletDisplay\n\n# https://gist.github.com/kastnerkyle/d127197dcfdd8fb888c2\n\nCURIOSITY_VALUE = 1 # 1 = random. 0.1 ~ about right for learning\nGAMMA = 0.8\nALPHA = 0.1\n\nCONFIG_FILE_PATH = path.join(\"..\", \"game_config.txt\")\nGRAPH_CONFIG_PATH = path.join(\"..\", \"graph_config.txt\")\n\nlog = logging.getLogger()\n\nconsecutive_runs = 20\n\n\nclass QMatrix:\n moves_matrix = []\n\n action_space = 4\n first_step = 0 # The first step taken by the QMatrix, press button 1\n prev_step = 0 # The previous step taken by the matrix\n prev_known_nodes = 0 # The amount of nodes we have seen until before this step\n nodes_in_graph = 10\n max_steps = 0\n\n def __init__(self, action_space, max_steps, nodes_in_graph):\n self.action_space = action_space\n self.max_steps = max_steps\n self.nodes_in_graph = nodes_in_graph\n self.reinit()\n self.moves_matrix = []\n for i in range(4):\n self.moves_matrix.append([])\n for _ in range(4):\n self.moves_matrix[i].append(0)\n\n def reinit(self, known_nodes=0):\n self.prev_step = 0\n self.prev_known_nodes = known_nodes\n\n def init_q_array(self):\n pass\n\n def init_record_array(self):\n pass\n\n def max_args(self):\n \"\"\"\n looks at the matrix. chooses option with highest percentage\n \"\"\"\n return self.moves_matrix[self.prev_step].index(max(self.moves_matrix[self.prev_step]))\n\n def choose_action_epsilon_greedy(self):\n if random() < CURIOSITY_VALUE:\n return randint(1, self.action_space) - 1\n else:\n return self.max_args()\n # Maybe not use greedy??\n\n def update_matrix(self, num_nodes, current_step):\n \"\"\"\n\n :param num_nodes:\n :param current_step:\n :return:\n \"\"\"\n\n improvement_score = self.get_reword_score(num_nodes, self.nodes_in_graph, calc_type=2)\n qsa = self.moves_matrix[self.prev_step][current_step]\n # = qsa + ALPHA * (rsa + GAMMA * max(self.moves_arr[current_step][:]) - qsa)\n new_q = qsa + ALPHA * (improvement_score + GAMMA * max(self.moves_matrix[current_step][:]) - qsa)\n self.moves_matrix[self.prev_step][current_step] = new_q\n\n self.prev_step = current_step\n return 100*float(num_nodes)/float(self.nodes_in_graph)\n\n def get_reword_score(self, current_known_nodes, nodes_in_full_graph, calc_type=1):\n if calc_type == 1:\n return float(current_known_nodes) / float(nodes_in_full_graph)\n elif calc_type == 2:\n diff_nodes = current_known_nodes - self.prev_known_nodes\n self.prev_known_nodes = current_known_nodes\n return diff_nodes\n\n\nclass QPlayer:\n auto_first_press = 0 # the first button press is predetermined\n\n def __init__(self):\n pass\n\n def run_q_player(self, graph_file_path, log_file_path):\n Utils.read_game_config_file(CONFIG_FILE_PATH)\n Utils.read_graph_config_file(GRAPH_CONFIG_PATH)\n Utils.image_folder = path.join(\"..\", Utils.image_folder)\n\n log.setLevel(Utils.game_config_data['Default']['log_level'])\n session_length = 1000\n\n graph = load_py_graph(graph_file_path)\n q_matrix = QMatrix(action_space=4, max_steps=int(Utils.game_config_data['Default']['max_turns']), nodes_in_graph=len(graph.node_list))\n\n with open(log_file_path,'w') as f:\n f.write(\"episode, score\\n\")\n for i in range(session_length):\n dummy_screen = DummyScreen(graph)\n game = GraphTabletDisplay(dummy_screen)\n data_handler = GameDataHandler(GRAPH_CONFIG_PATH, graph.size)\n data_handler.add_view_to_db(game.get_info_from_screen())\n\n rw = 0\n game.press_button(self.auto_first_press + 1)\n data_handler.add_view_to_db(game.get_info_from_screen())\n q_matrix.reinit(known_nodes=len(data_handler.get_real_nodes()))\n for j in range(1, int(Utils.game_config_data['Default']['max_turns'])):\n log.debug(\"doing a step {}/{}\".format(j, Utils.game_config_data['Default']['max_turns']))\n btn = q_matrix.choose_action_epsilon_greedy()\n game.press_button(btn + 1)\n data_handler.add_view_to_db(game.get_info_from_screen())\n rw = q_matrix.update_matrix(num_nodes=len(data_handler.get_real_nodes()), current_step=btn)\n log.info(\"Q session {}:{} - reword:{}\".format(i, session_length, rw))\n f.write(\"{},{}\\n\".format(i + 1, rw))\n\n\nclass DummyScreen:\n graph = None\n graph_config = GRAPH_CONFIG_PATH\n max_turns = 0\n button_presses = []\n button_ratio = 0.2\n\n def __init__(self, graph):\n self.graph = graph\n self.real_user = False\n self.max_turns = int(Utils.game_config_data['Default']['max_turns'])\n\n def end_graph(self):\n pass\n\n def end_game(self):\n print (\"end game \\n\")\n\n\nfile_name = \"Graph_1.xml\"\ngraph_path = path.join(\"..\", \"GraphsData\", file_name)\ngraph_path = \"graph_1\"\nfor run_index in range(19, consecutive_runs):\n run_log_file = \"result_{}__{}__{}.csv\".format(file_name[:-4], CURIOSITY_VALUE, run_index)\n player = QPlayer()\n player.run_q_player(graph_path, run_log_file)","sub_path":"QLearning/QLearner.py","file_name":"QLearner.py","file_ext":"py","file_size_in_byte":5611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264497709","text":"from datetime import datetime, timedelta\n\nfrom google.appengine.ext import db\n\n#from django.conf import settings\nfrom base import SessionBase\n#from django.core.cache import cache\n\nfrom models.session import Session\n\nclass SessionStore(SessionBase):\n \"\"\"\n A google appengine datastore based session store. \n \"\"\"\n \n def __init__(self, session_key=None):\n self._datastore_session = None\n \n if session_key:\n query = db.Query(Session)\n query = query.filter(\"session_key =\", session_key)\n self._datastore_session = query.get()\n \n super(SessionStore, self).__init__(session_key)\n \n def load(self):\n session_data = {}\n if self._datastore_session:\n if self._datastore_session.expire_date > datetime.now():\n if self._datastore_session.session_data:\n session_data = self.decode(self._datastore_session.session_data)\n else:\n session_data = None\n else:\n self.delete()\n \n return session_data or {}\n\n def save(self):\n time_till_expire = timedelta(seconds=60*60*24*7*2)\n expire_date = datetime.now() + time_till_expire\n \n if self._datastore_session:\n self._datastore_session.session_data = self.encode(self._session)\n else:\n self._datastore_session = Session(session_key=self.session_key, session_data=self.encode(self._session), expire_date=expire_date)\n self._datastore_session.put()\n \n\n def exists(self, session_key):\n query = db.Query(Session)\n query = query.filter(\"session_key =\", session_key)\n session = query.get()\n\n if session:\n exists = True\n else:\n exists = False\n \n return exists\n \n def delete(self, session_key):\n query = db.Query(Session)\n query = query.filter(\"session_key =\", session_key)\n session = query.get()\n\n if session:\n session.delete()\n","sub_path":"ganji/lib/datastore.py","file_name":"datastore.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"40130177","text":"#!/usr/bin/env python3\n\nfrom timfuz import Benchmark, load_sub, load_bounds, loadc_Ads_b\nimport numpy as np\n\n\ndef run(fns_in, corner, bounds_csv, verbose=False):\n print('Loading data')\n Ads, borig = loadc_Ads_b(fns_in, corner)\n\n bounds = load_bounds(bounds_csv, corner)\n # verify is flattened\n for k in bounds.keys():\n assert 'GROUP_' not in k, 'Must operate on flattened bounds'\n\n # compute our timing model delay at the given corner\n bgots = []\n for row_ds in Ads:\n delays = [n * bounds[x] for x, n in row_ds.items()]\n bgots.append(sum(delays))\n\n ses = (np.asarray(bgots) - np.asarray(borig))**2\n mse = (ses).mean(axis=None)\n print('MSE aggregate: %0.1f' % mse)\n print('Min SE: %0.1f' % min(ses))\n print('Max SE: %0.1f' % max(ses))\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser(description='Report a timing fit score')\n\n parser.add_argument('--verbose', action='store_true', help='')\n parser.add_argument('--corner', required=True, default=\"slow_max\", help='')\n parser.add_argument(\n '--bounds-csv',\n required=True,\n help='Previous solve result starting point')\n parser.add_argument('fns_in', nargs='+', help='timing4i.csv input files')\n args = parser.parse_args()\n # Store options in dict to ease passing through functions\n bench = Benchmark()\n\n fns_in = args.fns_in\n if not fns_in:\n fns_in = glob.glob('specimen_*/timing4i.csv')\n\n try:\n run(\n fns_in=fns_in,\n corner=args.corner,\n bounds_csv=args.bounds_csv,\n verbose=args.verbose)\n finally:\n print('Exiting after %s' % bench)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"fuzzers/007-timing/solve_qor.py","file_name":"solve_qor.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"653071534","text":"from django.contrib import admin\nfrom django.contrib.sites.models import Site\nfrom django.contrib.auth.models import Group\nfrom tournaments.models import Player, Tournament, Team, FundsRaised, Nonprofit, TournamentAward, Award\nfrom media.models import TournamentPhoto\n\n\nclass TeamsInline(admin.TabularInline):\n model = Team.players.through\n\n\nclass PlayerAdmin(admin.ModelAdmin):\n inlines = [\n TeamsInline\n ]\n fieldsets = (\n ('Basic', {\n 'fields': (\n 'first_name',\n 'last_name',\n 'bio',\n ),\n }),\n ('Account-related', {\n 'fields': (\n 'username',\n 'email',\n 'is_active',\n 'is_staff',\n ),\n })\n )\n\n\nclass TournamentPhotoInline(admin.TabularInline):\n model = TournamentPhoto\n extra = 1\n\n\nclass FundsRaisedInline(admin.TabularInline):\n model = FundsRaised\n extra = 1\n\n\nclass TournamentAwardInline(admin.TabularInline):\n model = TournamentAward\n extra = 1\n\n\nclass TeamAdmin(admin.ModelAdmin):\n list_filter = ['players']\n\n\nclass TournamentAdmin(admin.ModelAdmin):\n inlines = [\n TournamentPhotoInline,\n FundsRaisedInline,\n TournamentAwardInline,\n ]\n filter_horizontal = ('teams', )\n list_display = ('slogan', 'date', 'winners')\n\n\n# register\nadmin.site.register(Player, PlayerAdmin)\nadmin.site.register(Team, TeamAdmin)\nadmin.site.register(Nonprofit)\nadmin.site.register(Award)\nadmin.site.register(Tournament, TournamentAdmin)\n\n\n# unregister\nadmin.site.unregister(Site)\n# admin.site.unregister(Group)","sub_path":"tournaments/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"381274329","text":"from openspending.lib import ckan\nfrom openspending.lib import json\nfrom openspending.etl.command import daemon\nfrom openspending.etl.ui.test import ControllerTestCase, url, helpers as h\n\nMOCK_REGISTRY = json.load(h.fixture_file('mock_ckan.json'))\n\nclass TestLoadController(ControllerTestCase):\n def setup(self):\n super(TestLoadController, self).setup()\n self.patcher = h.patch('openspending.etl.ui.controllers.load.ckan.CkanClient',\n spec=ckan.CkanClient)\n self.MockCkanClient = self.patcher.start()\n self.MockCkanClient.return_value = self.c = h.mock_ckan(MOCK_REGISTRY)\n\n def teardown(self):\n self.patcher.stop()\n super(TestLoadController, self).teardown()\n\n def test_packages(self):\n response = self.app.get(url(controller='load', action='packages'))\n\n # Show title for packages\n assert 'The Baz dataset' in response\n\n # Show 'import' link for importable packages\n import_url = url(controller='load', action='start', package='bar')\n assert '' % import_url in response\n\n # Show 'diagnose' link for non-importable packages\n diagnose_url = url(controller='load', action='diagnose', package='baz')\n assert '' % diagnose_url in response\n\n def test_diagnose_valid_package(self):\n response = self.app.get(url(controller='load',\n action='diagnose',\n package='bar'))\n\n assert 'http://example.com/barmodel.js' in response, \\\n \"No link to package model in response!\"\n\n assert 'http://example.com/bardata.csv' in response, \\\n \"No link to package data in response!\"\n\n assert 'error-message' not in response, \\\n \"There was an error-message in response\"\n\n def test_diagnose_broken_package_no_hints(self):\n response = self.app.get(url(controller='load',\n action='diagnose',\n package='foo'))\n\n assert 'None set' in response, \"'None set' not in response!\"\n\n def test_diagnose_broken_package_ambiguous_hints(self):\n response = self.app.get(url(controller='load',\n action='diagnose',\n package='baz'))\n\n assert \"multiple resources with hint 'model'\" in response, \\\n \"No warning about ambiguous resources in response!\"\n\n @h.patch('openspending.ui.lib.authz.have_role')\n def test_start(self, have_role_mock):\n have_role_mock.return_value = True # Pretend to be admin user.\n\n response = self.app.get(url(controller='load',\n action='start',\n package='bar'))\n\n # Redirects to status page\n status_path = url(controller='job', action='status', job_id='import_bar')\n assert response.headers['Location'].endswith(status_path), \\\n \"LoadController start action didn't redirect to status page.\"\n\n assert daemon.job_running('import_bar'), \\\n \"LoadController start action didn't start the import_bar job!\"","sub_path":"etl/ui/test/functional/test_load.py","file_name":"test_load.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"640892722","text":"from selenium import webdriver\r\nfrom selenium.common.exceptions import ElementClickInterceptedException\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom selenium.webdriver.common.by import By\r\nimport telebot\r\nimport time\r\nimport os\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\n\r\nfrom config import token\r\nfrom random import randint, random\r\nimport gspread\r\nfrom oauth2client.service_account import ServiceAccountCredentials\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\n\r\nscope = [\"https://spreadsheets.google.com/feeds\",'https://www.googleapis.com/auth/spreadsheets',\"https://www.googleapis.com/auth/drive.file\",\"https://www.googleapis.com/auth/drive\"]\r\n\r\ncreds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)\r\n\r\nclient = gspread.authorize(creds)\r\n\r\nsheet = client.open('testsheets').sheet1\r\n\r\nbot = telebot.TeleBot(token)\r\n\r\nrubrick_url ={'Транспорт':'transport','Автобусы':'avtobusy','Прицепы / дома на колесах':'pritsepy-doma-na-kolesah','Автозапчасти и аксессуары':'avtozapchasti-i-aksessuary','Мотозапчасти и аксессуары':'motozapchasti-i-aksessuary','Шины, диски и колёса':'shiny-diski-i-kolesa','Запчасти для спец техники':'zapchasti-dlya-spets-sh-tehniki','Прочие запчасти':'prochie-zapchasti','Сельхозтехника':'selhoztehnika','Автомобили из Польши':'avtomobili-iz-polshi','Водный Транспорт':'vodnyy-transport','Грузовые автомобили':'gruzovye-avtomobili','Спецтехника':'spetstehnika','Мото':'moto','Недвижемость':'nedvizhimost', 'Услуги':'uslugi','Запчасти для транспорта':'zapchasti-dlya-transporta','Электроника':'elektronika'}\r\nregion_url ={\"Херсон\":'khe', 'Одесса':'od','Винница':'vin','Волынская область':'vol','Днепропетровск':'dnp','Житомир':'zht','Ивано-Франковск':'if','Киев':'ko','Николаев':'nikolaev_106'}\r\n\r\nrubrick_rus = {'Транспорт':\r\n ['Сельхозтехника','Автобусы','Прицепы/домы на колесах','Автомобили из Польши','Водный транспорт','Другой транспорт','Грузовые автомобили','Спецтехника','Воздушный транспорт','Запчасти для транспорта'],\r\n 'Запчасти для транспорта':\r\n ['Автозапчасти и аксессуары','Мотозапчасти и аксессуары','Шины, диски и колёса','Прочие запчасти','Транспорт','Запчасти для спец техники'],\r\n 'Недвижемость':\r\n ['Квартиры, комнаты','Коммерческая недвижимость','Предложения от застройщиков','Дома','Гаражи, парковки','Недвижимость за рубежом','Земля','Посуточная аренда жилья'],\r\n\r\n }\r\n\r\nregion_rus = ['Херсон', 'Одесса','Винница','Днепропетровск','Киев','Николаев','Житомир','Волынская область','Ивано-Франковск']\r\n\r\nchoosen_rubrick = ''\r\nchoosen_region = ''\r\nPATH = os.path.abspath('chromedriver.exe')\r\n\r\n\r\n\r\n\r\n@bot.message_handler(commands=['start_new_search'])\r\ndef choose_rubr(message):\r\n bot.send_message(message.chat.id, text='Напишите название рубрики из перечисленных: ' +', '.join([r for r in rubrick_rus.keys()]))\r\n bot.register_next_step_handler(message, choose_region)\r\n\r\ndef choose_pod_rubr(message):\r\n bot.send_message(message.vhat.id, 'Выбирите подрубрику из перечисленных: ')\r\n\r\ndef choose_region(message):\r\n global choosen_rubrick\r\n choosen_rubrick=message.text\r\n bot.send_message(message.chat.id, text='Напишите название региона из перечисленных: ' + ' ,'.join([r for r in region_rus]))\r\n bot.register_next_step_handler(message, to_end)\r\ndef to_end(message):\r\n try:\r\n global choosen_region\r\n choosen_region=message.text\r\n bot.send_message(message.chat.id, 'Вы выбрали рубрику - '+choosen_rubrick+' и регион - '+choosen_region)\r\n bot.send_message(message.chat.id, 'Начинаю сбор данных ...')\r\n global choosen_rubrick_url, choosen_region_url\r\n choosen_rubrick_url = rubrick_url[choosen_rubrick]\r\n choosen_region_url = region_url[choosen_region]\r\n b = Bot()\r\n except Exception as e:\r\n bot.send_message(message.chat.id, 'yyyyyyy'+str(e))\r\n\r\n\r\n\r\nclass Bot:\r\n def __init__(self):\r\n\r\n\r\n PROXY = '185.86.76.225:1080'\r\n chrome_options = webdriver.ChromeOptions()\r\n chrome_options.add_argument('--proxy-server=socks5://%s' % PROXY)\r\n\r\n\r\n self.driver = webdriver.Chrome(executable_path=PATH, chrome_options=chrome_options)\r\n self.navigate()\r\n\r\n\r\n def navigate(self):\r\n list_links = []\r\n actions = ActionChains(driver=self.driver)\r\n imwait = self.driver.implicitly_wait(randint(2, 4))\r\n\r\n main_link = 'https://www.olx.ua/'+str(choosen_rubrick_url)+'/'+str(choosen_region_url)+'/'\r\n self.driver.get(main_link)\r\n\r\n pages = self.driver.find_elements_by_xpath('//a[@class=\"block br3 brc8 large tdnone lheight24\"]')\r\n wait = WebDriverWait(self.driver, 5)\r\n pages_list = []\r\n for page in pages:\r\n pages_list.append(page.get_property('href'))\r\n count_pages = len(pages_list)+1\r\n print(count_pages)\r\n for i in range(1,count_pages):\r\n self.driver.get(main_link+'?page={}'.format(i))\r\n offers = self.driver.find_elements_by_xpath('//a[@class=\"marginright5 link linkWithHash detailsLink\"]')\r\n for link in offers:\r\n list_links.append(link.get_attribute('href'))\r\n for link in list_links:\r\n self.driver.execute_script(\"window.scrollTo(0, 150)\")\r\n self.driver.get(link)\r\n time.sleep(randint(2,4))\r\n print('Перешли по ссылке')\r\n\r\n# print('прокрутим страницу')\r\n self.driver.execute_script(\"window.scrollTo(0, 300)\")\r\n print('прокрутили')\r\n try:\r\n time.sleep(randint(2,4))\r\n\r\n print('найдем кнопку')\r\n but_w = wait.until(EC.element_to_be_clickable((By.XPATH, '//div[@data-rel=\"phone\"]')))\r\n but = self.driver.find_element_by_xpath('//div[@data-rel=\"phone\"]')\r\n self.driver.execute_script(\"arguments[0].click();\", but)\r\n but.click()\r\n print('Нажали на кнопку')\r\n\r\n\r\n self.driver.execute_script(\"window.scrollTo(0, 150)\")\r\n time.sleep(randint(2,4))\r\n\r\n\r\n\r\n number = self.driver.find_element_by_xpath('//strong[@class=\"xx-large\"]').text\r\n name = self.driver.find_element_by_tag_name('h4').text\r\n add_to_db(number, name)\r\n time.sleep(randint(2,4))\r\n\r\n self.driver.execute_script(\"window.scrollTo(0, 350)\")\r\n print('Добавили в БД сделали скролл ')\r\n\r\n\r\n #\r\n print('Еще не вернулись назад')\r\n self.driver.execute_script(\"window.scrollTo(0, 350)\")\r\n self.driver.back()\r\n print('вернулись назад')\r\n time.sleep(randint(2,4))\r\n\r\n self.driver.execute_script(\"window.scrollTo(0, 350)\")\r\n except:\r\n time.sleep(3)\r\n self.driver.back()\r\n print('tut vse rabotaet')\r\n print('собрал 1 номер')\r\n\r\ndef in_db(number):\r\n try:\r\n sheet.find(number)\r\n\r\n return True\r\n except:\r\n return False\r\ndef add_to_db(number, name):\r\n if in_db(number):\r\n pass\r\n else:\r\n user_info = [number, name]\r\n sheet.insert_row(user_info)\r\n\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n\r\n bot.polling(none_stop=True)","sub_path":"olx_tel.py","file_name":"olx_tel.py","file_ext":"py","file_size_in_byte":8706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"614084850","text":"import matplotlib.pyplot as plt\n\nx = [1,2,3]\ny = [6,7,8]\n\nz = [1,2,3]\nw = [6,7,8]\n\nplt.title(\"Deaths by mms\")\nplt.xlabel(\"axis x\")\nplt.ylabel(\"axis y\")\nplt.plot(x,y)\nplt.bar(x,y)\nplt.bar(x,y, label=\"orange bars\")\nplt.bar(z,w, label=\"blue bars\")\nplt.show()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222753914","text":"# -------------------------------------------------------------------------\n#\n# Part of the CodeChecker project, under the Apache License v2.0 with\n# LLVM Exceptions. See LICENSE for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n#\n# -------------------------------------------------------------------------\n\"\"\"\nTest the report converter between the common Report type and the\nthrift ReportData type\n\"\"\"\n\nimport unittest\n\nfrom codechecker_common import report\nfrom codechecker_client import report_type_converter\nfrom codechecker_api.codeCheckerDBAccess_v6 import ttypes\n\n\nclass ReportTypeConverterTest(unittest.TestCase):\n \"\"\"Type conversion tests.\"\"\"\n\n def test_Report_to_ReportData(self):\n \"\"\"Report to reportData conversion.\"\"\"\n check_name = \"checker.name\"\n report_hash = \"2343we23\"\n source_file = \"main.cpp\"\n description = \"some checker message\"\n line = 10\n column = 8\n\n main = {\n \"description\": description,\n \"check_name\": check_name,\n \"issue_hash_content_of_line_in_context\": report_hash,\n \"location\": {\"line\": line, \"col\": column, \"file\": 0},\n }\n\n rep = report.Report(main=main,\n bugpath=[],\n files={0: source_file},\n metadata=None)\n\n severity_map = {check_name: \"LOW\"}\n rep_data = report_type_converter.report_to_reportData(rep, severity_map)\n\n self.assertEqual(rep_data.checkerId, rep.check_name)\n self.assertEqual(rep_data.bugHash, rep.report_hash)\n self.assertEqual(rep_data.checkedFile, rep.file_path)\n self.assertEqual(rep_data.line, rep.line)\n self.assertEqual(rep_data.column, rep.col)\n self.assertEqual(rep_data.severity, ttypes.Severity.LOW)\n\n def test_ReportData_to_Report(self):\n \"\"\"ReportData to Report conversion.\"\"\"\n check_name = \"checker.name\"\n report_hash = \"2343we23\"\n source_file = \"main.cpp\"\n description = \"some checker message\"\n line = 10\n column = 8\n\n rep_data = ttypes.ReportData(\n checkerId=check_name,\n bugHash=report_hash,\n checkedFile=source_file,\n checkerMsg=description,\n line=line,\n column=column,\n severity=\"LOW\",\n bugPathLength=5,\n )\n\n rep = report_type_converter.reportData_to_report(rep_data)\n self.assertEqual(rep.check_name, rep_data.checkerId)\n self.assertEqual(rep.report_hash, rep_data.bugHash)\n self.assertEqual(rep.file_path, rep_data.checkedFile)\n self.assertEqual(rep.description, rep_data.checkerMsg)\n self.assertEqual(rep.line, rep_data.line)\n self.assertEqual(rep.col, rep_data.column)\n","sub_path":"web/client/tests/unit/test_report_converter.py","file_name":"test_report_converter.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"54297127","text":"import sys, getopt, os, this\nimport numpy as np \nimport matplotlib.pyplot as plt\nprint('Good coding style is illustrated at: https://docs.python-guide.org/writing/style/')\n\n\nargv = sys.argv\n\ntry:\n opts, args = getopt.getopt(argv[1:], \"a:b:N:title:d:p\",\n [\"a=\", \"b=\", \"N=\", \"title=\", \"d=\"\n , \"p=\"])\n print(opts)\n print(args)\nexcept:\n print('Input variable syntax seems wrong.')\n sys.exit(2)\n \nprint('Input variables are: ')\nfor opt, arg in opts:\n print(opt)\n if opt in (\"-a\", \"--a\"):\n arg_a = arg\n print(arg_a)\n elif opt in (\"-b\", \"--b\"):\n arg_b = arg\n print(arg_b)\n elif opt in (\"-N\", \"--N\"):\n arg_N_vals = arg\n print(arg_N_vals)\n elif opt in (\"-title\", \"--title\"):\n arg_title = arg\n print(arg_title)\n elif opt in (\"-d\", \"--d\"):\n arg_distr_type = arg\n print(arg_distr_type)\n elif opt in (\"-p\", \"--p\"):\n arg_pfname = arg\n print(arg_pfname)\n\n# default values\na = 0\nb = 2\nN_vals = 500\ntitle = 'dummy distribution'\ndistr_type = 'gauss'\npfname = 'dummy_distr_plot'\n\nif 'arg_a' not in locals(): \n arg_a = a # or some other default value.\nelse:\n arg_a = float(arg_a)\n \nif 'arg_b' not in locals(): \n arg_b = b # or some other default value.\nelse:\n arg_b = float(arg_b)\n \nif 'arg_N_vals' not in locals(): \n arg_N_vals = N_vals # or some other default value.\nelse:\n arg_N_vals = int(arg_N_vals)\n\nif 'arg_title' not in locals(): \n arg_title = title # or some other default value.\n\nif 'arg_distr_type' not in locals(): \n arg_distr_type = distr_type # or some other default value.\n\nif 'arg_pfname' not in locals(): \n arg_pfname = pfname # or some other default value.\n \n\nprint('Distribution plotting funtion')\nif arg_distr_type == 'gauss':\n print('Default or not. You chose the gauss distribution')\n print('Therefore -> ' + 'a=mu : ' + str(arg_a) + \n ' & b=sigma : ' + str(arg_b))\n distr_data = np.random.normal(arg_a, arg_b, arg_N_vals)\nelif arg_distr_type == 'uniform':\n print('You chose the uniform distribution')\n print('Therefore -> ' + 'a=mu : ' + str(arg_a) +\n ' & b=sigma : ' + str(arg_b))\n distr_data = np.random.uniform(arg_a, arg_b, arg_N_vals)\n\nelif arg_distr_type == 'lognormal':\n print('Default or not. You chose the lognormal distribution')\n print('Therefore -> ' + 'a=alpha : ' + str(arg_a) +\n ' & b=beta : ' + str(arg_b))\n distr_data = np.random.lognormal(arg_a, arg_b, arg_N_vals)\n\n\n\nuser_path = input('Where to plot?\\n')\n\nif os.path.exists(user_path):\n print('Nice folder...')\nelse:\n os.mkdir(user_path)\n\n\nplt.cla()\nplt.hist(distr_data, bins=150)\nplt.ylabel('Probability')\nplt.title(arg_title)\nplot_fname = user_path + arg_pfname + '.png'\nprint(plot_fname)\nplt.savefig(plot_fname, dpi=150)\n\n\n### Get envorimental variables for technical reasons\n#import os\n#for name, value in os.environ.items():\n# print(\"{0}: {1}\".format(name, value))\n\n\nprint('Good coding style is illustrated at: https://docs.python-guide.org/writing/style/')\n\n### Dictionaries looping\n#ROIs = {'temporal_lobe': str(1152) + 'vertices', 'occipital_lobe': str(10) + 'vertices'}\n\n#for k, v in ROIs.items():\n#\n# print(k, v)\n\n### Multiple assignment\n#a,b,c = 3,5,999\n\n","sub_path":"dv_distr_plotter2.py","file_name":"dv_distr_plotter2.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179660807","text":"import RPi.GPIO as GPIO\nimport time\n\nLWAY = 1\nMWAY = 2\n\ndataPin = 11 #DS Pin of 74HC595(Pin14)\nlatchPin = 13 #ST_CP Pin of 74HC595(Pin12)\nclockPin = 15 #CH_CP Pin of 74HC595(Pin11)\n\ndef setup():\n GPIO.setmode(GPIO.BOARD) \n GPIO.setup(dataPin,GPIO.OUT)\n GPIO.setup(latchPin,GPIO.OUT)\n GPIO.setup(clockPin,GPIO.OUT)\n\ndef sendout(dPin,cPin,way,val):\n for i in range(0,8):\n GPIO.output(cPin,GPIO.LOW)\n if(way == LWAY):\n GPIO.output(dPin,(0x01 & (val>>i)==0x01) and GPIO.HIGH or GPIO.LOW)\n elif(way == MWAY):\n GPIO.output(dPin,(0x80 & (val<>=1 # make the variable move one bit to left once, then the bright LED move one step to the left once.\n time.sleep(0.1)\n time.sleep(0.5)\n\ndef destroy(): # When 'Ctrl+C' is pressed, the function is executed.\n GPIO.cleanup()\n\nif __name__ == '__main__': # Program starting from here\n print(\"starting...\")\n setup()\n try:\n loop()\n except KeyboardInterrupt:\n destroy()","sub_path":"code/python/15.74HC595LED/74HC595LED.py","file_name":"74HC595LED.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629902046","text":"##########################################################################################\n# #\n# Created by Endymion D. Cooper (endymion.dante.cooper@gmail.com) #\n# This is version 1.1 created on 2nd Sept 2015 #\n# #\n# Modified from version 1.0 (25th August 2015) to incorporate a second method for #\n# calculating the per duplication KS value (see details of modes below). #\n# #\n# reduce_redundant_KS.py takes a set of pairwise KS values for clustered sequences #\n# and uses a UPGMA like clustering method (following Maere et al. PNAS 2005 #\n# DOI:10.1073/pnas.0501102102) to approximate gene duplications and reduce redundant # \n# KS values. #\n# #\n# Maere et al. (2005) Supporting methods: #\n# #\n# \" Correction for redundant KS values. #\n# A gene family of n members originates from n-1 retained single gene #\n# duplications, whereas the number of possible pairwise comparisons (KS #\n# measurements) within a gene family is n(n-1)/2. To correct for the #\n# redundancy of KS values when building the age distribution for duplicated #\n# genes, we constructed tentative phylogenetic trees for each gene family #\n# with an average linkage clustering algorithm using KS as a distance #\n# measure, similar to the approach adopted by Blanc and Wolfe (1). Starting #\n# from each gene as a separate cluster, the two clusters with the lowest #\n# mean inter-cluster KS value (i.e. the mean of all observed KS values #\n# (edges) between two clusters) were iteratively merged. The splits in #\n# the resulting average linkage tree represent the n-1 retained duplication #\n# events. For each split, the m KS measurements between the two merged #\n# gene clusters were added to the KS distribution with a weight 1/m. In #\n# other words, all KS estimates for a particular duplication event were #\n# added to the KS distribution, while the total weight of a single #\n# duplication event sums up to one. \" #\n# #\n# #\n# Dependancies: written for python 2.7, builtins and standard libraries. #\n# #\n# Usage: python reduce_redundant_KS.py #\n# #\n# The input file lines should look like this (tab separated): #\n# #\n# #\n# Two outputs are generated: #\n# 1. _KS_by_cluster.txt #\n# 2. _KS.txt #\n# #\n# Two methods of calculating mean KS between sub-clusters are available. #\n# Specify M1 (mode 1) or M2 (mode 2). #\n# The differences are explained below with an example. #\n# #\n# Example data: #\n# #\n# cluster1 G1 G2 0.003 #\n# cluster1 G1 G3 0.326 #\n# cluster1 G1 G4 0.563 #\n# cluster1 G2 G3 0.245 #\n# cluster1 G2 G4 0.637 #\n# cluster1 G3 G4 0.476 #\n# #\n# Denote: - the KS score between two sequences/subclusters as e.g. G1:G2. #\n# - a subcluster of sequences as e.g. G1/2 #\n# #\n# First iteration: #\n# The smallest KS value is between G1 & G2 therefore join as G1/2. Tree: #\n# G1 __ #\n# G2 __| <-- Duplication event 1. KS score G1:G2 = 0.003 #\n# G3 #\n# G4 #\n# And recalculate the KS scores by averaging (note that mode 1 = mode 2 here): #\n# ------------------------------------------------------------------------- #\n# | New Pairs | Mode 1 | Mode 2 | #\n# |-----------|------------------------------|------------------------------| #\n# | G1/2 G3 | ((G1:G3)+(G2:G3))/2 = 0.2855 | ((G1:G3)+(G2:G3))/2 = 0.2855 | #\n# | G1/2 G4 | ((G1:G4)+(G2:G4))/2 = 0.6 | ((G1:G4)+(G2:G4))/2 = 0.6 | #\n# | G3 G4 | (raw value) = 0.476 | (raw value) = 0.476 | #\n# ------------------------------------------------------------------------- #\n# Second iteration: #\n# The smallest KS value is between G1/2 and G3 therefore join as G1/2/3. Tree: #\n# G1 __ #\n# G2 __|__ #\n# G3 _____| <-- Duplication event 2. KS score G1/2:G3 = 0.2855 #\n# G4 #\n# And recalculate the KS scores by averaging (mode 1 =/= mode 2): #\n# ---------------------------------------------------------------------------------- #\n# | New Pairs | Mode 1 | Mode 2 | #\n# |------------|-------------------------------------|-------------------------------| #\n# | G1/2/3 G4 | ((G1:G4)+(G2:G4)+(G3:G4))/3 = 0.559 | ((G1/2:G4)+(G3:G4))/2 = 0.538 | #\n# ---------------------------------------------------------------------------------- #\n# #\n# Third iteration 3: #\n# The smallest KS value is between G1/2/3 and G4 therefore join as G1/2/3/4. Tree: #\n# G1 __ #\n# G2 __|__ #\n# G3 _____|__ #\n# G4 ________| <-- Duplication event 3. KS score G1/2/3:G4 = 0.559 (mode 1) #\n# = 0.538 (mode 2) #\n# #\n##########################################################################################\n\nimport sys\n\n# Parse command line arguments.\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\nmode = sys.argv[3]\n\n# First open the file and read the lines, store the data in a dictionary indexed by \n# cluster name, with values as a list of lines for each cluster\nfile = open(input_file, 'r')\nlines = file.readlines()\nfile.close()\ndata_dict = {}\nfor line in lines:\n if line.startswith('\\n'):\n continue\n else:\n L1 = line.rstrip('\\n')\n L2 = L1.split('\\t')\n if L2[0] not in data_dict:\n data_dict[L2[0]]=[L2]\n else:\n data_dict[L2[0]].append(L2)\n\n# Define the primary function to do the clustering and extract the \n# non-redundant KS values for each blast cluster.\ndef remove_redundant_KS(lines):\n # list to hold current clusters\n clusters = []\n # list to hold sequence names\n sequences = []\n # dictionary to hold cluster definitions\n cluster_defs = {}\n # dictionary to hold all KS scores\n all_KS = {}\n # dictionary to hold KS scores for current clusters\n current_KS = {}\n # list for final KS scores\n KS = []\n # a counter to append to subcluster IDs\n counter = 0\n\n # populate the lists and dictionaries with initial values.\n for line in lines:\n L2 = line\n L3 = frozenset([L2[1],L2[2]])\n # populate the KS value dictionary\n all_KS[L3] = L2[3]\n # populate the cluster and sequence lists\n if L2[1] not in clusters:\n clusters.append(L2[1])\n sequences.append(L2[1])\n if L2[2] not in clusters:\n clusters.append(L2[2])\n sequences.append(L2[2])\n # populate the cluster definitions\n for i in xrange(0,len(clusters)):\n cluster_defs[clusters[i]]=[clusters[i]]\n\n # define a function to get the KS scores for the current clusters\n # KS scores are held in a dictionary and sent to get_min_KS to extract the smallest KS value\n def get_current_KS():\n dict = {}\n temp = []\n for x in xrange(0,len(clusters)):\n for y in xrange(0,len(clusters)):\n if x != y:\n # This is the simplest case.\n if frozenset([clusters[x],clusters[y]]) in all_KS:\n if frozenset([clusters[x],clusters[y]]) not in dict:\n dict[frozenset([clusters[x],clusters[y]])] = all_KS[frozenset([clusters[x],clusters[y]])]\n else:\n continue\n # Here for merged clusters. Put pairs in temporary list. \n else:\n if frozenset([clusters[x],clusters[y]]) not in temp:\n temp.append(frozenset([clusters[x],clusters[y]]))\n else:\n continue\n else:\n continue\n # For merged clusters, calculate the mean of all KS between clusters.\n for key in temp:\n pairs = []\n values = []\n # Values in first cluster of pair\n for x in xrange(0,len(cluster_defs[list(key)[0]])):\n # Values in second cluster of pair\n for y in xrange(0,len(cluster_defs[list(key)[1]])):\n combi = frozenset([list(cluster_defs[list(key)[0]])[x],list(cluster_defs[list(key)[1]])[y]])\n if combi not in pairs:\n pairs.append(combi) \n values.append(float(all_KS[combi]))\n dict[key]=str(sum(values)/len(values))\n # If mode is M2 we update all_KS to treat subclusters as if they were terminal sequences for next iteration.\n if mode == 'M2':\n \tall_KS[key]=str(sum(values)/len(values))\n # If mode is M2 we update cluster definitions to treat subclusters as if they were terminal sequences for next iteration.\n if mode == 'M2':\n \tfor i in xrange(0,len(clusters)):\n \t\tcluster_defs[clusters[i]]=[clusters[i]]\n return dict\n\n # get the min KS in current clustering\n def get_min_KS(ks_dict):\n min_KS = {}\n pair = min(ks_dict, key = ks_dict.get)\n min_KS[pair] = ks_dict[pair]\n # Append the KS score to the final list of KS scores.\n KS.append(ks_dict[pair])\n return min_KS\n\n # update the current clusters\n # having identified the smallest KS, those sequences/sub-clusters are merged and the cluster list modified.\n def update_clusters(cluster_list,min_KS):\n temp = []\n new_clusters = []\n for x in xrange(0,len(clusters)):\n for key in min_KS:\n # If KS value for a pair of sequences.\n if list(key)[0] in sequences and list(key)[1] in sequences:\n cluster_defs[\"sub_clust_\"+str(counter)]=list(key)\n if clusters[x] in list(key):\n temp.append(clusters[x])\n else:\n continue\n # If KS value for a sequence and a cluster of sequences.\n elif list(key)[0] in sequences or list(key)[1] in sequences:\n seq_list = []\n if list(key)[1] in sequences:\n seq_list.append(str(list(key)[1]))\n if len(cluster_defs[list(key)[0]]) > 1:\n for y in xrange(0,len(cluster_defs[list(key)[0]])):\n if cluster_defs[list(key)[0]][y] not in seq_list:\n seq_list.append(cluster_defs[list(key)[0]][y])\n if list(key)[0] in sequences:\n seq_list.append(str(list(key)[0]))\n if len(cluster_defs[list(key)[1]]) > 1:\n for y in xrange(0,len(cluster_defs[list(key)[1]])):\n if cluster_defs[list(key)[1]][y] not in seq_list:\n seq_list.append(cluster_defs[list(key)[1]][y])\n cluster_defs[\"sub_clust_\"+str(counter)]=seq_list\n if clusters[x] in list(key):\n temp.append(clusters[x])\n else:\n continue\n # If KS value for two clusters of sequences.\n else:\n seq_list = []\n if len(cluster_defs[list(key)[0]]) > 1:\n for y in xrange(0,len(cluster_defs[list(key)[0]])):\n if cluster_defs[list(key)[0]][y] not in seq_list:\n seq_list.append(cluster_defs[list(key)[0]][y])\n if len(cluster_defs[list(key)[1]]) > 1:\n for y in xrange(0,len(cluster_defs[list(key)[1]])):\n if cluster_defs[list(key)[1]][y] not in seq_list:\n seq_list.append(cluster_defs[list(key)[1]][y])\n cluster_defs[\"sub_clust_\"+str(counter)]=seq_list\n if clusters[x] in list(key):\n temp.append(clusters[x])\n else:\n continue\n for y in xrange(0,len(clusters)):\n if clusters[y] not in temp:\n new_clusters.append(clusters[y])\n else:\n if \"sub_clust_\"+str(counter) not in new_clusters:\n new_clusters.append(\"sub_clust_\"+str(counter))\n return new_clusters\n\n # An iterator to sequentially merge sequences/sub-clusters with shortest KS.\n while len(clusters) > 1:\n # if mode is M2 we update the sequence list so sub-clusters are treated as terminal sequences in next iteration.\n if mode == 'M2':\n \tsequences = clusters\n counter = counter + 1\n current_KS = get_current_KS()\n min_KS = get_min_KS(current_KS)\n clusters = update_clusters(clusters,min_KS)\n return KS\n\n# Open output files.\nOUT1 = open(output_file+\"_KS_by_cluster.txt\", \"w\")\nOUT2 = open(output_file+\"_KS.txt\", \"w\")\n\n# Call main function and write results to outputs.\nfor key in data_dict:\n KS = remove_redundant_KS(data_dict[key])\n print >> OUT1,key,KS\n for i in xrange(0,len(KS)):\n \tprint >> OUT2,KS[i]\n \n# Close output files.\nOUT1.close()\nOUT2.close()\n \n \t\n","sub_path":"reduce_redundant_KS.py","file_name":"reduce_redundant_KS.py","file_ext":"py","file_size_in_byte":17143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"316622536","text":"import scrapy\nimport re\nimport json\nimport demjson\nfrom instagram.items import InstagramItem\nimport urllib.parse\nfrom ..root_urls import query_hash,ins_name,ins_username,ins_password\n\nclass InsSpider(scrapy.Spider):\n name = 'ins2'\n\n loggin_urls = 'https://www.instagram.com/accounts/login/ajax/'\n urls = 'https://www.instagram.com/{}/'\n starturl = 'https://www.instagram.com/'\n img_url = 'https://www.instagram.com/p/{}/?__a=1'\n query_hash = query_hash#非常关键需要手动去浏览器xhr查找 从而限制了批量操作\n next_urls = f'https://www.instagram.com/graphql/query/?query_hash={query_hash}'\n\n allowed_domains = ['instagram.com']\n start_urls = [ins_name]\n\n headers = {\n 'origin': \"www.instagram.com\",\n 'accept-encoding': \"gzip, deflate, br\",\n 'accept-language': \"ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\",\n 'x-requested-with': \"XMLHttpRequest\",\n 'x-csrftoken': \"\",\n 'x-instagram-ajax': \"de81cb3fd9c4-hot\",\n 'content-type': \"application/x-www-form-urlencoded\",\n 'accept': \"*/*\",\n 'referer': \"https://www.instagram.com/accounts/login\"\n\n}\n\n def start_requests(self):\n\n for name in self.start_urls:\n user_url = self.urls.format(name)\n yield scrapy.Request(user_url, headers=self.headers, callback=self.loggin, meta={'cookiejar': 1,'name':name})\n\n def loggin(self,response):\n name = response.meta['name']\n cook = response.headers.getlist('Set-Cookie')[0].decode()\n cook = cook.split(';')[0].split('=')[1]\n self.headers['x-csrftoken'] = cook\n print(cook)\n data = {'username': ins_username,\n 'password': ins_password,\n 'queryParams': \"{}\"}\n yield scrapy.FormRequest(self.loggin_urls, formdata=data, headers=self.headers,callback=self.after_logged, meta={'cookiejar': 1,'name':name})\n\n def after_logged(self,response):\n name = response.meta['name']\n user_url = self.urls.format(name)\n yield scrapy.Request(user_url, headers=self.headers, callback=self.parse_firstpage, meta={'cookiejar': 1, 'name': name},dont_filter=True)\n\n def parse_firstpage(self,response):\n name = response.meta['name']\n content = response.text\n cont = content.split('window._sharedData = ')[1].split(\";\")[0]\n\n js = demjson.decode(cont)\n entry_data= js['entry_data']['ProfilePage'][0]\n user = entry_data['graphql']['user']\n id = user['id']\n edge_owner_to_timeline_media = user['edge_owner_to_timeline_media']\n end_cursor = edge_owner_to_timeline_media['page_info']['end_cursor']\n edges = edge_owner_to_timeline_media['edges']\n print(id,end_cursor)\n\n for edge in edges:\n shortcode = edge['node']['shortcode']\n\n yield scrapy.Request(url=self.img_url.format(shortcode), callback=self.parse_img, headers=self.headers,meta={'cookiejar': 1,'name':name})\n\n ss = '{\"id\":\"'+id+'\",\"first\":12,\"after\":\"'+end_cursor+'\"}'\n fs = urllib.parse.quote(ss)\n\n next_url = self.next_urls+f'&variables={fs}'\n\n yield scrapy.Request(url=next_url, callback=self.parse_next, headers=self.headers,\n meta={'cookiejar': 1, 'name': name,'id':id})\n #\n def parse_next(self, response):\n name = response.meta['name']\n id = response.meta['id']\n js = json.loads(response.text)\n\n datas = js[\"data\"][\"user\"][\"edge_owner_to_timeline_media\"]\n\n edges = datas['edges']\n print(len(edges))\n for edge in edges:\n shortcode = edge['node']['shortcode']\n yield scrapy.Request(url=self.img_url.format(shortcode), callback=self.parse_img, headers=self.headers,\n meta={'cookiejar': 1, 'name': name})\n\n page_info = datas['page_info']\n has_next_page = page_info['has_next_page']\n end_cursor = page_info['end_cursor']\n print(end_cursor)\n print(has_next_page)\n\n if has_next_page:\n next_url = self.next_urls+'&variables={\"id\":\"'+id+'\",\"first\":50,\"after\":\"'+end_cursor+'\"}'\n yield scrapy.Request(url=next_url, callback=self.parse_next, headers=self.headers,\n meta={'cookiejar': 1, 'name': name,'id':id})\n\n def parse_img(self,response):\n\n item = InstagramItem()\n name = response.meta['name']\n js = json.loads(response.text)\n\n try:\n sidecar = js[\"graphql\"][\"shortcode_media\"][\"edge_sidecar_to_children\"]\n for side in sidecar[\"edges\"]:\n img = side['node']['display_url']\n item['name'] = name\n item['image_urls'] = [img]\n yield item\n\n except:\n img = js[\"graphql\"][\"shortcode_media\"]['display_url']\n item['name'] = name\n item['image_urls'] = [img]\n yield item\n\n\n #\n","sub_path":"instagram/spiders/ins2.py","file_name":"ins2.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265749771","text":"class Szemely: # osztály neve nagybetűvel\r\n veznev=''\r\n kernev=''\r\n kor=''\r\n\r\nsz1=Szemely\r\nsz1.veznev='Kis'\r\nsz1.kernev='Malac'\r\nsz1.kor=8\r\n\r\nprint(sz1.veznev)\r\nprint(sz1.kernev)\r\nprint(sz1.kor)\r\n\r\nsz2=Szemely\r\nsz2.veznev='Cirmos'\r\nsz2.kernev='Ceca'\r\nsz2.kor=2\r\n\r\nprint(sz2.veznev)\r\nprint(sz2.kernev)\r\nprint(sz2.kor)","sub_path":"python/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"510188426","text":"from operator import itemgetter\nfrom mince.effects import StaticFX\nfrom mince.effects import linear, smooth_step, smoother_step\nfrom mince import Colour\nimport random\n\nclass RainbowFX(StaticFX):\n def __init__(self, runner, wait=0.01, reverse=True, single=False):\n super(RainbowFX, self).__init__(runner)\n self.wait = wait\n self.offset = 0\n self.last_update = wait\n self.reverse = reverse\n self.single = single\n\n def _output_lights(self):\n if self.single:\n output = [Colour.wheel((self.offset * 256 / self.runner.num_lights)\n % 256)] * self.runner.num_lights\n else:\n output = []\n for i in range(self.runner.num_lights):\n output.append(Colour.wheel(((i * 256 / self.runner.num_lights) +\n self.offset) % 256))\n\n # Update lights\n if self.reverse:\n output.reverse()\n self.runner.lights.set_lights(output)\n self.runner.lights.write()\n\n def run(self, delta):\n # Constantly display lights\n self._output_lights()\n\n # Frame skip\n self.last_update += delta\n while self.last_update > self.wait:\n self.last_update -= self.wait\n self.offset -= 1\n self.offset = self.offset % 256\n\n\nclass GradientFX(StaticFX):\n def __init__(self, runner, colours=None, wait=0.01, smooth=4, reverse=True,\n single=False, offsets=None):\n super(GradientFX, self).__init__(runner)\n self.wait = wait / float(smooth)\n self.last_update = wait\n self.smooth = smooth\n self.reverse = reverse\n self.single = single\n\n num_lights = runner.num_lights\n\n if offsets is None:\n self.offset = [0] * num_lights\n else:\n self.offset = offsets\n\n # Interpolate colours\n if colours is None:\n colours = [Colour(0, 0, 0), Colour(255, 255, 255)]\n\n # Copy colours\n colours = [c for c in colours]\n colours.append(colours[0])\n num_colours = len(colours)\n\n stops = [0]\n step = float(num_lights * smooth) / (num_colours - 1)\n for i in range(num_colours - 2):\n stops.append(int(round((i + 1) * step, 0)))\n stops.append((num_lights * smooth) - 1)\n\n output = []\n for i in range(num_colours - 1):\n a, b = stops[i], stops[i+1]\n colour_a, colour_b = colours[i], colours[i+1]\n stop_step = 1.0 / (b - a)\n for j in range(a, b):\n colour = self._interp(colour_a, colour_b, stop_step * (j - a))\n output.append(colour)\n output.append(colours[-1])\n self.colours = output\n\n def _interp(self, colour_a, colour_b, weight):\n r = linear(colour_a.red, colour_b.red, weight)\n g = linear(colour_a.green, colour_b.green, weight)\n b = linear(colour_a.blue, colour_b.blue, weight)\n return Colour(int(r), int(g), int(b))\n\n def _output_lights(self):\n if self.single:\n index = self.offset[0] % (self.runner.num_lights * self.smooth)\n colour = self.colours[index]\n output = self.runner.num_lights * [colour]\n else:\n output = []\n for i in range(self.runner.num_lights):\n index = i * self.smooth\n index -= self.offset[i]\n index %= (self.runner.num_lights * self.smooth)\n output.append(self.colours[index])\n\n # Update lights\n if self.reverse:\n output.reverse()\n self.runner.lights.set_lights(output)\n self.runner.lights.write()\n\n def run(self, delta):\n # Constantly display lights\n self._output_lights()\n\n # Frame skip\n self.last_update += delta\n while self.last_update > self.wait:\n self.last_update -= self.wait\n\n for i in range(self.runner.num_lights):\n self.offset[i] += 1\n self.offset[i] = self.offset[i] % (self.smooth * self.runner.num_lights)\n\n\nclass ColourTwinkleFX(GradientFX):\n def __init__(self, runner, colours=None, wait=0.01, smooth=4, reverse=True):\n offsets = [random.randint(0, (runner.num_lights * smooth) - 1) for _ in\n range(runner.num_lights)]\n super(ColourTwinkleFX, self).__init__(runner, colours=colours,\n wait=wait, smooth=smooth, reverse=reverse, offsets=offsets)\n\n\nclass ShiftFX(StaticFX):\n def __init__(self, runner, pattern=None, wait=0.5, reverse=True):\n super(ShiftFX, self).__init__(runner)\n self.pattern = pattern\n self.wait = wait\n self.offset = 0\n self.len_pattern = len(pattern)\n self.last_update = wait\n self.reverse = reverse\n\n def _gen_output(self):\n output = []\n for i in range(self.runner.num_lights):\n idx = (i + self.offset) % self.len_pattern\n output.append(self.pattern[idx])\n return output\n\n def _output_lights(self):\n output = self._gen_output()\n\n # Update lights\n if self.reverse:\n output.reverse()\n self.runner.lights.set_lights(output)\n self.runner.lights.write()\n\n def run(self, delta):\n # Constantly display lights\n self._output_lights()\n\n # Frame skip\n self.last_update += delta\n while self.last_update > self.wait:\n self.last_update -= self.wait\n self.offset += 1\n self.offset = self.offset % self.len_pattern\n\n\nclass RandomColourShiftFX(StaticFX):\n def __init__(self, runner, pattern=None, wait=0.5, reverse=True):\n super(RandomColourShiftFX, self).__init__(runner)\n self.wait = wait\n self.last_update = wait\n self.reverse = reverse\n\n # Setup cumulative probability distribution\n probs = sorted(pattern, key=itemgetter(1))\n self.cum = []\n total = 0\n for col, prob in probs:\n total += prob\n self.cum.append((col, total))\n\n # Generate initial colours\n self.colours = []\n for i in range(self.runner.num_lights):\n self.colours.append(self._gen_colour())\n\n def _output_lights(self):\n output = [c for c in self.colours]\n\n # Update lights\n if self.reverse:\n output.reverse()\n self.runner.lights.set_lights(output)\n self.runner.lights.write()\n\n def _gen_colour(self):\n i = random.random()\n\n for c, p in self.cum:\n if i <= p:\n return c\n return self.cum[-1][0]\n\n def run(self, delta):\n # Constantly display lights\n self._output_lights()\n\n # Frame skip\n self.last_update += delta\n while self.last_update > self.wait:\n self.last_update -= self.wait\n\n # Pop\n self.colours.pop()\n self.colours.insert(0, self._gen_colour())\n\n\n","sub_path":"mince/effects/colour.py","file_name":"colour.py","file_ext":"py","file_size_in_byte":6967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"159748998","text":"import math\r\nimport random\r\n\r\nhard_of_level = int(input())\r\n\r\n\r\nclass Boss:\r\n HP = 9999999999\r\n armor = 9999999999\r\n damage = 9999999999\r\n\r\n def __init__(self, hard_of_level):\r\n if hard_of_level == 1:\r\n self.HP = 150000\r\n self.armor = 0\r\n self.damage = 1250\r\n elif hard_of_level == 2:\r\n self.HP = 500000\r\n self.armor = 500\r\n self.damage = 2500\r\n elif hard_of_level == 3:\r\n self.HP = 1000000\r\n self.armor = 2000\r\n self.damage = 7500\r\n\r\n def taking_damage(self, hard_of_level):\r\n if hard_of_level != 3:\r\n if pc.damage - (self.armor - pc.physical_penetration) > 0:\r\n self.HP -= (pc.damage - (self.armor - pc.physical_penetration))\r\n else:\r\n if random.choice([True, False]):\r\n if pc.damage - (self.armor - pc.physical_penetration) > 0:\r\n self.HP -= (pc.damage - (self.armor - pc.physical_penetration))\r\n def giving_damage(self):\r\n pc.taking_damage()\r\n\r\n\r\nclass miniBoss:\r\n HP = 9999999999\r\n armor = 9999999999\r\n damage = 9999999999\r\n\r\n def __init__(self, hard_of_level):\r\n if hard_of_level == 1:\r\n self.HP = 15000\r\n self.armor = 0\r\n self.damage = 125\r\n elif hard_of_level == 2:\r\n self.HP = 50000\r\n self.armor = 50\r\n self.damage = 250\r\n elif hard_of_level == 3:\r\n self.HP = 100000\r\n self.armor = 200\r\n self.damage = 750\r\n\r\n def taking_damage(self, hard_of_level):\r\n if hard_of_level != 3:\r\n if pc.damage - (self.armor - pc.physical_penetration) > 0:\r\n self.HP -= (pc.damage - (self.armor - pc.physical_penetration))\r\n else:\r\n if random.choice([True, False]):\r\n if pc.damage - (self.armor - pc.physical_penetration) > 0:\r\n self.HP -= (pc.damage - (self.armor - pc.physical_penetration))\r\n\r\n def giving_damage(self):\r\n pc.taking_damage()\r\n\r\n\r\nclass Player_characters:\r\n HP = 1\r\n armor = 1\r\n damage = 1\r\n vampirizm = 0\r\n regen = 1\r\n death = 0\r\n SHP = HP\r\n dod = 0\r\n physical_penetration = 0\r\n\r\n def __init__(self, hard_of_level):\r\n if hard_of_level == 1:\r\n self.SHP = 100\r\n self.HP = self.SHP\r\n self.armor = 200\r\n self.damage = 100\r\n self.regen = 25\r\n elif hard_of_level == 2:\r\n self.SHP = 50\r\n self.HP = self.SHP\r\n self.armor = 100\r\n self.damage = 20\r\n self.regen = 4\r\n elif hard_of_level == 3:\r\n self.SHP = 10\r\n self.HP = self.SHP\r\n self.armor = 50\r\n self.damage = 0\r\n self.regen = 1\r\n\r\n def taking_damage(self):\r\n if Boss.damage - self.armor > 0:\r\n self.HP -= (Boss.damage - self.armor)\r\n\r\n def giving_damage(self, hero):\r\n hero.taking_damage()\r\n if self.damage - hero.armor > 0:\r\n self.HP += ((self.damage - hero.armor) * (self.vampirizm / 100))\r\n self.HP = math.ceil(self.HP)\r\n if hero.HP <= 50 and self.dod > 0:\r\n self.dod = 0\r\n self.damage = math.ceil(self.damage * 1.25)\r\n\r\n def kill(self):\r\n if self.death > 0 and self.HP > 0:\r\n self.death -= 1\r\n self.SHP = self.SHP * 0.15\r\n self.HP = self.SHP\r\n else:\r\n pass # допиши это конец ишры\r\n\r\n def all_characters(self):\r\n print(str(self.HP) + '/' + str(self.SHP) + 'HP')\r\n print('Защита:', pc.armor)\r\n print('Урон:', pc.damage)\r\n print('Вампиризм', pc.vampirizm)\r\n print('Реген:', pc.regen)\r\n print('Жизней:', pc.death)\r\n print('Физ-проникновение:', pc.physical_penetration)\r\n\r\ndef blade_of_despair():\r\n pc.dod += 1\r\n pc.damage += 170\r\n\r\n\r\ndef blade_of_the_seven_seas():\r\n pc.damage += 65\r\n pc.SHP += 250\r\n pc.physical_penetration += 15\r\n\r\n\r\ndef berserker_rage():\r\n\r\n pc.damage += 65\r\n\r\n pc.damage = math.ceil(pc.damage * 1.25)\r\n\r\n\r\n\r\n\r\n\r\ndef axe_of_bloodlust():\r\n\r\n pc.damage += 70\r\n\r\n pc.vampirizm += 20\r\n\r\n\r\n\r\n\r\n\r\ndef endless_battle():\r\n\r\n pc.damage += 65\r\n\r\n pc.SHP += 250\r\n\r\n pc.vampirizm += 15\r\n\r\n\r\n\r\n\r\n\r\ndef claws_of_chaos():\r\n\r\n pc.damage += 70\r\n\r\n pc.vampirizm += 20\r\n\r\n\r\n\r\n\r\n\r\ndef nature_wind():\r\n\r\n pc.damage += 10\r\n\r\n pc.vampirizm += 15\r\n\r\n\r\n\r\n\r\n\r\ndef armor_blade():\r\n\r\n pc.armor += 90\r\n\r\n\r\n\r\n\r\n\r\ndef benefit_of_courage():\r\n\r\n pc.SHP += 770\r\n\r\n pc.vampirizm += 45\r\n\r\n pc.armor = math.ceil(pc.armor * 1.1)\r\n\r\n pc.damage = math.ceil(pc.damage * 1.1)\r\n\r\n\r\n\r\n\r\n\r\ndef caller_of_the_devil():\r\n\r\n pc.damage += 15\r\n\r\n pc.SHP += 770\r\n\r\n\r\n\r\n\r\n\r\ndef forse_of_ice():\r\n\r\n pc.damage += 30\r\n\r\n pc.SHP += 1000\r\n\r\n\r\n\r\n\r\n\r\ndef trident():\r\n\r\n pc.damage += 80\r\n\r\n\r\n\r\n\r\n\r\ndef golden_meteor():\r\n\r\n pc.damage += 60\r\n\r\n pc.vampirizm += 5\r\n\r\n\r\ndef a_shot_of_the_hunter():\r\n pc.damage += 80\r\n\r\n\r\ndef the_Golden_stick():\r\n pc.damage += 100\r\n\r\n\r\ndef the_giants_axe():\r\n pc.damage += 30\r\n pc.SHP += 250\r\n\r\n\r\ndef the_sword_of_the_legionnaire():\r\n pc.damage += 60\r\n\r\n\r\ndef dagger():\r\n pc.damage += 15\r\n\r\n\r\ndef an_ordinary_spear():\r\n pc.damage += 40\r\n\r\n\r\ndef hammer_of_wrath():\r\n pc.damage += 35\r\n pc.physical_penetration += 15\r\n\r\n\r\ndef an_angry_growl():\r\n pc.damage += 60\r\n pc.physical_penetration += 40\r\n\r\n\r\ndef health_crystal():\r\n pc.SHP += 230\r\n\r\n\r\ndef leather_armor():\r\n pc.armor += 15\r\n\r\n\r\ndef healing_necklace():\r\n pc.regen += 20\r\n\r\n\r\ndef the_belt_of_ares():\r\n pc.SHP += 770\r\n\r\n\r\ndef studded_armor():\r\n pc.armor += 90\r\n\r\n\r\ndef queens_wings():\r\n pc.SHP += 1000\r\n pc.damage += 15\r\n\r\n\r\ndef storm_belt():\r\n pc.SHP += 800\r\n pc.armor += 40\r\n\r\n\r\ndef protective_helmet():\r\n pc.SHP += 1550\r\n pc.regen += 100\r\n\r\n\r\ndef immortality():\r\n pc.armor += 40\r\n pc.SHP += 800\r\n pc.death += 1\r\n\r\n\r\ndef what_the_item(item):\r\n if item == 'a':\r\n axe_of_bloodlust()\r\n elif item == 'b':\r\n berserker_rage()\r\n elif item == 'c':\r\n blade_of_despair()\r\n elif item == 'd':\r\n blade_of_the_seven_seas()\r\n elif item == 'e':\r\n claws_of_chaos()\r\n elif item == 'g':\r\n endless_battle()\r\n elif item == 'f':\r\n nature_wind()\r\n elif item == 'h':\r\n a_shot_of_the_hunter()\r\n elif item == 'i':\r\n an_ordinary_spear()\r\n elif item == 'j':\r\n armor_blade()\r\n elif item == 'k':\r\n benefit_of_courage()\r\n elif item == 'l':\r\n caller_of_the_devil()\r\n elif item == 'm':\r\n dagger()\r\n elif item == 'n':\r\n golden_meteor()\r\n elif item == 'o':\r\n hammer_of_wrath()\r\n elif item == 'p':\r\n healing_necklace()\r\n elif item == 'q':\r\n health_crystal()\r\n elif item == 'r':\r\n leather_armor()\r\n elif item == 's':\r\n queens_wings()\r\n elif item == 'u':\r\n storm_belt()\r\n elif item == 'v':\r\n studded_armor()\r\n elif item == 'w':\r\n the_Golden_stick()\r\n elif item == 'x':\r\n the_giants_axe()\r\n elif item == 'y':\r\n the_sword_of_the_legionnaire()\r\n elif item == 't':\r\n trident()\r\n elif item == 'z':\r\n protective_helmet()\r\n elif item == 'A':\r\n immortality()\r\n\r\n\r\npc = Player_characters(hard_of_level)\r\n\r\n\r\n","sub_path":"body.py","file_name":"body.py","file_ext":"py","file_size_in_byte":7525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"528498605","text":"from flask import Blueprint, request, render_template, url_for, redirect, jsonify, g\nfrom app import db, models\nimport json\nfrom datetime import datetime\nfrom blueprints.paginas import paginas_blueprint\nfrom flask.ext.login import current_user, login_required\nfrom forms import NovaPag, NovaPostagem\nfrom math import ceil\n\nusers_blueprint = Blueprint('users', __name__)\n\ndef get_key(post):\n\treturn datetime.strptime(post['timestamp'], '%Y-%m-%d %H:%M:%S')\n\ndef json_postagem(postagem):\n\treturn json.dumps({'timestamp': str(postagem.timestamp), 'conteudo': postagem.conteudo})\n\ndef get_user(username):\n\tusuarios = models.Usuario.query.all()\n\tfor us in usuarios:\n\t\tif us.username == username:\n\t\t\tpags = []\n\t\t\tfor p in us.curtidas:\n\t\t\t\tpags.append(p.nome)\n\t\t\tdono = []\n\t\t\tfor p in us.minhas_paginas:\n\t\t\t\tdono.append(p.nome)\n\t\t\tpostagens = []\n\t\t\tfor post in us.minhas_postagens:\n\t\t\t\tpostagens.append(json_postagem(post))\n\t\t\tuser = json.dumps({'nome':us.nome,'email':us.email,'curtidas':pags, 'dono':dono, 'username':username, 'postagens':postagens})\n\t\t\treturn user\n\treturn None\n\n@users_blueprint.route(\"/json//\")\n@login_required\ndef json_p(username):\n\tusuario = get_user(username)\n\tif usuario != None:\n\t\tuser = json.loads(usuario)\n\t\treturn jsonify(user)\n\treturn redirect(url_for('users.usuarios'))\n\n@users_blueprint.route(\"/perfil//\")\n@login_required\ndef perfil(username):\n\tusuario = get_user(username)\n\tif usuario != None:\n\t\tuser = json.loads(usuario)\n\t\tposts = []\n\t\tfor post in user['postagens']:\n\t\t\tposts.append(json.loads(post))\n\t\tform = NovaPostagem()\n\t\treturn render_template('perfil.html', user=user, form=form, postagens=sorted(posts, key=get_key, reverse=True)[0:4])\n\treturn redirect(url_for('users.usuarios'))\n\t\n@users_blueprint.route(\"/usuarios/\")\n@login_required\ndef usuarios():\n\tusers = models.Usuario.query.all()\n\treturn render_template('usuarios.html', users=users)\n\n@users_blueprint.route(\"/perfil/criar_pag/\", methods=['GET', 'POST'])\n@login_required\ndef criar_pag():\n\tif request.method == 'POST':\n\t\tnome_pag = request.form['nome']\n\t\t#verificar se ja existe\n\t\tpaginas = models.Pagina.query.all()\n\t\tfor pgs in paginas:\n\t\t\tif pgs.nome.replace(\" \", \"\").upper() == nome_pag.replace(\" \", \"\").upper():\n\t\t\t\tform = NovaPag()\n\t\t\t\treturn render_template('criar_pag.html', form=form)\n\t\tp = models.Pagina(nome=nome_pag, usuario=current_user)\n\t\tdb.session.add(p)\n\t\tdb.session.commit()\n\t\treturn redirect(url_for('paginas.pagina', name=nome_pag))\n\tform = NovaPag()\n\treturn render_template('criar_pag.html', form=form)\n\n@users_blueprint.route(\"/perfil//postar\", methods=['POST'])\n@login_required\ndef postar(username):\n\ttimestamp = datetime.utcnow()\n\tconteudo = request.form['conteudo']\n\tpost = models.Postagem(conteudo=conteudo, id_user=current_user.id, timestamp=timestamp)\n\tdb.session.add(post)\n\tdb.session.commit()\n\treturn redirect(url_for('users.perfil', username=current_user.username))\n\n@users_blueprint.route('/users_pages/', methods=['GET', 'POST'])\n@login_required\ndef users_pages():\n\treturn render_template('users_pages.html')\n\n@users_blueprint.route('/all_get/', methods=['GET'])\n@login_required\ndef all_get():\n\treturn_val = []\n\tfor p in models.Pagina.query.all():\n\t\treturn_val.append({'name': p.nome})\n\tfor u in models.Usuario.query.all():\n\t\treturn_val.append({'name': u.nome})\n\treturn jsonify(return_val)\n\n@users_blueprint.route('/users_get/', methods=['GET'])\n@login_required\ndef users_get():\n\treturn_val = []\n\tfor u in models.Usuario.query.all():\n\t\treturn_val.append({'name': u.nome})\n\treturn jsonify(return_val)\n\n@users_blueprint.route('/pages_get/', methods=['GET'])\n@login_required\ndef pages_get():\n\treturn_val = []\n\tfor p in models.Pagina.query.all():\n\t\treturn_val.append({'name': p.nome})\n\treturn jsonify(return_val)\n\n@users_blueprint.route('//user_posts/')\n@login_required\ndef user_posts(username):\n\tusuario = get_user(username)\n\tif usuario != None:\n\t\tuser = json.loads(usuario)\n\t\tposts = []\n\t\tfor post in user['postagens']:\n\t\t\tposts.append(json.loads(post))\n\t\treturn render_template('user_posts.html', user=user, postagens=sorted(posts, key=get_key, reverse=True))\n\treturn redirect(url_for('users.usuarios'))","sub_path":"blueprints_treinamento/blueprints/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115157415","text":"import numpy as np\n\nclass FourBiharmonicPhaseOscillators:\n def __init__(self, paramW, paramA, paramB, paramR):\n self.paramW = paramW\n self.paramA = paramA\n self.paramB = paramB\n self.paramR = paramR\n\n def funG(self, fi):\n return -np.sin(fi + self.paramA) + self.paramR * np.sin(2 * fi + self.paramB)\n\n def getFullSystem(self, phis):\n rhsPhis = [0,0,0,0] \n for i in range(4):\n elem = self.paramW\n for j in range(4):\n elem += 0.25 * self.funG(phis[i]-phis[j])\n rhsPhis[i] = elem\n return rhsPhis\n\n def getReducedSystem(self, gammas):\n gammas = list(gammas)\n phis = [0] + gammas\n rhsPhi = self.getFullSystem(phis)\n rhsGamma = [0,0,0,0]\n for i in range(4):\n rhsGamma[i] = rhsPhi[i]-rhsPhi[0]\n return rhsGamma[1:]\n\n def getRestriction(self,psi): \n psi = list(psi) \n gammas = [0] + psi\n rhsPsi = self.getReducedSystem(gammas)\n return rhsPsi[1:]\n \n def DiagComponentJac2d(self, x,y):\n \n \n return (2*(-np.cos(x + self.paramA) + 2*self.paramR * np.cos(2 * x + self.paramB)) +\n (-np.cos(x-y + self.paramA) + 2*self.paramR * np.cos(2 * (x-y) + self.paramB)) -\n (np.cos((-x) + self.paramA) - 2*self.paramR * np.cos(2 * (-x) + self.paramB))\n )/4\n def NotDiagComponentJac(self, x,y):\n \n return ((np.cos(x-y + self.paramA) - 2*self.paramR * np.cos(2 * (x-y) + self.paramB)) -\n (np.cos((-y) + self.paramA) - 2*self.paramR * np.cos(2 * (-y) + self.paramB))\n )/4\n \n def DiagComponentJac3d(self, x,y,z):\n \n \n return (\n (-np.cos(x + self.paramA) + 2*self.paramR * np.cos(2 * x + self.paramB)) +\n \n (-np.cos(x-y + self.paramA) + 2*self.paramR * np.cos(2 * (x-y) + self.paramB))+\n \n (-np.cos(x-z + self.paramA) + 2*self.paramR * np.cos(2 * (x-z) + self.paramB))-\n \n (np.cos((-x) + self.paramA) - 2*self.paramR * np.cos(2 * (-x) + self.paramB))\n )/4\n \n def getRestrictionJac(self,X): \n x,y=X \n return np.array([[self.DiagComponentJac2d(x,y), self.NotDiagComponentJac(x,y)],\n [ self.NotDiagComponentJac(y,x),self.DiagComponentJac2d(y,x)]])\n \n def getReducedSystemJac(self,X): \n x,y,z=X \n return np.array([[self.DiagComponentJac3d(x,y,z), self.NotDiagComponentJac(x,y),self.NotDiagComponentJac(x,z)],\n [ self.NotDiagComponentJac(y,x),self.DiagComponentJac3d(y,x,z),self.NotDiagComponentJac(y,z)],\n [ self.NotDiagComponentJac(z,x),self.NotDiagComponentJac(z,y),self.DiagComponentJac3d(z,x,y)]\n ])\n \n def getParams(self): \n return [self.paramW,self.paramA,self.paramB,self.paramR]","sub_path":"SystOsscills.py","file_name":"SystOsscills.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"33631162","text":"import os\nfrom pathlib import Path\n\nCLONE_DESTINATION = Path(\n os.environ.get(\"CURRICULUM_CLONE_DIR\", \"gitignore/sync_curriculum\")\n)\nREPO_SSH_URL = \"git@github.com:Umuzi-org/tech-department.git\"\nREPO_NAME = \"tech-department\"\n\n\nFULL_PATH = CLONE_DESTINATION / REPO_NAME\nCURRICULUMS_BASE_DIR = FULL_PATH / \"content/syllabuses\"\n\nRAW_CONTENT_URL = \"https://raw.githubusercontent.com/Umuzi-org/tech-department/master/{content_sub_dir}\"\n\n\nCURRICULUM_STATIC_SITE_URL = \"https://umuzi-org.github.io/tech-department/\"\n\n\nNOT_YET_COMPETENT = \"NYC\"\nCOMPETENT = \"C\"\nEXCELLENT = \"E\"\nRED_FLAG = \"R\"\n\nREVIEW_STATUS_CHOICES = [\n (NOT_YET_COMPETENT, \"not yet competent\"),\n (COMPETENT, \"competent\"),\n (EXCELLENT, \"excellent\"),\n (RED_FLAG, \"red flag\"),\n]\n","sub_path":"backend/curriculum_tracking/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"161737507","text":"# import cv2\r\nimport numpy as np\r\nimport os\r\nimport json\r\nimport math\r\nfrom operator import itemgetter\r\nfrom creat_coord import *\r\nimport argparse\r\nfrom tqdm import tqdm\r\n\r\nclass NpEncoder(json.JSONEncoder):\r\n def default(self, obj):\r\n if isinstance(obj, np.integer):\r\n return int(obj)\r\n elif isinstance(obj, np.floating):\r\n return float(obj)\r\n elif isinstance(obj, np.ndarray):\r\n return obj.tolist()\r\n else:\r\n return super(NpEncoder, self).default(obj)\r\n\r\nclass HybridLoader:\r\n \"\"\"\r\n If db_path is a director, then use normal file loading\r\n If lmdb, then load from lmdb\r\n The loading method depend on extention.\r\n \"\"\"\r\n\r\n def __init__(self, db_path, ext):\r\n self.db_path = db_path\r\n self.ext = ext\r\n if self.ext == '.npy':\r\n self.loader = lambda x: np.load(x)\r\n self.db_type = 'dir'\r\n\r\n def get(self, key):\r\n\r\n f_input = os.path.join(self.db_path, key + self.ext)\r\n # load image\r\n feat = self.loader(f_input)\r\n return feat\r\n\r\nclass box:\r\n def __init__(self):\r\n # self.box_loader = HybridLoader(\"/home/ubuntu/LY/self-critical.pytorch-master/data/bottom_up_box\", '.npy')\r\n self.box1_loader = HybridLoader(\"/home/ubuntu/LY/self-critical.pytorch-master/data/bottom_up_box1\", '.npy')\r\n def get_box(self, id):\r\n # box_feat = self.box_loader.get(str(id))\r\n box1_feat = self.box1_loader.get(str(id))\r\n\r\n return box1_feat\r\n\r\ndef sort(box_feat):\r\n c = np.zeros((36, 7))\r\n for k, i in enumerate(box_feat):\r\n x1, y1, x2, y2 = i[0], i[1], i[2], i[3]\r\n s = (x2 - x1) * (y2 - y1)\r\n w = x2 - x1\r\n h = y2 - y1\r\n x = x1 + w/2\r\n y = y1 + h/2\r\n c[k] = (x1, y1, x2, y2, s, x, y)\r\n sorted_feat = sorted(c, key=lambda x: x[4])\r\n sorted_feat = sorted_feat[0:25]\r\n sorted_feat = sorted(sorted_feat, key=lambda x: x[5])\r\n\r\n return sorted_feat\r\n\r\ndef cluster(box_feat, label, id):\r\n lab = []\r\n k = max(label)\r\n for index, value in enumerate(label):\r\n t = (index, value)\r\n lab.append(t)\r\n clu = dict()\r\n for i in range(k+1):\r\n a = []\r\n for j in lab:\r\n if j[1] == i:\r\n a.append(j)\r\n clu[i] = a\r\n coord = dict()\r\n for i in range(k+1):\r\n b = clu[i]\r\n x_sum = 0\r\n y_sum = 0\r\n for j in b:\r\n x_sum += box_feat[j[0]][5]\r\n y_sum += box_feat[j[0]][6]\r\n x = x_sum / len(b)\r\n y = y_sum / len(b)\r\n coord[i] = (x, y)\r\n example = {\"clu\": clu, \"coord\": coord, \"id\": id}\r\n return example\r\n\r\ndef main(params):\r\n file = open(params['output_json'], 'w', encoding='utf-8')\r\n images = json.load(open(params['input_json'], 'r'))\r\n imgs = images['images']\r\n for img in tqdm(imgs):\r\n id = img['id']\r\n box_feat = box.get_box(id)\r\n sorted_box_feat = sort(box_feat)\r\n coordinate_list = create_coordinate_list(sorted_box_feat)\r\n dbscan = DBSCAN(eps=20, min_samples=1, metric=get_distance).fit(coordinate_list)\r\n label = dbscan.labels_\r\n res = cluster(sorted_box_feat, label, id)\r\n file.write(json.dumps(res, cls=NpEncoder) + '\\n')\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n\r\n # input json\r\n parser.add_argument('--input_json', default='/home/ubuntu/LY/self-critical.pytorch-master/data/outfile/4+4/output.json')\r\n parser.add_argument('--output_json', default='/home/ubuntu/LY/self-critical.pytorch-master/data/label/label1_25_4+4.json')\r\n\r\n args = parser.parse_args()\r\n params = vars(args) # convert to ordinary dict\r\n box = box()\r\n main(params)","sub_path":"box.py","file_name":"box.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264139199","text":"#coding=utf-8\nfrom PyQt5.QtSql import *\nimport oss2\nimport pymysql\nfrom PyQt5.QtGui import QBrush, QColor\nBRUSH0=QBrush(QColor(220, 230, 255))\nBRUSH1=QBrush(QColor(210, 220, 255))\ndef connectdb():\n import sys\n if QSqlDatabase.contains(\"qt_sql_default_connection\"): \n db = QSqlDatabase.database(\"qt_sql_default_connection\")\n return db\n \n \n else: \n db=QSqlDatabase.addDatabase(\"QMYSQL\")\n db.setHostName('57af503e35be5.gz.cdb.myqcloud.com')\n# db.setDatabaseName('gstar')\n db.setDatabaseName('gstar_normal')\n db.setUserName('root')\n db.setPassword('rootabc123456*')\n db.setPort(4402) \n \n if not db.open():\n print(\"can not open database,please check\")\n return None\n else:\n return db\n \n\nclass oss():\n def __init__(self):\n \n AccessKeyId='LTAIZtiyU7P3rOkA'\n AccessKeySecret='9bfi605OH5eQTeF9xnGqlL1zfRkK9F'\n self.Endpoint='http://oss-cn-shenzhen.aliyuncs.com'\n self.bucketName='gstardata'\n self.auth = oss2.Auth(AccessKeyId, AccessKeySecret)\n self.bucket = oss2.Bucket(self.auth, self.Endpoint,self.bucketName )\n def getbucket(self):\n return self.bucket\n def getauth(self):\n return self.auth\n def getendpoint(self):\n return self.Endpoint\n \nDB_CONFIG = {\n 'host':'57af503e35be5.gz.cdb.myqcloud.com',\n 'port':4402,\n 'user':'root',\n 'password':'rootabc123456*',\n 'db':'gstar_normal',\n 'charset':'utf8mb4',\n# 'cursorclass':pymysql.cursors.DictCursor\n }\n","sub_path":"MA18/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197343942","text":"from itertools import cycle\n# cycle()会把传入的一个序列无限重复下去\n# >>> import itertools\n# >>> cs = itertools.cycle('ABC') # 注意字符串也是序列的一种\n# >>> for c in cs:\n# ... print(c)\n# ...\n# 'A'\n# 'B'\n# 'C'\n# 'A'\n\nfrom time import time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\n\nfrom sklearn.cluster import Birch, MiniBatchKMeans\nfrom sklearn.datasets import make_blobs\n\n# Generate centers for the blobs so that it forms a 10 X 10 grid.\nxx = np.linspace(-22, 22, 10)\nyy = np.linspace(-22, 22, 10)\nxx, yy = np.meshgrid(xx, yy)\n# meshgrid() 扩充矩阵,使xx和yy大小不等扩充为大小相等\n# In [4]: import numpy as np\n# ...: nx, ny = (3,2)\n# ...: x = np.linspace(0,1,nx)\n# ...: y = np.linspace(0,1,ny)\n# ...: x\n# ...:\n# ...:\n# Out[4]: array([ 0. , 0.5, 1. ])\n#\n# In [5]:\n#\n# In [5]: y\n# Out[5]: array([ 0., 1.])\n#\n# In [6]: xv,yv=np.meshgrid(x,y)\n#\n# In [7]: xv\n# Out[7]:\n# array([[ 0. , 0.5, 1. ],\n# [ 0. , 0.5, 1. ]])\n#\n# In [8]: x\n# Out[8]: array([ 0. , 0.5, 1. ])\n#\n# In [9]: y\n# Out[9]: array([ 0., 1.])\n#\n# In [10]: yv\n# Out[10]:\n# array([[ 0., 0., 0.],\n# [ 1., 1., 1.]])\n\nn_centres = np.hstack((np.ravel(xx)[:, np.newaxis],\n np.ravel(yy)[:, np.newaxis]))\n\n# hstack 横向扩展 horizontally stack 横向上堆叠\n# >>> a = np.array((1,2,3))\n# >>> b = np.array((2,3,4))\n# >>> np.hstack((a,b))\n# array([1, 2, 3, 2, 3, 4])\n# >>> a = np.array([[1],[2],[3]])\n# >>> b = np.array([[2],[3],[4]])\n# >>> np.hstack((a,b))\n# array([[1, 2],\n# [2, 3],\n# [3, 4]])\n\n# ravel() 和 flatten() 函数都是对原数组降为一维,但区别就是ravel()返回的是原\n# 数组的视图,而flatten() 是原数组的拷贝\n# np.newaxis 在使用和功能上等价于 None,其实就是 None 的一个别名。\n# Generate blobs to do a comparison between MiniBatchKMeans and Birch.\nX, y = make_blobs(n_samples=100000, centers=n_centres, random_state=0)\n\n# Use all colors that matplotlib provides by default.\ncolors_ = cycle(colors.cnames.keys())\n# colors.cnames 颜色表---》字典类型,值为十六进制表示,键为字母表示法\nfig = plt.figure(figsize=(12, 4))\nfig.subplots_adjust(left=0.04, right=0.98, bottom=0.1, top=0.9)\n\n# Compute clustering with Birch with and without the final clustering step\n# and plot.\nbirch_models = [Birch(threshold=1.7, n_clusters=None),\n Birch(threshold=1.7, n_clusters=100)]\nfinal_step = ['without global clustering', 'with global clustering']\n\nfor ind, (birch_model, info) in enumerate(zip(birch_models, final_step)):\n t = time()\n birch_model.fit(X)\n time_ = time() - t\n print(\"Birch %s as the final step took %0.2f seconds\" % (\n info, (time() - t)))\n\n # Plot result\n labels = birch_model.labels_\n centroids = birch_model.subcluster_centers_\n n_clusters = np.unique(labels).size\n print(\"n_clusters : %d\" % n_clusters)\n\n ax = fig.add_subplot(1, 3, ind + 1)\n for this_centroid, k, col in zip(centroids, range(n_clusters), colors_):\n mask = labels == k\n ax.plot(X[mask, 0], X[mask, 1], 'w',\n markerfacecolor=col, marker='.')\n if birch_model.n_clusters is None:\n ax.plot(this_centroid[0], this_centroid[1], '+', markerfacecolor=col,\n markeredgecolor='k', markersize=5)\n ax.set_ylim([-25, 25])\n ax.set_xlim([-25, 25])\n ax.set_autoscaley_on(False)\n ax.set_title('Birch %s' % info)\n\n# Compute clustering with MiniBatchKMeans.\nmbk = MiniBatchKMeans(init='k-means++', n_clusters=100, batch_size=100,\n n_init=10, max_no_improvement=10, verbose=0,\n random_state=0)\nt0 = time()\nmbk.fit(X)\nt_mini_batch = time() - t0\nprint(\"Time taken to run MiniBatchKMeans %0.2f seconds\" % t_mini_batch)\nmbk_means_labels_unique = np.unique(mbk.labels_)\n\nax = fig.add_subplot(1, 3, 3)\nfor this_centroid, k, col in zip(mbk.cluster_centers_,\n range(n_clusters), colors_):\n mask = mbk.labels_ == k\n ax.plot(X[mask, 0], X[mask, 1], 'w', markerfacecolor=col, marker='.')\n ax.plot(this_centroid[0], this_centroid[1], '+', markeredgecolor='k',\n markersize=5)\nax.set_xlim([-25, 25])\nax.set_ylim([-25, 25])\nax.set_title(\"MiniBatchKMeans\")\nax.set_autoscaley_on(False)\nplt.show()\n\n\n# 索引多维数组的某一列时返回的是一个行向量\n# >>> X = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n# >>> X[:, 1]\n# array([2, 6, 10]) % 这里是一个行\n# >>> X[:, 1].shape % X[:, 1] 的用法完全等同于一个行,而不是一个列,\n# (3, )\n#\n# 所以,一种正确的索引方式是:\n# X[:, 1][:, np.newaxis]\n# array([[2],\n# [6],\n# [10]])\n#\n# 如果想实现第二列和第四列的拼接(层叠):\n#\n# >>>X_sub = np.hstack([X[:, 1][:, np.newaxis], X[:, 3][:, np.newaxis]])\n# % hstack:horizontal stack,水平方向上的层叠\n# >>>X_sub\n# array([[2, 4]\n# [6, 8]\n# [10, 12]])","sub_path":"birch.py","file_name":"birch.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"238545448","text":"#!/usr/bin/python\n\n# count GC content of sequence\n\nimport re\nimport sys\n\nf1 = open(sys.argv[1])\t# bin.fa\nf2 = open(sys.argv[2],'w') # GCcontent\nfor i in f1:\n\tif re.match('>',i):\n\t\tf2.write(i.strip().lstrip('>') + '\\t')\n\telse:\n\t\tif not re.search('N',i):\n\t\t\tbin = i.strip()\n\t\t\tcount = 0\n\t\t\tfor j in bin:\n\t\t\t\tif re.match('[CG]',j):\n\t\t\t\t\tcount += 1\n\t\t\tcontent = round(float(count) / 100,2 )\n\t\t\tf2.write(str(content) + '\\n')\n\t\telse:\n\t\t\tf2.write('0\\n')\n\nf2.close()\nf1.close()\n","sub_path":"incrna-0.1-src/bin/GC.py","file_name":"GC.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"140364860","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.optim as optim\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom dataset import *\nfrom model import *\n\ntransform_dataset = torchvision.transforms.ToTensor()\ncarvana2 = carvana_dataset('../input/', transform = transform_dataset)\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nnet = UNet(3, 1).to(device)\noptimizer = optim.SGD(\n net.parameters(),\n lr = .1,\n momentum = .9,\n weight_decay=0.0005\n)\n\n#criterion = nn.CrossEntropyLoss()\ncriterion = nn.BCELoss()\n\nfor epoch in range(3):\n print('starting epoch number {}'.format(epoch))\n epoch_loss = 0\n net.train()\n for i, image_mask in enumerate(carvana2):\n # try:\n original_mask = image_mask['mask'].to(device)\n # original_mask_flat = original_mask.squeeze().view(-1)\n #mask_pred = net(image_mask['image'].to(device).unsqueeze(0))\n mask_pred = net(image_mask['image'].unsqueeze(0).to(device))\n # print(mask_pred.shape, mask_pred.squeeze().shape)\n # mask_pred_flat= mask_pred.squeeze().view(-1)\n # loss = criterion(original_mask_flat, mask_pred_flat)\n print(mask_pred.view(1, -1).shape)\n print(original_mask.view(1, -1).shape)\n loss = criterion( mask_pred.view(-1), original_mask.view(-1))\n epoch_loss += loss.item()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()\n # except RuntimeError as e:\n# del original_mask\n# del original_mask_flat\n# del mask_pred\n# del mask_pred_flat\n# del loss\n# print(e)\n\n\n if (i % 100) == 0:\n print(\"train loss in {:0>2}epoch /{:>5}iter: {:<10.8}\".\\\n format(epoch+1, i, epoch_loss/(i+1)))\n print(\"time number: %i\", i)\n","sub_path":"carvana/carvana.py","file_name":"carvana.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81684020","text":"import socket,os,sys\nimport numpy as np\nfrom PIL import Image\nimport cv2\n#from test import infer_and_match\n#sys.path.append(\"/Users/lhtlinda/Desktop/rps-cv\")\n#from play import process\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.bind((socket.gethostbyname(socket.gethostname()), int(sys.argv[1])))\nsys.path.append(\"/Users/lhtlinda/Desktop/rock-paper-scissor-vision\")\nfrom play import main \naction = int(sys.argv[2])\n# 1 stands for detecting people, 2 stands for RockPaperScissors\n\nprint(socket.gethostbyname(socket.gethostname()))\n\nserver_socket.listen(5)\nidx=0\nwhile 1:\n idx+=1\n #accept connections from outside\n (clientsocket, address) = server_socket.accept()\n #now do something with the clientsocket\n #in this case, we'll pretend this is a threaded server\n print(\"connected to client\") \n while True:\n size = clientsocket.recv(1024)\n #print(size)\n print(\"got size\")\n \n i=str(size)\n print(i)\n\n \n \n s=str(i)[2:-1]\n s=int(s)\n shape1=1920\n shape0=1080\n #shape2=3\n #print(shape0)\n \n #s=str(shape0)\n #print(s)\n #s=s[2:]\n #s0=int(s[:3])\n #s1=int(s[3:6])\n #shape1=clientsocket.recv(1024)\n #print(shape1)\n #s1=int(shape1)\n #print(s0)\n #print(s1)\n #buf=clientsocket.recv(i)\n #im = Image.frombuffer(\"RGBA\",(s0,s1),buf)\n #c=clientsocket.recv(1024)\n #if not c:\n # break\n #s=str(size)\n #i=int(size)\n #s0=int(shape0)\n #s1=int(shape1)\n #buf=clientsocket.recv(i)\n #print(type(buf))\n #arr=np.frombuffer(buf,dtype=\"int32\")\n #print(arr.shape)\n #im = Image.frombuffer(\"RGBA\",(s0,s1),buf)\n #im.save(\"test_images/image4.jpg\")\n break\n clientsocket.close()\n print(\"closed\")\n server_socket.listen(10)\n \n (clientsocket, address) = server_socket.accept()\n print(\"accepted second connection\")\n print(clientsocket)\n print(address)\n \n l=0\n \n\n while l 1:\n raise ValueError(\"Decorator takes only one string [save_file_path] argument\")\n elif not isinstance(args[0], str):\n raise ValueError(\"Decorator takes string [save_file_path] argument\")\n self._function = lambda function: LoggerFunction(function, *args)\n self.save_path: str = args[0]\n self.file_was_opened = False\n elif len(args) == 1 and isinstance(args[0], Callable):\n raise ValueError(\"You can not use this decorator without passing file name\")\n else:\n self._function = args[0]\n self.save_path = args[1]\n self.file_was_opened = False\n self.__name__ = args[0].__name__\n functools.update_wrapper(self, args[0])\n\n def __call__(self, *args: Hashable, **kwargs: Hashable):\n if not inspect.isclass(args[0]):\n return self._function(*args, **kwargs)\n result = self._function(*args, **kwargs)\n if not self.file_was_opened:\n with open(self.save_path, \"w\") as f:\n f.write(f\"{datetime.now()} {self.__name__} {args} ({kwargs}) {result} \\n\")\n self.file_was_opened = True\n else:\n with open(self.save_path, \"a\") as f:\n f.write(f\"{datetime.now()} {self.__name__} {args} ({kwargs}) {result} \\n\")\n return result\n","sub_path":"homework/tests/test1/task1/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"271321637","text":"import csv\nfrom selenium import webdriver\nimport base64, os, datetime, json,io\n\n\ndef set_chrome_options():\n chrome_options = webdriver.ChromeOptions()\n preferences = {\n \"credentials_enable_service\": False,\n 'profile': {\n 'password_manager_enabled': False\n }}\n chrome_options.add_argument(\"disable-infobars\")\n chrome_options.add_argument(\"disable-notifications\")\n chrome_options.add_experimental_option(\"excludeSwitches\", ['enable-automation'])\n chrome_options.add_experimental_option(\"prefs\", preferences)\n return chrome_options\n\n\ndef get_csv_length(filename):\n length = 0\n with open(filename, 'r') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n length += 1\n return length\n\n\ndef read_from_csv(filename):\n data = []\n with open(filename, 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n data.append(row)\n return data\n\n\ndef read_from_csv_as_dict(filename):\n data = []\n with open(filename, 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n data.append(row)\n return data\n\n\ndef write_in_csv(filename, data, source='dict', write_mode='a'):\n if data is None:\n return\n len = get_csv_length(filename)\n with open(filename, write_mode) as csvfile:\n if source == 'list':\n writer = csv.writer(csvfile)\n else:\n writer = csv.DictWriter(csvfile, fieldnames=data.keys())\n if len == 0 and source == 'dict':\n writer.writeheader()\n writer.writerow(data)\n\n\ndef encode(plainText):\n return base64.encodebytes(str.encode(plainText, 'latin-1'))\n\n\ndef decode(encodedText):\n return base64.decodebytes(str.encode(encodedText, 'latin-1')).decode('latin-1')\n\n\ndef is_present_in_dictionary(current_dict, key):\n if key in current_dict:\n return True\n return False\n\n\ndef string_contains(parent_string,search_string):\n return search_string in parent_string\n\n\ndef find_in_string(parent_string,search_string):\n return parent_string.find(search_string)\n\n\ndef get_absolute_path(relative_path):\n return os.path.abspath(relative_path)\n\n\ndef format_date_time(in_date, current_format='%d/%m/%Y', new_format='%m/%d/%y'):\n return datetime.datetime.strptime(in_date, current_format).strftime(new_format)\n\n\ndef parse_paytm_csv(txn_date, activity, src, wallet_id, comment, debit, credit):\n parsed_txn_date = format_date_time(str(txn_date).split(\" \")[0].strip())\n parsed_source = \"\"\n parsed_comment = \"\"\n parsed_category = \"\"\n parsed_amount = 0.0\n parsed_txn_type = \"credit\"\n activity = str(activity).title().strip()\n src = str(src)\n parsed_order_no = src\n comment = str(comment)\n parsed_debit = 0.0\n parsed_credit = 0.0\n if debit and debit != '':\n parsed_debit = float(debit)\n if credit and credit != '':\n parsed_credit = float(credit)\n valid_activity = [\"Paid For Order\",\"Cashback Received\",\"Payment Received\",\"Money Sent\",\"Refund For Order\",\"Paytm Cash Sent\"]\n if activity in valid_activity:\n if parsed_credit > 0:\n parsed_amount = parsed_amount + parsed_credit\n if parsed_debit > 0:\n parsed_amount = parsed_amount - parsed_debit\n if parsed_amount < 0:\n parsed_txn_type = \"debit\"\n parsed_amount = parsed_amount * -1\n parsed_source_index = src.find(\" Order #\", 1)\n if parsed_source_index > 0:\n parsed_source = src.split(\" Order #\", 1)[0]\n parsed_order_no = src.split(\" Order #\", 1)[1]\n parsed_comment_index = comment.find(\" To: \")\n if parsed_comment_index > 0:\n if parsed_txn_type == \"debit\":\n parsed_comment = comment.split(\" To: \", 1)[1]\n else:\n parsed_comment = comment.split(\" To: \", 1)[0].replace(\"From: \", \"\")\n if parsed_source == \"\" and parsed_comment != \"\":\n parsed_source = parsed_comment\n if parsed_source == \"\" and activity == \"Cashback Received\":\n parsed_source = \"Paytm\"\n parsed_category = \"Cashback\"\n parsed_comment = \"Wallet Txn ID: \"+str(wallet_id)+\" | Order #: \"+parsed_order_no\n if comment is not None and comment.strip() != \"\":\n parsed_comment = parsed_comment+\" | Comment: \"+comment\n if parsed_source is not None and parsed_source.strip() == \"\":\n parsed_source = \"Paytm Transfer\"\n parsed_dict = {\n \"Date\" : parsed_txn_date,\n \"Activity\" : activity,\n \"Description\" : parsed_source.title().strip(),\n \"Category\" : parsed_category,\n \"Amount\" : parsed_amount,\n \"Notes\" : parsed_comment.title().strip(),\n \"Source\" : \"paytm\",\n \"Type\" : parsed_txn_type\n }\n return parsed_dict\n\n\ndef construct_map_from_txn_csv(filename):\n parsed_map_description_to_merchant = {}\n parsed_map_merchant_to_category = {}\n with open('Mappings/description_to_merchant_map.json') as f:\n data = json.load(f)\n if data is not None and issubclass(type(data),dict) and len(data)>0:\n parsed_map_description_to_merchant = data.copy()\n with open('Mappings/merchant_to_category_map.json') as f:\n data = json.load(f)\n if data is not None and issubclass(type(data),dict) and len(data) > 0:\n parsed_map_merchant_to_category = data.copy()\n data = read_from_csv_as_dict(filename)\n if data is None or len(data) < 1:\n return\n for row in data:\n if row is None or not issubclass(type(row),dict):\n continue\n if \"Description\" not in row or \"Category\" not in row:\n continue\n if str(row[\"Category\"]).strip() == \"\":\n row[\"Category\"] = \"Uncategorized\"\n if row[\"Description\"] is not None and str(row[\"Description\"]).strip() != \"\":\n if row[\"Description\"] in parsed_map_description_to_merchant:\n continue\n else:\n parsed_map_description_to_merchant[row[\"Description\"]] = row[\"Description\"]\n if row[\"Description\"] in parsed_map_merchant_to_category:\n continue\n else:\n parsed_map_merchant_to_category[row[\"Description\"]] = row[\"Category\"]\n if len(parsed_map_description_to_merchant) > 0:\n with open('Mappings/description_to_merchant_map.json', 'w') as f:\n json.dump(parsed_map_description_to_merchant, f,indent=4,sort_keys=True)\n if len(parsed_map_merchant_to_category) > 0:\n with open('Mappings/merchant_to_category_map.json', 'w') as f:\n json.dump(parsed_map_merchant_to_category, f,indent=4,sort_keys=True)\n print(\"done\")\n\n\ndef map_merchant_and_category_from_json(filename,target_file):\n parsed_map_description_to_merchant = {}\n parsed_map_merchant_to_category = {}\n with open('Mappings/description_to_merchant_map.json') as f:\n data = json.load(f)\n if data is not None and issubclass(type(data), dict) and len(data) > 0:\n parsed_map_description_to_merchant = data.copy()\n with open('Mappings/merchant_to_category_map.json') as f:\n data = json.load(f)\n if data is not None and issubclass(type(data), dict) and len(data) > 0:\n parsed_map_merchant_to_category = data.copy()\n if parsed_map_description_to_merchant is None or parsed_map_merchant_to_category is None:\n return\n data = read_from_csv_as_dict(filename)\n if data is None or len(data) < 1:\n return\n for row in data:\n if row is None or not issubclass(type(row), dict):\n continue\n data_to_write = {}\n if \"Date\" not in row or \"Activity\" not in row or \"Description\" not in row or \"Category\" not in row \\\n or \"Amount\" not in row or \"Notes\" not in row or \"Source\" not in row or \"Type\" not in row:\n continue\n if row[\"Date\"] is not None and str(row[\"Date\"]).strip() != \"\" \\\n and row[\"Activity\"] is not None and str(row[\"Activity\"]).strip() != \"\" \\\n and row[\"Description\"] is not None and str(row[\"Description\"]).strip() != \"\" \\\n and row[\"Amount\"] is not None and str(row[\"Activity\"]).strip() != \"\" \\\n and row[\"Source\"] is not None and str(row[\"Source\"]).strip() != \"\" \\\n and row[\"Type\"] is not None and str(row[\"Type\"]).strip() != \"\":\n if row[\"Description\"] not in parsed_map_description_to_merchant:\n continue\n merchant = parsed_map_description_to_merchant[row[\"Description\"]]\n if merchant not in parsed_map_merchant_to_category:\n continue\n category = parsed_map_merchant_to_category[merchant]\n data_to_write[\"Date\"] = row[\"Date\"]\n data_to_write[\"Description\"] = merchant\n data_to_write[\"Category\"] = category\n data_to_write[\"Amount\"] = row[\"Amount\"]\n data_to_write[\"Notes\"] = row[\"Notes\"]\n data_to_write[\"Source\"] = row[\"Source\"]\n data_to_write[\"Type\"] = row[\"Type\"]\n write_in_csv(target_file,data_to_write)\n","sub_path":"Lib/Helper.py","file_name":"Helper.py","file_ext":"py","file_size_in_byte":9198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"607736312","text":"import time\nimport sys\nfrom HTMLTestRunner import HTMLTestRunner\nfrom commentClass.SendEmail import SendMail\nimport unittest\nsys.path.append('./testCase')\n\n\n# 指定测试用例为当前文件夹下的testCase目录\ntest_dir = './testCase'\nsuite = unittest.defaultTestLoader.discover(test_dir, pattern='*_test.py')\n\n\nif __name__ == \"__main__\":\n\n now = time.strftime(\"%Y-%m-%d-%H_%M_%S\", time.localtime(time.time()))\n HtmlFile = './testReports/' + now + '_result.html'\n fp = open(HtmlFile, 'wb')\n runner = HTMLTestRunner(stream=fp,\n title=u\"PC端线上接口自动化测试报告\",\n description=u\"测试数据统计\")\n runner.run(suite)\n fp.close()\n\n # 测试结束之后,执行邮件发送报告\n sendMail = SendMail()\n sendMail.send()\n\n\n\n","sub_path":"自动化测试/接口功能/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"229493073","text":"import os\nimport time\nimport datetime\nfrom selenium.common.exceptions import TimeoutException, StaleElementReferenceException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom UserInputs.generateUserInputs import fetch_random_string\nfrom UserInputs.userInputsData import UserInputsData\nfrom datetime import date\n\n\ndef latest_download_file():\n cwd = os.getcwd()\n try:\n os.chdir(UserInputsData.download_path)\n files = sorted(os.listdir(os.getcwd()), key=os.path.getctime)\n print(files)\n for filename in files:\n if filename.endswith(\".xlsx\"):\n newest = max(files, key=os.path.getctime)\n print(\"File downloaded: \" + newest)\n return newest\n finally:\n print(\"Restoring the path...\")\n os.chdir(cwd)\n print(\"Current directory is-\", os.getcwd())\n\n\nclass OrganisationStructurePage:\n\n def __init__(self, driver):\n self.driver = driver\n self.org_menu_link_text = \"Organization Structure\"\n self.add_loc_btn_xpath = \"//span[@data-bind='text: new_child_caption' and text()='New location at top level']\"\n self.loc_name_xpath = \"//input[@type='text']\"\n self.create_loc_xpath = \"//button[@type='submit']\"\n self.loc_saved_success_msg = \"//div[@class ='alert alert-margin-top fade in alert-success']\"\n self.error_1_id = \"error_1_id_name\"\n self.new_location_name = \"location_\" + fetch_random_string()\n self.edit_this_loc = \"(//span[contains(text(),'updated_on:')])[1]\"\n self.edit_loc_button_xpath = self.edit_this_loc + \\\n \"//preceding::a[@data-bind='attr: { href: loc_edit_url(uuid()) }'][1]\"\n self.loc_name_input_id = \"id_name\"\n self.update_loc_xpath = \"(//button[@type='submit'])[1]\"\n self.location_created_xpath = \"//span[text()='\" + self.new_location_name + \"']\"\n self.renamed_location = \"//span[text()='updated_on:\" + str(date.today()) + \"']\"\n self.edit_loc_field_btn_xpath = \"//a[@data-action='Edit Location Fields']\"\n self.add_field_btn_xpath = \"//button[@data-bind='click: addField']\"\n self.loc_property_xpath = \"(//input[@data-bind='value: slug'])[last()]\"\n self.loc_label_xpath = \"(//input[@data-bind='value: label'])[last()]\"\n self.choice_selection = \"(//div[contains(@data-bind, \\\"validationMode('choice')\\\")])[last()]\"\n self.add_choice_btn_xpath = \"(//button[@data-bind='click: addChoice'])[last()]\"\n self.choice_xpath = \"(//input[@data-bind='value: value'])[last()]\"\n self.save_btn_id = \"save-custom-fields\"\n self.success_msg_xpath = \"//div[@class='alert alert-margin-top fade in alert-success']\"\n self.additional_info_drop_down = \"//*[@id='select2-id_data-field-\" + \"location_field_\" + str(\n fetch_random_string()) + \"-container']\"\n self.select_value_drop_down = \"//li[text()='\" + \"location_field_\" + str(fetch_random_string()) + \"']\"\n self.duplicate_msg_xpath = \"//div[@class='alert alert-danger']\"\n self.org_level_menu_link_text = \"Organization Levels\"\n self.new_org_level_btn_xpath = \"//button[@data-bind='click: new_loctype']\"\n self.org_level_value_xpath = \"(//input[@data-bind='value: name'])[last()]\"\n self.save_btn_xpath = \"//button[@type='submit' and @class='btn btn-default pull-right btn-primary']\"\n self.save_btn_delete = \"//button[@class='btn btn-default pull-right']\"\n self.download_loc_btn = \"Download Organization Structure\"\n self.upload_loc_btn = \"Bulk Upload\"\n self.upload = \"//button[@class='btn btn-primary disable-on-submit']\"\n self.import_complete = \"//legend[text()='Import complete.']\"\n self.download_filter = \"//button[@data-bind='html: buttonHTML']\"\n\n # cleanup\n self.delete_location_created = \"//span[text ()='\" + self.new_location_name + \\\n \"']//preceding::button[@class='btn btn-danger'][1]\"\n self.delete_confirm = '//input[@data-bind =\"value: signOff, valueUpdate: \\'input\\'\"]'\n self.delete_confirm_button = \"//button[@data-bind ='click: delete_fn, css: {disabled: !(signOff() == count)}']\"\n self.delete_loc_field = \"(//a[@class='btn btn-danger'])[last()]\"\n self.delete_org_level = \"(//button[@class='btn btn-danger'])[last()]\"\n\n def wait_to_click(self, *locator, timeout=10):\n try:\n clickable = ec.element_to_be_clickable(locator)\n WebDriverWait(self.driver, timeout).until(clickable).click()\n except TimeoutException:\n print(TimeoutException)\n\n def organisation_menu_open(self):\n self.wait_to_click(By.LINK_TEXT, self.org_menu_link_text)\n print(self.driver.title)\n assert \"Organization Structure : Locations :: - CommCare HQ\" in self.driver.title\n\n def create_location(self):\n self.wait_to_click(By.XPATH, self.add_loc_btn_xpath)\n self.driver.find_element(By.XPATH, self.loc_name_xpath).clear()\n self.driver.find_element(By.XPATH, self.loc_name_xpath).send_keys(self.new_location_name)\n self.driver.find_element(By.XPATH, self.create_loc_xpath).click()\n assert WebDriverWait(self.driver, 10).until(ec.presence_of_element_located((\n By.XPATH, self.loc_saved_success_msg))).is_displayed()\n self.wait_to_click(By.LINK_TEXT, self.org_menu_link_text)\n self.driver.refresh()\n try:\n assert WebDriverWait(self.driver, 3).until(ec.presence_of_element_located((\n By.XPATH, self.location_created_xpath))).is_displayed()\n except StaleElementReferenceException:\n assert WebDriverWait(self.driver, 3).until(ec.presence_of_element_located((\n By.XPATH, self.location_created_xpath))).is_displayed()\n\n def edit_location(self):\n try:\n self.wait_to_click(By.LINK_TEXT, self.org_menu_link_text)\n self.driver.find_element(By.XPATH, self.edit_loc_button_xpath).click()\n self.driver.find_element(By.ID, self.loc_name_input_id).clear()\n self.driver.find_element(By.ID, self.loc_name_input_id).send_keys(\"updated_on:\" + str(date.today()))\n self.driver.find_element(By.XPATH, self.update_loc_xpath).click()\n assert WebDriverWait(self.driver, 5).until(ec.visibility_of_element_located((\n By.XPATH, self.loc_saved_success_msg))).is_displayed()\n self.driver.find_element(By.LINK_TEXT, self.org_menu_link_text).click()\n self.driver.refresh()\n assert WebDriverWait(self.driver, 5).until(ec.visibility_of_element_located((\n By.XPATH, self.renamed_location))).is_displayed()\n except StaleElementReferenceException:\n print(StaleElementReferenceException)\n\n def edit_location_fields(self):\n self.driver.find_element(By.LINK_TEXT, self.org_menu_link_text).click()\n self.wait_to_click(By.XPATH, self.edit_loc_field_btn_xpath)\n self.wait_to_click(By.XPATH, self.add_field_btn_xpath)\n self.driver.find_element(By.XPATH, self.loc_property_xpath).clear()\n self.driver.find_element(By.XPATH, self.loc_property_xpath).send_keys(\"location_field_\" + fetch_random_string())\n self.driver.find_element(By.XPATH, self.loc_label_xpath).clear()\n self.driver.find_element(By.XPATH, self.loc_label_xpath).send_keys(\"location_field_\" + fetch_random_string())\n # self.driver.find_element_by_xpath(self.choice_selection).click() # required when reg exp FF enabled\n self.driver.find_element(By.XPATH, self.add_choice_btn_xpath).click()\n self.driver.find_element(By.XPATH, self.choice_xpath).send_keys(\"location_field_\" + fetch_random_string())\n self.driver.find_element(By.ID, self.save_btn_id).click()\n assert self.driver.find_element(By.XPATH, self.success_msg_xpath).is_displayed()\n self.driver.refresh()\n\n def selection_location_field_for_location_created(self):\n try:\n self.driver.find_element(By.LINK_TEXT, self.org_menu_link_text).click()\n self.wait_to_click(By.XPATH, self.edit_loc_button_xpath)\n self.wait_to_click(By.XPATH, self.additional_info_drop_down)\n self.driver.find_element(By.XPATH, self.select_value_drop_down).click()\n self.driver.find_element(By.XPATH, self.update_loc_xpath).click()\n assert WebDriverWait(self.driver, 2).until(ec.presence_of_element_located((\n By.XPATH, self.success_msg_xpath))).is_displayed()\n except StaleElementReferenceException:\n print(StaleElementReferenceException)\n\n def create_org_level(self):\n self.driver.find_element(By.LINK_TEXT, self.org_level_menu_link_text).click()\n self.wait_to_click(By.XPATH, self.new_org_level_btn_xpath)\n self.driver.find_element(By.XPATH, self.org_level_value_xpath).send_keys(\"loc_level_\" + fetch_random_string())\n self.wait_to_click(By.XPATH, self.save_btn_xpath)\n\n def download_locations(self):\n self.driver.find_element(By.LINK_TEXT, self.org_menu_link_text).click()\n self.driver.find_element(By.LINK_TEXT, self.download_loc_btn).click()\n self.wait_to_click(By.XPATH, self.download_filter)\n try:\n WebDriverWait(self.driver, 20).until(ec.presence_of_element_located((\n By.LINK_TEXT, self.download_loc_btn))).click()\n time.sleep(10)\n except TimeoutException as e:\n print(\"Still preparing for download..\" + str(e))\n assert False\n # verify_downloaded_location\n newest_file = latest_download_file()\n modTimesinceEpoc = (UserInputsData.download_path / newest_file).stat().st_mtime\n modificationTime = datetime.datetime.fromtimestamp(modTimesinceEpoc)\n timeNow = datetime.datetime.now()\n diff_seconds = round((timeNow - modificationTime).total_seconds())\n print(\"Last Modified Time : \", str(modificationTime) + 'Current Time : ', str(timeNow),\n \"Diff: \" + str(diff_seconds))\n assert \"_locations\" in newest_file and diff_seconds in range(0, 600)\n print(\"File download successful\")\n\n def upload_locations(self):\n self.driver.find_element(By.LINK_TEXT, self.org_menu_link_text).click()\n self.driver.find_element(By.LINK_TEXT, self.upload_loc_btn).click()\n newest_file = latest_download_file()\n file_that_was_downloaded = UserInputsData.download_path / newest_file\n self.driver.find_element(By.ID, \"id_bulk_upload_file\").send_keys(str(file_that_was_downloaded))\n time.sleep(2)\n self.wait_to_click(By.XPATH, self.upload)\n assert WebDriverWait(self.driver, 100).until(ec.presence_of_element_located((\n By.XPATH, self.import_complete))).is_displayed()\n print(\"File uploaded successfully\")\n\n def cleanup(self):\n # Delete User Field\n self.wait_to_click(By.LINK_TEXT, self.org_menu_link_text)\n self.wait_to_click(By.XPATH, self.edit_loc_field_btn_xpath)\n self.wait_to_click(By.XPATH, self.delete_loc_field)\n self.wait_to_click(By.XPATH, self.delete_org_level)\n self.wait_to_click(By.ID, self.save_btn_id)\n # Delete Location\n try:\n self.wait_to_click(By.LINK_TEXT, self.org_menu_link_text)\n self.driver.refresh()\n self.wait_to_click(By.XPATH, self.delete_location_created)\n self.driver.find_element(By.XPATH, self.delete_confirm).send_keys(\"1\")\n self.driver.find_element(By.XPATH, self.delete_confirm_button).click()\n except StaleElementReferenceException:\n print(StaleElementReferenceException)\n # Delete Org Level\n org_level_menu = self.driver.find_element(By.LINK_TEXT, self.org_level_menu_link_text)\n self.driver.execute_script(\"arguments[0].click();\", org_level_menu)\n time.sleep(1)\n self.driver.find_element(By.XPATH, self.delete_org_level).click()\n self.wait_to_click(By.XPATH, self.save_btn_delete)\n","sub_path":"Pages/organisationStructurePage.py","file_name":"organisationStructurePage.py","file_ext":"py","file_size_in_byte":12179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353414413","text":"from bow import Bow\nfrom he import He\nimport cv2\nimport numpy as np\n\nclass HeBow(object):\n\n\tdef __init__(self, he, bow):\n\t\tself.he = he\n\t\tself.bow = bow\n\n\t#@params descs the feature matrix of all images\n\tdef fit(self, descs, preprcess=True):\n\t\tif preprcess:\n\t\t\tdescs = self.bow.preprcessing(descs)\n\t\tlist_descs = []\n\t\twords, distance = Bow.flann(descs, self.bow.centers)\n\t\tkeys = list(set(words))\n\t\tassert( len(keys) == len(self.bow.centers) )\n\t\tdictionary = self.DefaultDict(keys, [])\n\t\tfor i, w in enumerate(words):\n\t\t\tdictionary[w].append(descs[i])\n\t\t# generate list_descs, do not use vstack, it's slow\n\t\tlist_descs = []\n\t\tfor idx in xrange(len(keys)):\n\t\t\tlist_descs.append(np.array(dictionary[idx]))\n\n\t@classmethod\n\tdef DefaultDict(cls, keys, default_value):\n\t\t# we also can use setdefault\n\t\tdictionary = {}\n\t\tfor k in keys:\n\t\t\tdictionary[k] = default_value\n\t\treturn dictionary\n\n\n\n","sub_path":"python/CBIR/my_package/HeBow.py","file_name":"HeBow.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"282001694","text":"import time\nimport numpy as np\n\nimport networkx as nx\n\n#from garageofcode.mip.solver import get_solver\nfrom babelsberg import get_solver\n\ndef get_xkcd730_graph():\n G = nx.DiGraph()\n edges = [(0, 1), (0, 7), (0, 9), (0, 10),\n (1, 7), (1, 3), (1, 6),\n (3, 4), (3, 5),\n (4, 5), (4, 9),\n (5, 8),\n (6, 7), (6, 8),\n (7, 8), (7, 9), (7, 12), (7, 13), (7, 14),\n (8, 14),\n (9, 10), (9, 11),\n (10, 11),\n (11, 12), (11, 13),\n (12, 13),\n (13, 14)\n ]\n\n G.add_edges_from(edges)\n return G\n\ndef get_simple_graph():\n G = nx.DiGraph()\n edges = [(0, 1), (0, 2),\n (1, 2), (1, 3),\n (2, 3),\n ]\n G.add_edges_from(edges)\n return G\n\ndef get_potentials(G, s, t):\n # It's not necessary to use a MIP solver for this;\n # it's just a linear equation system.\n # But it makes for a simple formulation.\n\n solver = get_solver(\"couenne\")\n\n t0 = time.time()\n potentials = {node: solver.num_var(lb=0) for node in G}\n currents = {e: solver.num_var() for e in G.edges}\n\n # Edge conditions\n U0, U_1 = 1, 0\n total_potential = U0 - U_1\n solver.add(potentials[s] == U0)\n solver.add(potentials[t] == U_1)\n\n # Kirchoff's law: current is preserved in internal nodes\n for node in G:\n in_current = solver.sum([currents[e] for e in G.in_edges(node)])\n out_current = solver.sum([currents[e] for e in G.out_edges(node)])\n if node == s:\n total_in = out_current - in_current\n elif node == t:\n total_out = in_current - out_current\n else:\n solver.add(in_current == out_current)\n\n # Ohm's law: delta U = I * R\n for e in G.edges:\n i, j = e\n Ui = potentials[i]\n Uj = potentials[j]\n Iij = currents[e]\n Rij = 1 # ignore resistance parameter for now\n solver.add(Ui - Uj == Rij * Iij)\n\n t1 = time.time()\n print(\"Build time: {0:.3f}\".format(t1 - t0))\n\n solver.solve(time_limit=10, verbose=True)\n\n total_current = solver.solution_value(total_in)\n total_resistance = total_potential / total_current\n print(\"Total resistance: {0:.3f}\".format(total_resistance))\n print(\"Total current: {0:.3f}\".format(total_current))\n\n for node, potential in sorted(potentials.items()):\n print(\"{0:d} {1:.3f}\".format(node, solver.solution_value(potential)))\n\ndef main():\n np.random.seed(0)\n G = get_xkcd730_graph()\n #G = get_simple_graph()\n get_potentials(G, 0, max(G))\n\n\nif __name__ == '__main__':\n main()","sub_path":"garageofcode/other/xkcd730.py","file_name":"xkcd730.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584106837","text":"# Copyright 2017 Catalyst IT Limited\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 qinlingclient.common import base\n\n\nclass FunctionExecution(base.Resource):\n pass\n\n\nclass ExecutionManager(base.Manager):\n resource_class = FunctionExecution\n\n def list(self, **kwargs):\n q_list = []\n for key, value in kwargs.items():\n q_list.append('%s=%s' % (key, value))\n q_params = '&'.join(q_list)\n\n url = '/v1/executions'\n if q_params:\n url += '?%s' % q_params\n return self._list(url, response_key='executions')\n\n def create(self, function, version=0, sync=True, input=None):\n data = {\n 'function_id': function,\n 'function_version': version,\n 'sync': sync,\n 'input': input\n }\n return self._create('/v1/executions', data)\n\n def delete(self, id):\n self._delete('/v1/executions/%s' % id)\n\n def get(self, id):\n return self._get('/v1/executions/%s' % id)\n\n def get_log(self, id):\n return self._get('/v1/executions/%s/log' % id, return_raw=True)\n","sub_path":"qinlingclient/v1/function_execution.py","file_name":"function_execution.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"521373356","text":"from setuptools import setup, find_packages\nimport sys, os\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\nlong_description = read('src/z3c/saconfig/README.txt') + '\\n' + read('CHANGES.txt')\n\nsetup(name='z3c.saconfig',\n version='0.14dev',\n description=\"Minimal SQLAlchemy ORM session configuration for Zope\",\n long_description=long_description,\n # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers\n classifiers=['Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Framework :: Zope3',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Zope Public License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Database',\n ],\n keywords='zope relational sqlalchemy component integration',\n author='Martijn Faassen',\n author_email='faassen@startifact.com',\n url='http://pypi.python.org/pypi/z3c.saconfig',\n license='ZPL 2.1',\n packages=find_packages('src'),\n package_dir = {'':'src'},\n namespace_packages=['z3c'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n # -*- Extra requirements: -*-\n 'setuptools',\n 'zope.sqlalchemy>=0.5',\n 'zope.interface',\n 'zope.component',\n 'zope.hookable',\n 'zope.security',\n 'zope.event',\n 'zope.configuration',\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n extras_require = dict(\n test = ['zope.testing'],\n ),\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"227823956","text":"import Printing\nfrom Carbon import Qd\nfrom Carbon import Fm\nfrom Carbon import Res\n\n# some constants\nPostScriptBegin = 190\t# Set driver state to PostScript\t\nPostScriptEnd = 191\t# Restore QuickDraw state\t\nPostScriptHandle = 192\t# PostScript data referenced in handle\n\nCHUNK_SIZE = 0x8000 # max size of PicComment\n\ndef PostScript(text):\n\t\"\"\"embed text as plain PostScript in print job.\"\"\"\n\thandle = Res.Resource('')\n\tQd.PicComment(PostScriptBegin, 0, handle)\n\twhile text:\n\t\tchunk = text[:CHUNK_SIZE]\n\t\ttext = text[CHUNK_SIZE:]\n\t\thandle.data = chunk\n\t\tQd.PicComment(PostScriptHandle, len(chunk), handle)\n\thandle.data = ''\n\tQd.PicComment(PostScriptEnd, 0, handle)\n\n# create a new print record\nprintrecord = Printing.NewTPrintRecord()\n\n# open the printer\nPrinting.PrOpen()\ntry:\n\t# initialize print record with default values\n\tPrinting.PrintDefault(printrecord)\n\t\n\t# page setup, ok is 0 when user cancelled\n\tok = Printing.PrStlDialog(printrecord)\n\tif not ok:\n\t\traise KeyboardInterrupt\n\t# at this stage, you should save the print record in your document for later\n\t# reference. \n\t\n\t# print job dialog, ok is 0 when user cancelled\n\tok = Printing.PrJobDialog(printrecord)\n\tif not ok:\n\t\traise KeyboardInterrupt\n\t\n\t# once per document\n\tport = Printing.PrOpenDoc(printrecord)\n\t# port is the Printer's GrafPort, it is also the current port, so no need to Qd.SetPort(port)\n\ttry:\n\t\t# start printing a page\n\t\t# XXX should really look up what pages to print by\n\t\t# inspecting the print record.\n\t\tPrinting.PrOpenPage(port, None)\n\t\ttry:\n\t\t\t# use QuickDraw like in any other GrafPort\n\t\t\tQd.FrameRect((10, 250, 100, 500))\n\t\t\tQd.FrameRect((10, 510, 100, 600))\n\t\t\tQd.MoveTo(10, 100)\n\t\t\tQd.TextSize(50)\n\t\t\tQd.TextFont(Fm.GetFNum(\"Helvetica\"))\n\t\t\tQd.DrawString(\"It rreally works!\")\n\t\t\tQd.MoveTo(10, 150)\n\t\t\tQd.TextSize(20)\n\t\t\tQd.DrawString(\"(and now for a little PostScript...)\")\n\t\t\t\n\t\t\t# example PostScript code\n\t\t\tps = \"\"\"\n\t\t\t\t% the coordinate system is the quickdraw one, which is flipped\n\t\t\t\t% compared to the default PS one. That means text will appear\n\t\t\t\t% flipped when used directly from PostScript. \n\t\t\t\t% As an example we start by defining a custom scalefont operator \n\t\t\t\t% that corrects this. \n\t\t\t\t/myscalefont{[exch 0 0 2 index neg 0 0]makefont}def\n\t\t\t\t0.75 setgray\n\t\t\t\t0 0 moveto\n\t\t\t\t0 30 lineto 10000 30 lineto\n\t\t\t\t10000 0 lineto closepath fill\n\t\t\t\t0 setgray\n\t\t\t\t5 25 moveto /Courier findfont 20 myscalefont setfont\n\t\t\t\t(Printed with PostScript!) show\n\t\t\t\t2 setlinewidth [10 10 5 10] 0 setdash 5 5 moveto 400 0 rlineto stroke\n\t\t\t\t\"\"\"\n\t\t\t# embed the PostScript code in the print job\n\t\t\tPostScript(ps)\n\t\tfinally:\n\t\t\t# when done with the page\n\t\t\tPrinting.PrClosePage(port)\n\tfinally:\n\t\t# when done with the document\n\t\tPrinting.PrCloseDoc(port)\nfinally:\n\t# when done printing\n\tPrinting.PrClose()\n","sub_path":"Python/MacPython/printing/PrintingDemo.py","file_name":"PrintingDemo.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"214978122","text":"import numpy as np\r\nimport cv2\r\nimport helper as hlp\r\nfrom constants import *\r\nimport imageFunctions as imf\r\n\r\n#List of image filenames such as example below \r\npaths = ['iss030e187822.nef']\r\n\r\n#Convert raw NEF's to BRG arrays and stitch together\r\nimList = imf.convertRawImages(paths, resizeX=resizeX, resizeY=resizeY)\r\nstitched = imf.stitchImages(imList)\r\n\r\n#Increase contrast and convert to grayscale\r\ncontrast = cv2.convertScaleAbs(stitched, alpha=scaleF, beta=0)\r\ngray = cv2.cvtColor(contrast, cv2.COLOR_BGR2GRAY)\r\n\r\n#Blur to remove noise & highpass to isolate\r\nkR, kC = imf.findKSize(gray)\r\ngblur = cv2.GaussianBlur(gray, ksize=(kR, kC), sigmaX=0, sigmaY=0)\r\nhighP = cv2.filter2D(gblur, -1, highPassFilter3)\r\nthresh1 = cv2.threshold(highP, 0, maxVal, cv2.THRESH_OTSU)[1]\r\n\r\n#Calculate initial mask then open & close and remove mask holes\r\nnum = imf.findNum(gray)\r\nmask = hlp.findMask(thresh1, winR=thresh1.shape[1]//25, winC=thresh1.shape[0]//25, num=num)\r\nellipseK = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (mask.shape[0]//75, mask.shape[1]//75))\r\nopened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, ellipseK)\r\nthresh2 = cv2.threshold(opened, halfVal, maxVal, cv2.THRESH_BINARY)[1]\r\nclosed = cv2.morphologyEx(thresh2, cv2.MORPH_CLOSE, ellipseK)\r\nim = hlp.fillMaskHoles(closed)\r\n\r\n#List of images which are first converted to RGB for display\r\nimList = [stitched, contrast, gray, gblur, highP, thresh1, mask, opened, closed, im]\r\nimList = imf.convertBRG2RGB(imList)\r\nimf.plotImages(imList, figX, figY, save=False, show=True)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"392672621","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom project.models import UserInfo\nfrom hashlib import sha1\nfrom django.core.urlresolvers import reverse\n\n\n# Create your views here.\ndef register(request):\n return render(request, 'register.html')\n\n\ndef register_handle(request):\n uname = request.POST.get('user_name')\n upwd = request.POST.get('pwd')\n upwd2 = request.POST.get('cpwd')\n uemail = request.POST.get('email')\n filterResult = UserInfo.objects.filter(uname=uname)\n if filterResult:\n return HttpResponse('用户名已存在')\n else:\n if upwd == upwd2:\n s1 = sha1()\n s1.update(upwd.encode('utf8'))\n upwd3 = s1.hexdigest()\n UserInfo.objects.create(uname=uname, upwd=upwd3, uemail=uemail)\n return redirect('/user/login')\n\n else:\n return HttpResponse('两次密码不一致')\n\n\ndef login(request):\n return render(request, 'login.html')\n\n\ndef login_handle(request): # 登录\n uname = request.POST.get('username')\n upwd = request.POST.get('pwd')\n request.session['uname'] = request.POST['username']\n\n if upwd:\n s2 = sha1()\n s2.update(upwd.encode('utf8'))\n upwd2 = s2.hexdigest()\n userResult = UserInfo.objects.filter(uname=uname, upwd=upwd2)\n if userResult:\n return redirect(reverse('goods:indexs'))\n # else:\n # return HttpResponse('密码错误,重新输入密码')\n\n\ndef logout(request):\n request.session.flush()\n return redirect(reverse('goods:indexs'))\n","sub_path":"demo_end/project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"178231463","text":"import re\nfrom urllib.request import urlopen\n\nfrom bs4 import BeautifulSoup\n\nhtml = urlopen('http://www.pythonscraping.com/pages/page3.html')\nbsObj = BeautifulSoup(html, 'html.parser')\n\n# print('children: ')\n# # for child in bsObj.find('table',{'id':'giftList'}).descendants:\n# for child in bsObj.find('table', {'id': 'giftList'}).children:\n# print(child)\n#\n# print('next: ')\n# for child in bsObj.find('table', {'id': 'giftList'}).tr.next_siblings:\n# print(child)\n#\n# print('previous: ')\n#\n# for child in bsObj.find('table', {'id': 'giftList'}).tr.previous_siblings:\n# print(child)\n\n\nprice = bsObj.find('img', {'src': '../img/gifts/img1.jpg'}).parent.previous_sibling.get_text()\nprint(price)\n\nimages = bsObj.findAll('img', {'src': re.compile('\\.\\./img/gifts/img\\d+\\.jpg')})\nfor img in images:\n print(img['src'])\n\nvalues = bsObj.findAll('td', text=re.compile('\\$\\d*(,|)*\\d*\\.\\d+'))\nfor v in values:\n print(v.get_text())\n","sub_path":"Page3.py","file_name":"Page3.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"424975023","text":"#_*_ coding: utf-8 _*_\nfrom django.shortcuts import render\nfrom .models import UserMessage\n# Create your views here.\ndef getform(request):\n\n # all_messages = UserMessage.objects.filter(name='bobby') # type: object\n # for message in all_messages:\n # print message.name\n # 读取数据\n\n # user_message = UserMessage()\n # user_message.name='zhaorenqun'\n # user_message.message='hello2'\n # user_message.address='上海'\n # user_message.email='2@2.com'\n # user_message.object_id='hello2'\n # user_message.save()\n # 保存数据\n\n # if request.method == 'POST':\n # name = request.POST.get('name','')\n # message=request.POST.get('message','')\n # email = request.POST.get('email', '')\n # address = request.POST.get('address', '')\n # user_message = UserMessage()\n # user_message.name=name\n # user_message.message=message\n # user_message.address=address\n # user_message.email=email\n # user_message.object_id='3test'\n # user_message.save()\n #页面数据写入\n\n # all_messages = UserMessage.objects.filter(name='bobby',address='北京') # type: object\n # # all_messages.delete() 删除1\n # for message in all_messages:\n # message.delete()\n # #数据删除\n\n message=None\n all_messages = UserMessage.objects.filter(name='bobby')\n if all_messages:\n message=all_messages[0]\n return render(request, 'message_form.html',{\n \"my_message\":message\n })","sub_path":"djangostart/message/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"411030050","text":"# -*-coding: utf-8 -*-\n\nimport os\nimport time\nimport re\nimport csv\n\ndef get_mgcError(): # 获取mgc错误信息统计\n \n mgc_num = ['#419b','#519b','#b19b','#c19b']\n mgc_error_info = []\n get_mgc_cmd = './nvme dera get-log /dev/nvme0'\n \n for mgc in mgc_num:\n mgc_ready_cmd = \"./nvme dera uart-in -p '{0} 0 0' /dev/nvme0\".format(mgc)\n os.popen(mgc_ready_cmd)\n time.sleep(1)\n get_current_mgc_error_info = os.popen(get_mgc_cmd).readlines() # 获取当前mgc的error info 信息\n mgc_error_info.extend(get_current_mgc_error_info) # 存储到mgc_error_info变量中\n \n return mgc_error_info\n\ndef list_to_csv(list_name, filename): # 将数据转换为csv格式的文件\n # 检查列表是否为空\n if not list_name:\n print('list is empty.')\n return\n # 调用re.split()对list逐个字符元素进行分割,非字符元素将被丢弃\n selected_list = []\n # print(list_name) # kou debug...\n for list_line in list_name:\n selected = []\n if isinstance(list_line, str):\n list_line.strip('\\n')\n if 'ERRBit' in list_line:\n splited = re.split(r'[.=,]', list_line) # 将长字符以 . , = 为分界,分解为列表\n if len(splited) < 10:\n selected = [list_line] \n else:\n selected = [splited[5], splited[7], splited[9]]\n # print(splited)\n elif 'ERRUNC' in list_line:\n splited = re.split(r'[.=,>]', list_line)\n if len(splited) < 10:\n selected = [list_line] \n else:\n selected = ['>72', splited[7], splited[9]]\n # print(splited)\n elif 'TotalReadECCFrameCnt' in list_line:\n splited = re.split(r'[,=]', list_line)\n if len(splited) < 7:\n selected = [list_line]\n else:\n selected = ['Total',splited[2], splited[4]]\n # selected = ['Total',splited[2], splited[4]]\n # print(splited)\n # print(selected)\n elif 'cpu_mask' in list_line:\n splited = re.split(r'[ ]', list_line)\n if len(splited) < 10:\n selected = [list_line]\n else:\n selected = ['cpu_mask', splited[9]]\n elif not list_line:\n continue\n # print(selected) \n selected_list.append(selected)\n with open(filename,'a',newline='') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(['ErrBit','FrameCnt','Rate'])\n data = selected_list\n writer.writerows(data)\n csv_file.close()\n return\n\nlist_name = get_mgcError()\nlist_to_csv(list_name,'50-50.csv')\n","sub_path":"ThermalShock/mgcError.py","file_name":"mgcError.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"462938189","text":"import numpy as np\nimport pandas as pd\nimport os\n\nfrom pandas import Series, DataFrame\nfrom sklearn.linear_model import LogisticRegression\n\n\n# Clear function for the console.\nclear = lambda: os.system(\"cls\")\n\nbank_full = pd.read_csv('bank_full_w_dummy_vars.csv')\n# print(bank_full.head())\n\n# Returns a description of the dataset.\n# print(bank_full.info())\n\n# Define the columns that will be used to train the model. Also define the predicted variable.\nX = bank_full.iloc[:,18:37].values\ny = bank_full.iloc[:,17].values\n\n# Build and train the model.\nLogReg = LogisticRegression()\nLogReg.fit(X, y)\n\n# Display the results.\nnew_user = [[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]]\ny_pred = LogReg.predict(new_user)\n\nif y_pred == 0:\n print(\"The customer won't accept the offer.\")\nelse:\n print(\"The customer will accept the offer.\")\n","sub_path":"3. Advance Your Skills as a Python Data Expert/1. Building a Recommendation System with Python Machine Learning & AI/Machine Learning Recommendation Systems/classificationBased.py","file_name":"classificationBased.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"281247973","text":"# -*- coding: utf-8 -*-\n\"\"\"\n facti.controller.claim_show\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n 응답을 얻기 위해 Worker에게 각 클레임을 보여주는 것\n\n :은지시도본\n\"\"\"\n\nfrom flask import request, current_app, send_from_directory \\\n , render_template, session, url_for, redirect, abort, make_response\nfrom math import ceil\nfrom datetime import datetime\nimport random\n\nfrom facti.database import dao\nfrom facti.model.claim import Claim\nfrom facti.controller.admin_login import login_required\nfrom facti.controller.get_answers import get_answers, GetAnswerForm\nfrom facti.facti_blueprint import facti\nfrom facti.facti_logger import Log\nfrom facti.facti_config import FactiConfig as config\nfrom facti.model.worker import Worker\nfrom facti.model.key import Key\n\nfrom boto.mturk.connection import MTurkConnection, Assignment\n\n\ndef url_for_other_page(page):\n args = request.view_args.copy()\n args['page'] = page\n return url_for(request.endpoint, **args)\n\n@facti.route('/claim/', defaults={'page': 1}, methods=['GET', 'POST'])\n@facti.route('/claim/page/', methods=['GET', 'POST'])\n# @agreement_required\ndef show_claim(page):\n form = GetAnswerForm(request.form)\n\n # 세팅\n count = dao.query(Claim).count()\n page = page\n per_page = current_app.config['PER_PAGE']\n pagination = Pagination(page, per_page, count)\n\n claims_shuffled = session['claims_shuffled']\n claim_page = claims_shuffled[page-1]\n\n\n # 첫 번째 페이지의 타임스탬프\n\n # if session['timestamp']:\n\n # session['timestamp'] = datetime.utcnow()\n # timestamp = session['timestmap']\n if not 'timestamp' in session:\n timestamp = datetime.today()\n\n else:\n timestamp = session['timestamp']\n\n # 응답 얻는 부분 (get_answers)\n if request.method == 'POST':\n if get_answers(claim_page.id, page, count, timestamp):\n\n if page != count:\n return redirect(url_for_other_page(page + 1))\n\n else:\n # mtc = MTurkConnection(aws_access_key_id=config.MTURK_ACCESS_ID,\n # aws_secret_access_key=config.MTURK_SECRET_KEY,\n # host=config.MTURK_HOST)\n # assignmentId = Assignment(mtc).AssignmentId\n surveycode = add_serial_key()\n\n resp = make_response(render_template('end.html', surveycode=surveycode))\n\n resp.headers['x-frame-options'] = 'ALLOW-FROM'\n return resp\n\n\n # 클레임 보여주는 부분 (show_claim)\n # if page != 1:\n # offset = per_page * (page - 1)\n # else:\n # offset = 0\n\n\n resp = make_response\\\n (render_template('claim.html',\n pagination=pagination,\n claims=claims_shuffled,\n claim=claim_page,\n count=count,\n page=page,\n form=form))\n\n\n # This is particularly nasty gotcha.\n # Without this header, your iFrame will not render in Amazon\n resp.headers['x-frame-options'] = 'ALLOW-FROM'\n # ''ALLOW-FROM ' + config.MTURK_HOST\n return resp\n\n\ndef add_serial_key():\n # 160816 EJ\n surveycode = serial_gen()\n currentWorkerId = session['worker_info'].id\n while 1:\n if dao.query(Key).filter(Key.serialKey == surveycode).count() == 0:\n serialKey = Key(currentWorkerId, surveycode)\n dao.add(serialKey)\n dao.commit()\n break\n else:\n surveycode = serial_gen()\n return surveycode\n\n\ndef serial_gen(count=3):\n seq = \"ABCDFGHJIKLMNOPQRSTUVWXYZ1234567890\"\n\n for i in range(count):\n genkey = ('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)))\n\n return genkey\n\n\n\nclass Pagination(object):\n\n def __init__(self, page, per_page, total_count):\n self.page = page\n self.per_page = per_page\n self.total_count = total_count\n\n @property\n def pages(self):\n return int(ceil(self.total_count / float(self.per_page)))\n\n @property\n def has_prev(self):\n return self.page > 1\n\n @property\n def has_next(self):\n return self.page < self.pages\n\n def iter_pages(self, left_edge=2, left_current=2,\n right_current=5, right_edge=2):\n last = 0\n for num in xrange(1, self.pages + 1):\n if num <= left_edge or \\\n (num > self.page - left_current - 1 and \\\n num < self.page + right_current) or \\\n num > self.pages - right_edge:\n if last + 1 != num:\n yield None\n yield num\n last = num\n\n\n@facti.route('/admin/keys/remove')\n@login_required\ndef keys_remove_all():\n \"\"\" DB에서 해당 데이터를 삭제하고 관련된 이미지파일을 함께 삭제한다.\"\"\"\n\n try:\n keys = dao.query(Key).all()\n\n for key in keys:\n dao.delete(key)\n dao.commit()\n\n except Exception as e:\n dao.rollback()\n Log.error(\"admin remove error => \"\n + str(e))\n raise e\n\n return redirect(url_for('facti.show_all_keys'))\n","sub_path":"facti/controller/claim_show.py","file_name":"claim_show.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"6214363","text":"'''\nCreated on Aug 12, 2013\n\n@author: lindahlm\n'''\n\n\nfrom core.network.default_params import Perturbation_list as pl\nimport numpy\nimport pprint\nfrom core_old.toolbox import misc\npp=pprint.pprint\n\nfrom oscillation_perturbations8 import get_solution, update\n\n\ndef get():\n \n\n \n l=[]\n solution, s_mul, s_equal=get_solution()\n \n d0=0.8\n f_beta_rm=lambda f: (1-f)/(d0+f*(1-d0))\n \n \n # betas MS-MS\n v=numpy.arange(1.5,3,0.25)\n for x in v:\n \n d={}\n for keys in s_mul: update(solution, d, keys) \n l+=[pl(d, '*', **{'name':''})]\n \n d={}\n for keys in s_equal: update(solution, d, keys) \n \n misc.dict_update(d,{'nest':{'ST':{'beta_I_AMPA_1': f_beta_rm(x)}}})\n misc.dict_update(d,{'nest':{'ST':{'beta_I_NMDA_1': f_beta_rm(x)}}})\n\n l[-1]+=pl(d, '=', **{'name':'mod_ST_beta_'+str(x)}) \n \n v1=numpy.arange(0.1, 1, 0.2)\n for x in v1:\n \n \n d={}\n for keys in s_mul: update(solution, d, keys) \n\n l+=[pl(d, '*', **{'name':''})]\n \n d={}\n for keys in s_equal: update(solution, d, keys)\n \n d['node']['EA']['rate']*=x\n l[-1]+=pl(d, '=', **{'name':'mod_EA_'+str(x)}) \n \n v2=numpy.arange(1.1, 2, 0.2)\n for x in v2:\n \n \n d={}\n for keys in s_mul: update(solution, d, keys) \n\n l+=[pl(d, '*', **{'name':''})]\n \n d={}\n for keys in s_equal: update(solution, d, keys)\n \n d['node']['EI']['rate']*=x\n l[-1]+=pl(d, '=', **{'name':'mod_EI_'+str(x)}) \n \n return l\n\nget()","sub_path":"python/scripts_inhibition/old_script/oscillation_perturbations12.py","file_name":"oscillation_perturbations12.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433458178","text":"from sklearn import svm, datasets, metrics\nfrom sklearn.model_selection import validation_curve, learning_curve\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndb = datasets.load_digits()\n\nX = db.data\nY = db.target\n\nnp.random.seed(0)\n\nn_samples = len(X)\npercentage = 0.75\n\norder = np.random.permutation(n_samples)\n\nX = X[order]\nY = Y[order]\n\nY_teste = Y[int(percentage*n_samples):]\nX_teste = X[int(percentage*n_samples):]\n\nY_treino = Y[:int(percentage*n_samples)]\nX_treino = X[:int(percentage*n_samples)]\n\nC = [x for x in range(1,11)]\n\nclf = svm.SVC(gamma='scale')\n\ntrain_scores, validation_scores = validation_curve(clf,X_treino,Y_treino,\"C\",C,verbose=3,cv=5)\ntrain_sizes, train_scores_lc, validation_scores_lc = learning_curve(clf,X_treino,Y_treino,cv=5)\n\ntrain_scores_mean = np.mean(train_scores,axis=1)\ntrain_scores_std = np.std(train_scores,axis=1)\nvalidation_scores_mean = np.mean(validation_scores,axis=1)\nvalidation_scores_std = np.std(validation_scores,axis = 1)\n\ntrain_scores_mean_lc = np.mean(train_scores_lc,axis=1)\ntrain_scores_std_lc = np.std(train_scores_lc,axis=1)\nvalidation_scores_mean_lc = np.mean(validation_scores_lc,axis=1)\nvalidation_scores_std_lc = np.std(validation_scores_lc,axis = 1)\n\nplt.subplot(1,2,1)\nplt.title(\"Curva de validação com SVM\")\nplt.xlabel(\"C\")\nplt.ylabel(\"Score\")\n\nmin_all = np.min([np.min(train_scores),np.min(validation_scores)])\n\nplt.ylim(min_all,1.001)\nplt.grid()\nparam_range = list(range(1,len(C)+1))\n#Largura da linha\nlw = 2\nplt.plot(param_range,train_scores_mean,'o-',label='Training Score',lw=lw)\nplt.fill_between(param_range,train_scores_mean-train_scores_std,train_scores_mean+train_scores_std,alpha=0.2,lw=lw)\n\nplt.plot(param_range,validation_scores_mean,'o-',label='Validation Score',lw=lw)\nplt.fill_between(param_range,validation_scores_mean-validation_scores_std,validation_scores_mean+validation_scores_std,alpha=0.2,lw=lw)\n\nplt.legend(loc=\"best\")\n\nplt.subplot(1,2,2)\n\nplt.title(\"Curva de aprendizado com SVM\")\nplt.xlabel(\"Exemplos de Treino\")\nplt.ylabel(\"Score\")\nplt.grid()\n\nmin_all = np.min([np.min(train_scores_lc),np.min(validation_scores_lc)])\n\nplt.ylim(min_all,1.001)\n\n#Largura da linha\nlw = 2\nplt.plot(train_sizes,train_scores_mean_lc,'o-',label='Training Score',lw=lw)\nplt.fill_between(train_sizes,train_scores_mean_lc-train_scores_std_lc,train_scores_mean_lc+train_scores_std_lc,alpha=0.2,lw=lw)\n\nplt.plot(train_sizes,validation_scores_mean_lc,'o-',label='Validation Score',lw=lw)\nplt.fill_between(train_sizes,validation_scores_mean_lc-validation_scores_std_lc,validation_scores_mean_lc+validation_scores_std_lc,alpha=0.2,lw=lw)\n\nplt.legend(loc=\"best\")\n\nplt.show()","sub_path":"venv/validacao.py","file_name":"validacao.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27945036","text":"#!/usr/bin/env python\n\n##############\n# Multi CRAB #\n##############\n\nimport time \nimport os\n\nif __name__ == '__main__':\n from CRABAPI.RawCommand import crabCommand\n\ndef submit(config):\n res = crabCommand('submit', config = config)\n\nfrom CRABClient.UserUtilities import config\nconfig = config()\n\nnfiles = -1 \n#nfiles = 16 \nuntsPerJob = 1\n\n# mask = 'https://cms-service-dqm.web.cern.ch/cms-service-dqm/CAF/certification/Collisions16/13TeV/ReReco/Final/Cert_271036-284044_13TeV_23Sep2016ReReco_Collisions16_JSON.txt'\nmask = 'https://cms-service-dqm.web.cern.ch/cms-service-dqm/CAF/certification/Collisions17/13TeV/ReReco/Cert_294927-306462_13TeV_EOY2017ReReco_Collisions17_JSON.txt'\n\nconfig.General.transferLogs = True\nconfig.General.transferOutputs = True\nconfig.JobType.pluginName = 'Analysis'\n# config.JobType.numCores = 4\nconfig.JobType.maxMemoryMB = 5000\nconfig.Data.inputDBS = 'global'\nconfig.JobType.psetName = 'PSet.py'\nconfig.JobType.scriptExe = 'crab_script.sh'\nconfig.JobType.inputFiles = [\n 'Cert_294927-306462_13TeV_EOY2017ReReco_Collisions17_JSON.txt', \n 'keep_and_drop.txt', \n 'crab_script.py',\n '../../PhysicsTools/NanoAODTools/scripts/haddnano.py' #hadd nano will not be needed once nano tools are in cmssw\n ] \nconfig.JobType.outputFiles = ['tree.root'] \nconfig.Data.splitting = 'FileBased'\nconfig.Data.publication = False\nconfig.JobType.sendPythonFolder = True\n# config.Site.storageSite = 'T2_CH_CERN'\nconfig.Site.storageSite = 'T3_US_FNALLPC'\n\nconfig.Data.ignoreLocality = False\n\n\n#config.Site.whitelist = ['T3_CH_CERN_CAF'] #Required for CAF submission\n#config.Site.whitelist = ['T2_US_Nebraska'] \n# config.Site.whitelist = ['T2_BE_IIHE', 'T2_CH_CERN', 'T2_DE_DESY', 'T2_IN_TIFR', 'T2_US_Wisconsin']\nconfig.Site.whitelist = ['T2_US_*']\n#config.Site.ignoreGlobalBlacklist = True\n#config.Site.ignoreGlobalBlacklist = False\n\n\n\ndataset = {\n 'SingleMuon_Run2017B' : '/SingleMuon/Run2017B-31Mar2018-v1/NANOAOD', \n 'SingleMuon_Run2017C' : '/SingleMuon/Run2017C-31Mar2018-v1/NANOAOD', \n 'SingleMuon_Run2017D' : '/SingleMuon/Run2017D-31Mar2018-v1/NANOAOD', \n 'SingleMuon_Run2017E' : '/SingleMuon/Run2017E-31Mar2018-v1/NANOAOD', \n 'SingleMuon_Run2017F' : '/SingleMuon/Run2017F-31Mar2018-v1/NANOAOD', \n}\n\ndef getFilesList(sample):\n # return [ \"root://cms-xrd-global.cern.ch/\" + s for s in os.popen('dasgoclient -query=\"file dataset=\"'+ sample).read().split()]\n return [ \"root://cmsxrootd.fnal.gov/\" + s for s in os.popen('dasgoclient -query=\"file dataset=\"'+ sample).read().split()]\n\ndef doSubmit(listOfSamples):\n for sample in listOfSamples:\n newName = sample+name\n config.General.workArea = 'crab_'+newName\n config.General.requestName = sample\n # config.Data.inputDataset = dataset[sample]\n # config.Data.unitsPerJob = untsPerJob\n config.Data.unitsPerJob = 1\n # config.Data.totalUnits = nfiles\n config.Data.totalUnits = -1\n config.Data.outputDatasetTag = sample\n # config.Data.lumiMask = mask\n config.Data.outputPrimaryDataset = sample\n config.Data.userInputFiles = getFilesList(dataset[sample])\n # print config.Data.userInputFiles\n config.Data.outLFNDirBase = '/store/user/ftorresd/HZtoUpsilonPlusPhotonSamples2017/NanoPost/test' + newName # or '/store/group/'\n submit(config)\n\n\n# SingleMuon_Run2017B\nnfiles = 10\nuntsPerJob = 4\nname = '_nanoPost_v15'\nlistOfSamples = ['SingleMuon_Run2017B', ]\ndoSubmit(listOfSamples)\n\n\n","sub_path":"Skimming/multiCRAB_Data.py","file_name":"multiCRAB_Data.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68843","text":"# -*- coding: utf-8 -*-\nimport os\nimport time\n\n__author__ = 'sean'\n\nimport subprocess\nimport threading\n\nclass MonkeyThread(threading.Thread):\n # monkey_execu = \"ping -c 10 www.baidu.com\"\n monkey_execu = \"\"\n # monkey_report = \"ping -c 10 www.163.com\"\n monkey_report = \"\"\n execu_process = None\n report_process = \"unbegin\"\n check_thread = None\n process_flag = False\n\n def __init__(self, deviceid, time, package_name,log_path,apk_path=None):\n # print(deviceid + str(time) + package_name + log_path + str(apk_path))\n threading.Thread.__init__(self)\n\n if not os.path.exists(\"./result/\" + log_path):\n os.mkdir(\"./result/\" + log_path)\n self.original_path = os.getcwd()\n os.chdir(self.original_path + \"/result/\" + log_path)\n os.system(\"cp -R \" + self.original_path + \"/extra/dist/\" + \" ./\")\n\n self.monkey_execu = \"java -jar monkey-adapter-runner.jar \" \\\n \" --device-id \" + deviceid + \\\n \" --user-name task_server \" \\\n \" --pkg-name \" + package_name + \\\n \" --single-duration \" + str(time) + \\\n \" --series-duration \" + str(time)\n if apk_path is not None:\n self.monkey_execu += \" --pkg-path \" + apk_path\n\n self.monkey_report = \"java -jar monkey-adapter-analyzer.jar \" \\\n \" --workspaces \" + os.getcwd() + \"/logs/ \" + \\\n \" --monkey-log-file-name monkey_log.txt \" \\\n \" --logcat-log-file-name logcat_log.txt \" \\\n \" --traces-log-file-name traces_log.txt \" \\\n \" --bugreport-log-file-name bugreport_log.txt \" \\\n \" --properties-file-name properties.txt \" \\\n \" --duration \" + str(time) + \\\n \" --package-name \" + package_name\n # print(self.monkey_execu)\n # print(self.monkey_report)\n\n\n\n self.thread_stop = False\n\n def run(self):\n os.system(\"adb kill-server\")\n os.system(\"adb start-server\")\n time.sleep(5)\n self.execu_process = subprocess.Popen(self.monkey_execu, shell=True)\n os.chdir(self.original_path)\n while not self.thread_stop:\n if not self.process_flag:\n result = self.execu_process.poll()\n if result is None:\n continue\n if result == 0:\n self.monkey_repo()\n self.process_flag = True\n else:\n result = self.report_process.poll()\n if result is None:\n continue\n else:\n break\n os.chdir(self.original_path)\n\n def monkey_repo(self):\n self.report_process = subprocess.Popen(self.monkey_report, shell=True)\n\n def kill(self):\n os.chdir(self.original_path)\n try:\n self.execu_process.kill()\n except:\n pass\n try:\n self.report_process.kill()\n except:\n pass\n self.thread_stop = True\n\n def poll(self):\n result = None\n if self.report_process != None and self.report_process != \"unbegin\":\n result = self.report_process.poll()\n return result\n if self.execu_process != None:\n result = self.execu_process.poll()\n return result","sub_path":"lib/MonkeyThread.py","file_name":"MonkeyThread.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115855807","text":"# -*- coding: utf-8 -*-\n# TextFileContent.py - file text container class source\n# author: Mrukwa Grzegorz\n\n'''This module implements storing data.\n\nThis module implements class with function which gives us ONLY correct words from user input.'''\n\nMIN_WORD_LEN = 4\nDELIMITER = ' '\n\n# Class containing every string between spaces in text file choosen by user.\nclass TextContainer:\n # Constructor inputing data from selected file.\n def __init__(self, userInput):\n self.words = []\n for content in userInput.content:\n for line in content.split('\\n'):\n for word in line.split(DELIMITER):\n if len(word) > 0:\n if (word[-1] != ',') & (word[-1] != '.'):\n self.words.append(word)\n else:\n self.words.append(word[0:-1])\n else:\n pass\n \n # Function returning array with correct words and its size.\n def CorrectWords(self):\n correctWords = []\n numberOfCorrectWords = 0\n for word in self.words:\n if (len(word) >= MIN_WORD_LEN) & word.isalpha():\n correctWords.append(word)\n numberOfCorrectWords = numberOfCorrectWords + 1\n return { 'CorrWords' : correctWords, 'NumOfCorrWords' : numberOfCorrectWords}\n","sub_path":"mrukwa_grzegorz/TextFiles/TextFileContent.py","file_name":"TextFileContent.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"653744937","text":"#售票多线程模型\nimport threading\nimport time\nimport os\nimport logging\ndef sale():\n time.sleep(0.5)\nclass BoothThread(threading.Thread):\n def __init__(self, tid, monitor):\n self.tid = tid\n self.monitor = monitor\n threading.Thread.__init__(self)\n def run(self):\n while True:\n monitor['lock'].acquire()\n if monitor['tick'] != 0 :\n monitor['tick'] = monitor['tick'] - 1\n print(self.tid,'left :',monitor['tick']) \n sale()\n else:\n print(\"thread_id\", self.tid,\"no more tickets\")\n os._exit(0)\n monitor['lock'].release()\n \nmonitor = {'tick':10000,'lock':threading.Lock()}\n\nfor k in range(10):\n print(k)\n new_thread = BoothThread(k,monitor)\n new_thread.start()\n","sub_path":"Booth.py","file_name":"Booth.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551556263","text":"# -*- coding: utf-8 -*-\nimport chardet\nimport json\nimport urllib.request\n\nf=urllib.parse.quote(input())\nurl = ('http://apis.baidu.com/apistore/weatherservice/cityname?cityname=%s'%f)\nreq = urllib.request.Request(url)\nreq.add_header(\"apikey\", \"fcb9af3a86a690d8703879054291888a\")\nresp = urllib.request.urlopen(req)\ncontent = resp.read()\nif(content):\n\tcontents = content.decode(encoding='ASCII')\n\tdata = json.loads(contents)\n\tstr_tmp = ('%s\\n%s\\n%s\\n%s\\n%s\\n' % (data['retData']['city'],data['retData']['weather'],data['retData']['h_tmp'],data['retData']['WD'],data['retData']['l_tmp']))\n\tc = str_tmp.encode(\"utf-8\")\n\tprint(chardet.detect(c))\n\td=c.decode('utf-8')\n\tprint(type(d))\n\tf = open('data.txt', 'a')\n\tf.write(d)\n\tf.close()\n\tf=open('data.txt')\n\ta=f.read()\n\tprint(a)","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"194090829","text":"import sys\nfrom PySide2.QtWidgets import QApplication, QMainWindow, QMdiArea, QMessageBox\nfrom PySide2.QtCore import Slot\n\nfrom views.add_reservation_window import AddReservationWindow\nfrom views.apartments_window import ApartmentsWindow\nfrom views.guests_window import GuestsWindow\nfrom views.reservations_window import ReservationsWindow\nfrom views.main_window import MainWindow\nimport services.mongo_setup as db_setup\n\n\nclass MDIWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.mdi = QMdiArea()\n self.setCentralWidget(self.mdi)\n menu = self.menuBar()\n\n apartments = menu.addAction(\"Apartments\")\n apartments.triggered.connect(self.ShowApartments)\n\n reservations = menu.addMenu(\"Reservations\")\n reservations_add = reservations.addAction(\"Add\")\n reservations_add.setShortcut('Ctrl+N')\n reservations_add.triggered.connect(self.AddReservations)\n reservations_view = reservations.addAction(\"View\")\n reservations_view.triggered.connect(self.ShowReservations)\n\n users = menu.addAction(\"Users\")\n users.triggered.connect(self.ShowUsers)\n\n help = menu.addAction(\"Help\")\n help.triggered.connect(self.ShowHelp)\n\n self.setWindowTitle(\"Hotel app\")\n self.ShowMainWindow()\n\n @Slot()\n def ShowMainWindow(self):\n self.main_window = MainWindow(self.mdi)\n self.main_window.showMaximized()\n\n @Slot()\n def AddReservations(self):\n print(\"reservations add\")\n self.closeMainWindow()\n add_reservations_window = AddReservationWindow(self.mdi)\n add_reservations_window.destroyed.connect(self.ShowMainWindow)\n add_reservations_window.createNewUser.connect(self.ShowUsers)\n\n @Slot()\n def ShowReservations(self):\n print(\"reservations view\")\n self.closeMainWindow()\n reservations_window = ReservationsWindow(self.mdi)\n reservations_window.destroyed.connect(self.ShowMainWindow)\n\n @Slot()\n def ShowApartments(self, p):\n #add singleton\n self.closeMainWindow()\n apartments_window = ApartmentsWindow(self.mdi)\n apartments_window.destroyed.connect(self.ShowMainWindow)\n\n @Slot()\n def ShowUsers(self):\n #add singleton\n self.closeMainWindow()\n users_window = GuestsWindow(self.mdi)\n users_window.destroyed.connect(self.ShowMainWindow)\n\n @Slot()\n def ShowHelp(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"This is help\")\n msg.exec_()\n print(\"Help\")\n\n def closeMainWindow(self):\n if self.main_window:\n self.main_window.close()\n self.main_window = None\n\n\nif __name__ == \"__main__\":\n db_setup.global_init()\n\n app = QApplication(sys.argv)\n mdi = MDIWindow()\n\n mdi.setMaximumSize(800, 600)\n mdi.setMinimumSize(800, 600)\n\n mdi.show()\n app.exec_()\n","sub_path":"Lections/Lection 18/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"240190054","text":"# -*- coding: utf-8 -*-\n\"\"\"\nModel solution for session one of the AZ Practical Python Course.\n\nThis script implements the ROT cipher, supplying functions both for encryption\nand decryption. The solution is compatible with messages containing alphabetic\ncharacters and spaces only, and any integer choice of rotation is valid.\nValidation is performed to ensure that inputs are appropriate. Furthermore,\na selection of tests are included to verify the workings of the script. This\nsection can generally be ignored; it is included simply to show what best\npractice looks like for developing Python scripts.\n\n@author: Tim Hargreaves\n\"\"\"\n\n\nimport unittest\n\n\ndef rot_encrypt(msg, rot=13):\n \"\"\"\n Encrypt a message using the ROT cipher.\n\n Accepts a message and rotation and applies the ROT cipher to encrypt it.\n The message is first converted to all upper case before encrypting.\n\n Args:\n msg (str): The message to be encrypted.\n Must only contain alphabetic characters and spaces.\n rot (int): The number of clockwise rotations to perform for encryption.\n Defaults to 13.\n\n Returns:\n enc (str): The encrypted message.\n Will only contain upper case letters and spaces.\n\n Raises:\n TypeError: If `msg` is not a string or `rot` is not an integer.\n ValueError: If `msg` contains characters other than alphabetic\n characters and spaces.\n \"\"\"\n # validate inputs\n if not isinstance(msg, str):\n raise TypeError(\"msg must be a string\")\n if not isinstance(rot, int):\n raise TypeError(\"rot must be an integer\")\n\n # handle spaces by calling the function recursively\n if ' ' in msg:\n return ' '.join(rot_encrypt(m, rot) for m in msg.split(' '))\n elif not msg.isalpha():\n raise ValueError(\"msg can only contain alphabet characters and spaces\")\n\n # convert to all upper case\n msg = msg.upper()\n\n # convert to numeric representation (A = 0, B = 1, ...)\n num_rep = [ord(c) - 65 for c in msg]\n\n # encrypt\n enc_num_rep = [(n + rot) % 26 for n in num_rep]\n\n # convert to text\n enc = ''.join(chr(n + 65) for n in enc_num_rep)\n\n return enc\n\n\ndef rot_decrypt(msg, rot=13):\n \"\"\"\n Decrypt a message using the ROT cipher.\n\n Accepts a message and rotation and applies the ROT cipher to decrypt it.\n This function is simply a wrapper for the `rot_encrypt` function due to\n the symmetric nature of encryption/decryption with the ROT cipher. See\n the docs for `rot_encrypt` for help with this function.\n \"\"\"\n return rot_encrypt(msg, -rot)\n\n\nclass TestROTCipher(unittest.TestCase):\n \"\"\"A class for testing the ROT cipher.\"\"\"\n\n def test_default_rot(self):\n msg = 'SPAM'\n enc = rot_encrypt(msg)\n self.assertEqual(enc, 'FCNZ')\n self.assertEqual(msg, rot_decrypt(enc))\n\n def test_custom_rot(self):\n msg = 'SPAM'\n rot = 17\n enc = rot_encrypt(msg, rot)\n self.assertEqual(enc, 'JGRD')\n self.assertEqual(msg, rot_decrypt(enc, rot))\n\n def test_with_spaces(self):\n msg = 'SPAM EGGS SPAM'\n enc = rot_encrypt(msg)\n self.assertEqual(enc, 'FCNZ RTTF FCNZ')\n self.assertEqual(msg, rot_decrypt(enc))\n\n def test_lower_case(self):\n msg = 'SpAm'\n enc = rot_encrypt(msg)\n self.assertEqual(enc, 'FCNZ')\n self.assertEqual(msg.upper(), rot_decrypt(enc))\n\n def test_invalid_message(self):\n with self.assertRaises(TypeError):\n rot_encrypt(123)\n with self.assertRaises(ValueError):\n rot_encrypt('5PAM')\n\n def test_invalid_rot(self):\n with self.assertRaises(TypeError):\n rot_encrypt('SPAM', 1.23)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"session_one/session_one_project_solutions.py","file_name":"session_one_project_solutions.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"604013509","text":"\"\"\"How many NFE samples are covered here?\"\"\"\nimport argparse\nimport pullExacVarsForEnrichment\n\ndef getGenes(effField):\n regionAndAltLs = set( [ (x.split('(')[0], x.split('|')[3], x.split('|')[5]) for x in effField.split('EFF=')[1].split(',') if '_variant' in x] )\n genes = set()\n for region,alt,candGene in regionAndAltLs:\n if not region in pullExacVarsForEnrichment.badSet:\n genes.add(candGene)\n return genes\n\ndef main(args):\n useGenes = set()\n with open(args.geneFile) as f:\n for line in f:\n useGenes.add( line.strip() )\n \n with open(args.exacVcf) as f, open(args.outFile, 'w') as fout:\n print('\\t'.join( ('chrom', 'pos', 'gene', 'chromCount') ), file=fout)\n for line in f:\n if line[0] != '#':\n sp = line.strip().split()\n chrom = sp[0]\n pos = sp[1]\n p = 'AN_' + args.pop + '='\n effField = sp[-1]\n if p in sp[7]:\n genes = getGenes(sp[7])\n if genes and useGenes:\n count = effField.split(p)[1].split(';')[0]\n for gene in genes:\n print('\\t'.join( (chrom, pos, gene, count) ), file=fout)\n \nif __name__ == \"__main__\":\n desc = 'Rm high freq vars in 1kg tot or 1kg all.'\n parser = argparse.ArgumentParser(description=desc)\n argLs = ('pop', 'exacVcf', 'geneFile', 'outFile',)\n for param in argLs:\n parser.add_argument(param)\n args = parser.parse_args()\n main(args)\n","sub_path":"code/parseExacVarSamplesExamined.py","file_name":"parseExacVarSamplesExamined.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181801075","text":"from __future__ import print_function\nfrom datetime import datetime\nimport pytz\nimport urllib #.request\nimport json\nimport pandas as pd\nfrom fuzzywuzzy import process\nimport tools\n#import MySQLdb\n\nParams = dict()\nParams['G'] = {u'units': u'mph', u'name': u'G', u'$': u'Wind Gust'}\nParams['T'] = {u'units': u'C', u'name': u'T', u'$': u'Temperature'}\nParams['V'] = {u'units': u'm', u'name': u'V', u'$': u'Visibility'}\nParams['D'] = {u'units': u'compass', u'name': u'D', u'$': u'Wind Direction'}\nParams['S'] = {u'units': u'mph', u'name': u'S', u'$': u'Wind Speed'}\nParams['W'] = {u'units': u'', u'name': u'W', u'$': u'Weather Type'}\nParams['P'] = {u'units': u'hpa', u'name': u'P', u'$': u'Pressure'}\nParams['Pt'] = {u'units': u'Pa/s', u'name': u'Pt', u'$': u'Pressure Tendency'}\nParams['Dp'] = {u'units': u'C', u'name': u'Dp', u'$': u'Dew Point'}\nParams['H'] = {u'units': u'%', u'name': u'H', u'$': u'Screen Relative Humidity'}\nParams['$'] = {u'units': u'minutes', u'name': u'$', u'$': u'Minute Of Day'}\n\nAPIKey = tools.getSecret('MetOffice')\n\n\n\ndef dataURL(APIKey, feed='capabilities'):\n #if feed == 'capabilities':\n URL = ('http://datapoint.metoffice.gov.uk/'\n 'public/data/val/wxobs/all/json/'\n '{}?res=hourly&key={}').format(feed, APIKey)\n return URL\n\ndef unpackURL(URL):\n response = urllib.urlopen(URL)\n content = response.read().decode('utf8')\n data = json.loads(content)\n return data\n\ndef getTimeSteps(APIKey):\n URL = dataURL(APIKey, feed='capabilities')\n data = unpackURL(URL)\n TSStrs = data['Resource']['TimeSteps']['TS']\n TSs = []\n for TSStr in TSStrs:\n TS = datetime.strptime(TSStr, '%Y-%m-%dT%H:%M:%SZ')\n TS = pytz.utc.localize(TS)\n TSs.append(TS)\n return TSs\n\ndef getSiteNames(APIKey):\n URL = dataURL(APIKey, feed='sitelist')\n data = unpackURL(URL)\n Locations = data['Locations']['Location']\n Locations = pd.DataFrame(Locations)\n return Locations\n\ndef getSiteID(APIKey, name, Locations='NotSet'):\n if isinstance(Locations, str):\n if Locations == 'NotSet':\n Locations = getSiteNames(APIKey)\n locationNames = list(Locations.name)\n if name in locationNames:\n ID = int(Locations[Locations.name == name].id)\n return ID\n else:\n print('No exact match for \"{}\". The 10 closest matches are:'.format(name))\n matches = process.extract(name, Locations.name, limit=10)\n for match in matches:\n print(match)\n return 0\n\ndef downloadMet(APIKey, LocationID, timeSteps=[]):\n if isinstance(LocationID, str):\n LocationID = getSiteID(APIKey, 'Edinburgh/Gogarbank', Locations=Locations)\n if len(timeSteps) == 0:\n timeSteps = getTimeSteps(APIKey)\n URL = dataURL(APIKey, feed=LocationID)\n response = urllib.urlopen(URL)\n content = response.read().decode('utf8')\n data = json.loads(content)\n data = data['SiteRep']['DV']# DV for the data, Wx for meta data.\n data = data['Location']['Period']\n hourdata = data[0]['Rep']\n for l in data:\n hourdata.extend(l['Rep'])\n data = pd.DataFrame(hourdata)\n data = data.drop_duplicates(subset='$', keep='last')\n colNames = list(data)\n renames = {}\n for colName in colNames:\n renames[colName] = Params[colName]['$'].replace(' ', '')\n data = data.rename(columns=renames)\n # Add the location ID to the dataframe.\n data['LocationID'] = LocationID\n # Add the datetimes to the dataframe.\n data['DateTime'] = timeSteps\n # Check that the MinuteOfDay agrees with the datetime\n minutes1 = list(data['DateTime'].dt.hour*60)\n minutes2 = [int(x) for x in list(data['MinuteOfDay'])]\n if minutes1 != minutes2:\n raise ValueError('Datetimes do not agree with MinuteOfDays')\n data = data.drop('MinuteOfDay', 1)\n return data\n\n# Get the site details.\nLocations = getSiteNames(APIKey)\n\nif __name__ == '__main__':\n\n # Get the met data.\n data = downloadMet(APIKey, 'Edinburgh/Gogarbank')\n\n\n print(data)","sub_path":"ConnectMet.py","file_name":"ConnectMet.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"597395631","text":"from kivy.uix.screenmanager import Screen, ScreenManager\nfrom kivymd.app import MDApp\nfrom kivy.uix.screenmanager import FadeTransition\nfrom kivy.core.window import Window\nfrom kivy.clock import Clock\nfrom kivymd.uix.dialog import MDDialog\nfrom kivy.properties import StringProperty\nfrom kivymd.uix.button import MDFlatButton\nimport os\nimport threading\nfrom spotdl.command_line.core import Spotdl\nfrom threading import Thread\nfrom kivymd.uix.filemanager import MDFileManager\nfrom kivymd.toast import toast\n\n\nFolderName = \"\"\n\n\nclass DownloadingScreen(Screen):\n pass\nclass WelcomeScreen(Screen):\n def on_enter(self):\n Clock.schedule_once(self.change_screen,5)\n def change_screen(self, dt):\n self.manager.transition = FadeTransition(duration=1.2)\n self.manager.current = \"Downloader\"\n\nclass DownloaderScreen(Screen):\n text = StringProperty(\"\")\n text2 = StringProperty(\"\")\n text3 = StringProperty(\"\")\n text4 = StringProperty(\"\")\n text5 = StringProperty(\"Choose your video/song's format type\")\n hint_text = \"File Path\"\n error = False\n downloadChoices = \"\"\n menu = \"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n Window.bind(on_keyboard=self.events)\n self.manager_open = False\n self.file_manager = MDFileManager(\n exit_manager=self.exit_manager,\n select_path=self.select_path,\n \n )\n\n \n\n def file_manager_open(self):\n self.file_manager.show('/') # output manager to the screen\n self.manager_open = True\n\n def select_path(self, path):\n '''It will be called when you click on the file name\n or the catalog selection button.\n\n :type path: str;\n :param path: path to the selected directory or file;\n '''\n\n self.exit_manager()\n self.ids.FilePathTextField.text = os.path.abspath(path)\n\n def exit_manager(self, *args):\n '''Called when the user reaches the root of the directory tree.'''\n\n self.manager_open = False\n self.file_manager.close()\n\n def events(self, instance, keyboard, keycode, text, modifiers):\n '''Called when buttons are pressed on the mobile device.'''\n\n if keyboard in (1001, 27):\n if self.manager_open:\n self.file_manager.back()\n return True\n \n def button_press(self):\n self.manager.transition = FadeTransition(duration=1.2)\n self.manager.current = \"downloading\" \n t = Thread(target=self.download)\n t.daemon = True\n t.start()\n \n \n def download(self):\n self.song_name = self.ids.SongName.text\n\n args = {\n \"no_encode\": False,\n }\n spotdl_handler = Spotdl(args)\n spotdl_handler.download_track(self.song_name)\n self.manager.transition = FadeTransition(duration=1.2)\n self.manager.current = \"Downloader\" \n toast(\"Download complete\")\n def change_file_path(self):\n self.file_path = self.ids.FilePathTextField.text\n os.chdir(self.file_path)\n\n \nclass MusicApp(MDApp): \n def build(self):\n self.theme_cls.theme_style = \"Dark\"\n self.theme_cls.accent_palette = \"Red\"\n self.theme_cls.primary_palette = \"Green\" \n def help_dialog_box_for_downloader(self):\n dialog_box_string = \"1. Click on the Choose Your Location Button. A file system screen should pop-up\\n\\n\" \\\n \"2. Choose the directory your video/song should be downloaded into\\n\\n\" \\\n \"3. Enter the name your song or a youtube or spotify link\\n\\n\" \\\n \"4. Click on the download button and Voila your video/song has been downloaded !\\n\\n\" \\\n \"WARNINGS:\\n\\n\" \\\n \"1. Please do not enter an invalid youtube link or url....\\n\\n\" \\\n \"2. Please choose a name for your video or song that does not already exist in your \" \\\n \"folder.\\n\\n\" \\\n\n close_button = MDFlatButton(text=\"Close\", text_color=self.theme_cls.primary_color, on_release=self.close_dialog)\n self.dialog = MDDialog(title=\"INSTRUCTIONS:\", text=dialog_box_string,\n size_hint=(0.7, 1), buttons=[close_button])\n self.dialog.open()\n\n def close_dialog(self, obj):\n self.dialog.dismiss()\nclass Manager(ScreenManager):\n pass\n\nif __name__ == '__main__':\n MusicApp().run() \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52196566","text":"from keras.models import Model\nfrom keras.layers import Input, PReLU, Dense, LSTM, multiply, concatenate, Activation\nfrom keras.layers import Conv1D, BatchNormalization, GlobalAveragePooling1D, Permute, Dropout, MaxPooling1D\n\nfrom utils.constants import MAX_SEQUENCE_LENGTH_LIST, NB_CLASSES_LIST\nfrom utils.keras_utils import train_model, evaluate_model, set_trainable, visualize_context_vector, visualize_cam\nfrom utils.layer_utils import AttentionLSTM\nfrom keras.utils.vis_utils import plot_model\nimport scipy.io\n\nDATASET_INDEX = 85\nMAX_SEQUENCE_LENGTH = MAX_SEQUENCE_LENGTH_LIST[DATASET_INDEX]\nNB_CLASS = NB_CLASSES_LIST[DATASET_INDEX]\n\nTRAINABLE = True\n\n\ndef generate_model():\n ip = Input(shape=(1, MAX_SEQUENCE_LENGTH))\n\n x = LSTM(128)(ip)\n x = Dropout(0.8)(x)\n\n y = Permute((2, 1))(ip)\n y = Conv1D(128, 8, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = Conv1D(256, 5, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = Conv1D(128, 3, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = GlobalAveragePooling1D()(y)\n\n x = concatenate([x, y])\n\n out = Dense(NB_CLASS, activation='softmax')(x)\n\n model = Model(ip, out)\n\n model.summary()\n\n #model.load_weights(\"weights/beef_weights - 8667 v3 lstm 8 batch 128 no attention dropout 80.h5\")\n\n return model\n\n\ndef generate_model_2():\n ip = Input(shape=(1, MAX_SEQUENCE_LENGTH))\n\n x = AttentionLSTM(128)(ip)\n x = Dropout(0.8)(x)\n\n y = Permute((2, 1))(ip)\n y = Conv1D(128, 8, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = Conv1D(256, 5, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = Conv1D(128, 3, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = GlobalAveragePooling1D()(y)\n\n x = concatenate([x, y])\n\n out = Dense(NB_CLASS, activation='softmax')(x)\n\n model = Model(ip, out)\n\n model.summary()\n\n # add load model code here to fine-tune\n\n return model\n\ndef generate_model_3():\n ip = Input(shape=(1, MAX_SEQUENCE_LENGTH))\n\n # x = LSTM(64, return_sequences=True)(ip)\n # x = LSTM(64, return_sequences=True)(x)\n x = LSTM(100)(ip)\n x = Dropout(0.8)(x) \n\n out = Dense(NB_CLASS, activation='softmax')(x)\n \n model = Model(ip, out)\n\n model.summary()\n\n # add load model code here to fine-tune\n\n return model\n\ndef generate_model_4():\n ip = Input(shape=(1, MAX_SEQUENCE_LENGTH))\n\n y = Permute((2, 1))(ip)\n y = Conv1D(128, 8, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = Conv1D(256, 5, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = Conv1D(128, 3, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Activation('relu')(y)\n\n y = GlobalAveragePooling1D()(y)\n\n out = Dense(NB_CLASS, activation='softmax')(y)\n\n model = Model(ip, out)\n\n model.summary()\n\n return model\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n result = {};\n for i in range(0,5):\n model = generate_model()\n # plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)\n current_data_idx = DATASET_INDEX + (i*2);\n weight_name = \"fmri_lstmfcn_{}_bias_zscore_b64\".format(i+1);\n\n print(\"Training:\");\n train_model(model, current_data_idx, dataset_prefix=weight_name, epochs=2000, batch_size=64,normalize_timeseries=False)\n\n print(\"Testing:\");\n cm = evaluate_model(model, current_data_idx + 1, dataset_prefix=weight_name, batch_size=64, normalize_timeseries=False)\n result[i+1] = cm;\n \n scipy.io.savemat('resultlstmfcn.mat', mdict={'cm1': result[1],'cm2':result[2],'cm3':result[3],'cm4':result[4],'cm5':result[5]});\n\n # visualize_context_vector(model, DATASET_INDEX, dataset_prefix='beef', visualize_sequence=True,\n # visualize_classwise=True, limit=1)\n\n # visualize_cam(model, DATASET_INDEX, dataset_prefix='beef', class_id=0)\n","sub_path":"fmri_model.py","file_name":"fmri_model.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"389767180","text":"import datetime\nfrom bson.json_util import dumps, RELAXED_JSON_OPTIONS\nfrom bson.objectid import ObjectId\nfrom json import loads\n\nfrom visualizer_data import pipelines\n\n\ndef sanitize_facet_result(result):\n result = result[0]\n for key, value in result.items():\n if len(value) == 0:\n result[key] = 0\n else:\n result[key] = value[0]['count']\n return result\n\n\ndef sanitize_from_datetime_input(datetime_str):\n if not datetime_str:\n return datetime.datetime(1970, 1, 1)\n else:\n return datetime.datetime.fromisoformat(datetime_str)\n\n\ndef sanitize_to_datetime_input(datetime_str):\n if not datetime_str:\n return datetime.datetime.utcnow()\n else:\n return datetime.datetime.fromisoformat(datetime_str)\n\n\ndef get_stats(user_id, ex_type, from_datetime=None, to_datetime=None):\n from config import mongo\n\n from_datetime = sanitize_from_datetime_input(from_datetime)\n to_datetime = sanitize_to_datetime_input(to_datetime)\n\n pipeline = pipelines.gen_pipeline(ex_type,\n ObjectId(user_id),\n from_datetime,\n to_datetime)\n if pipeline is None:\n return 'exercise type not found', 404\n\n result = mongo.db.ex_attempt.aggregate(pipeline)\n if not result:\n return 'exercise id not found', 404\n\n json_result = loads(dumps(result, json_options=RELAXED_JSON_OPTIONS))\n\n return sanitize_facet_result(json_result)\n","sub_path":"api/visualizer_data.py","file_name":"visualizer_data.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"630312897","text":"from tests.integration import basetest\n\n\nclass TestCaseTelegrafDatadog(basetest.BaseTest):\n def test_telegraf_datadog_running(self):\n self.stage_container(\n \"BuildpackTestApp-mx-7-16.mda\",\n env_vars={\n \"APPMETRICS_TARGET\": '{\"url\": \"https://foo.bar/write\"}',\n \"DD_API_KEY\": \"NON-VALID-TEST-KEY\",\n },\n )\n self.start_container()\n self.assert_app_running()\n\n # Validate telegraf is running and has port 8125 opened for StatsD\n tg_output = self.run_on_container(\"lsof -i | grep '^telegraf.*:8125'\",)\n assert tg_output is not None\n assert str(tg_output).find(\"telegraf\") >= 0\n\n dd_output = self.run_on_container(\n \"ps x | grep '\\\\.local/datadog/datadog-agent'\",\n )\n assert dd_output is not None\n","sub_path":"tests/integration/test_telegraf_datadog.py","file_name":"test_telegraf_datadog.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"471644712","text":"def main():\n argument_spec = ec2_argument_spec()\n argument_spec.update(dict(access_logs_enabled=dict(type='bool'), access_logs_s3_bucket=dict(type='str'), access_logs_s3_prefix=dict(type='str'), deletion_protection=dict(default=False, type='bool'), idle_timeout=dict(type='int'), listeners=dict(type='list'), name=dict(required=True, type='str'), purge_listeners=dict(default=True, type='bool'), purge_tags=dict(default=True, type='bool'), subnets=dict(type='list'), security_groups=dict(type='list'), scheme=dict(default='internet-facing', choices=['internet-facing', 'internal']), state=dict(choices=['present', 'absent'], type='str'), tags=dict(default={\n \n }, type='dict'), wait_timeout=dict(type='int'), wait=dict(type='bool')))\n module = AnsibleModule(argument_spec=argument_spec, required_if=[('state', 'present', ['subnets', 'security_groups'])], required_together=['access_logs_enabled', 'access_logs_s3_bucket', 'access_logs_s3_prefix'])\n listeners = module.params.get('listeners')\n if (listeners is not None):\n for listener in listeners:\n for key in listener.keys():\n if (key not in ['Protocol', 'Port', 'SslPolicy', 'Certificates', 'DefaultActions', 'Rules']):\n module.fail_json(msg=\"listeners parameter contains invalid dict keys. Should be one of 'Protocol', 'Port', 'SslPolicy', 'Certificates', 'DefaultActions', 'Rules'.\")\n if (not HAS_BOTO3):\n module.fail_json(msg='boto3 required for this module')\n (region, ec2_url, aws_connect_params) = get_aws_connection_info(module, boto3=True)\n if region:\n connection = boto3_conn(module, conn_type='client', resource='elbv2', region=region, endpoint=ec2_url, **aws_connect_params)\n connection_ec2 = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params)\n else:\n module.fail_json(msg='region must be specified')\n state = module.params.get('state')\n if (state == 'present'):\n create_or_update_elb(connection, connection_ec2, module)\n else:\n delete_elb(connection, module)","sub_path":"Data Set/bug-fixing-5/d0d2beafbac744c0ddc7e9527ffed0d532301747-
-fix.py","file_name":"d0d2beafbac744c0ddc7e9527ffed0d532301747-
-fix.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264568091","text":"\"\"\"\n 抓取腾讯招聘\n\"\"\"\nimport requests\nfrom fake_useragent import UserAgent\nfrom lxml import etree\nimport json\nimport time\nimport random\nclass Tencent:\n def __init__(self):\n self.url = 'https://careers.tencent.com/search.html?index={}'\n\n def get_html(self,url):\n headers ={'User-Agent':UserAgent().random}\n html = requests.get(url=url,headers=headers).text\n return html\n def parese_html(self,html):\n pass\n def run(self):\n for i in range(1,2):\n url =self.url.format(i)\n html = self.get_html(url)\n print(html)\n with open('f.html','a')as f:\n f.write(html)\n time.sleep(random.uniform(1,2))\nif __name__ == '__main__':\n spider = Tencent()\n spider.run()\n\n\n\n","sub_path":"Spider/day05/10_Tencent.py","file_name":"10_Tencent.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"547256871","text":"##############\n# Exercise 2.6\n##############\n\nclass AADist:\n \"\"\"\n The class provides a method to read fasta files and to calculate certain statistics on the read sequences.\n \"\"\"\n \n def __init__(self, filepath):\n self.__sequences = []\n self.read_fasta(filepath)\n self.aa = {\n 'A': 0,\n 'R': 0,\n 'N': 0,\n 'D': 0,\n 'C': 0,\n 'E': 0,\n 'Q': 0,\n 'G': 0,\n 'H': 0,\n 'I': 0,\n 'L': 0,\n 'K': 0,\n 'M': 0,\n 'F': 0,\n 'P': 0,\n 'S': 0,\n 'T': 0,\n 'W': 0,\n 'Y': 0,\n 'V': 0,\n }\n \n\n def get_counts(self):\n return len(self.__sequences)\n\n\n def get_average_length(self):\n n = self.get_counts()\n l = [len(s) for s in self.__sequences]\n s = sum(l)\n print(n)\n print(l)\n print(s)\n return s/n\n\n\n def read_fasta(self, path):\n with open(path,\"r\") as f:\n seqs = []\n seq =\"\"\n sequence_started = False\n for line in f:\n if line.startswith(\">\") or line.startswith(\";\"):\n if sequence_started:\n seqs.append(seq)\n sequence_started = False\n seq = \"\"\n else:\n sequence_started = True\n line = line.strip()\n if line.endswith(\"*\"):\n seq = seq+line[:-1]\n else:seq = seq+line\n seqs.append(seq)\n self.__sequences = seqs\n return seqs\n\n\n\n def get_abs_frequencies(self):\n # return number of occurences not normalized by length\n aas = self.aa.keys()\n for a in aas:\n f = 0\n for s in self.__sequences:\n index = [1 for c in s if c ==a]\n f = f + sum(index)\n self.aa[a] = f\n return self.aa\n\n\n\n\n\n\n def get_av_frequencies(self):\n # return number of occurences normalized by length\n avg_f = self.aa\n aas = avg_f.keys()\n total_length = self.get_average_length()*self.get_counts()\n for a in aas:\n avg_f[a] = avg_f[a]/total_length\n return avg_f\n\n\n","sub_path":"codechecker/repos/1/collected_files/aa_dist/ge56sen.py","file_name":"ge56sen.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"277703333","text":"\"\"\"\nTODO\n- nikkud version\n- generalize parts of code that assume english\n\nHow to update\n- To update sperling NEs\n - edit sperling_en_and_he.csv\n - run find_missing_rabbis.convert_final_en_names_to_ner_tagger_input()\n\n\ninputs\n --taggingParamsFile:\n filepath to JSON of the form\n {\n \"namedEntities\": [\n {\n \"id\": ,\n \"idIsSlug\": ,\n \"manualTitles\": [\n {\n \"lang\": [\"he\", \"en\"],\n \"text\": \n }\n ],\n \"tag\": (arbitrary tag to associate with this entity),\n \"getLeaves\": (if True, include all leaves of this topic),\n }\n ],\n \"corpus\": [\n {\n \"title\": ,\n \"type\": [\"category\", \"index\"],\n \"versions\": [\n {\n \"language\": [\"en\", \"he\"],\n \"versionTitle\": <VTITLE>,\n \"pretaggedFile\": <FILEPATH> (OPTIONAL)\n }\n ]\n }\n ]\n }\n pretaggedFile is of form\n [\n {\n \"start\": <START INDEX>,\n \"end\": <END INDEX>,\n \"mention\": <MENTION STRING>,\n \"id_matches\": [<ID>,],\n \"ref\": <REF>,\n \"vtitle\": <VTITLE>,\n \"lang\": <LANG>\n }\n ]\n --outputFile\n file name to save results to\n\noutput\n file of the form\n [\n {\n \"start\": <START INDEX>,\n \"end\": <END INDEX>,\n \"mention\": <MENTION STRING>,\n \"id_matches\": [<ID>,],\n \"ref\": <REF>,\n \"vtitle\": <VTITLE>,\n \"lang\": <LANG>\n }\n ]\n\"\"\"\nimport django, json, srsly, csv\ndjango.setup()\nimport re2 as re\nimport regex\nfrom tqdm import tqdm\nfrom sefaria.model import *\nfrom collections import defaultdict\n\nclass TextNormalizer:\n b_replacements = [' ben ', ' bar ', ', son of ', ', the son of ']\n b_token = ' b. '\n starting_replacements = ['Ben ', 'Bar ', 'The ']\n unidecode_table = {\n \"ḥ\": \"h\",\n \"Ḥ\": \"H\",\n \"ă\": \"a\",\n \"ǎ\": \"a\",\n \"ġ\": \"g\",\n \"ḫ\": \"h\",\n \"ḳ\": \"k\",\n \"Ḳ\": \"K\",\n \"ŏ\": \"o\",\n \"ṭ\": \"t\",\n \"ż\": \"z\",\n \"Ż\": \"Z\" ,\n \"’\": \"'\",\n '\\u05f3': \"'\",\n \"\\u05f4\": '\"',\n \"”\": '\"',\n \"“\": '\"'\n }\n normalizing_reg = r\"\\s*<[^>]+>\\s*\"\n normalizing_rep = \" \"\n\n @classmethod\n def get_rabbi_regex(cls, rabbi):\n reg = rabbi.replace(cls.b_token, f\"(?:{u'|'.join(re.escape(b) for b in cls.b_replacements)})\")\n for starter in cls.starting_replacements:\n starter = re.escape(starter)\n reg = re.sub(f'^{starter}', f\"(?:{starter.lower()}|{starter})\", reg)\n return reg\n\n @classmethod\n def get_rabbi_expansions(cls, rabbi):\n expansions = [rabbi]\n for starter in cls.starting_replacements:\n if rabbi.startswith(starter):\n expansions += [rabbi[0].lower() + rabbi[1:]]\n for expansion in expansions:\n if cls.b_token in expansion:\n for b_replacement in cls.b_replacements:\n expansions += [expansion.replace(cls.b_token, b_replacement)]\n return expansions\n\n @classmethod\n def myunidecode(cls, text):\n for k, v in cls.unidecode_table.items():\n text = text.replace(k, v)\n return text\n\n @classmethod\n def normalize_text(cls, lang, s):\n # text = re.sub('<[^>]+>', ' ', text)\n if lang == 'en':\n s = cls.myunidecode(s)\n s = re.sub(cls.normalizing_reg, cls.normalizing_rep, s)\n # text = unidecode(text)\n # text = re.sub('\\([^)]+\\)', ' ', text)\n # text = re.sub('\\[[^\\]]+\\]', ' ', text)\n # text = ' '.join(text.split())\n return s\n\n @classmethod\n def find_text_to_remove(cls, s):\n return [(m, cls.normalizing_rep) for m in re.finditer(cls.normalizing_reg, s)]\n\nclass Mention:\n\n def __init__(self, start=None, end=None, mention=None, id_matches=None, ref=None, versionTitle=None, language=None):\n self.start = start\n self.end = end\n self.mention = mention\n self.id_matches = id_matches\n self.ref = ref\n self.versionTitle = versionTitle\n self.language = language\n\n\n def add_metadata(self, **kwargs):\n for key, value in kwargs.items():\n setattr(self, key, value)\n return self\n\n def serialize(self):\n return {\n \"start\": self.start,\n \"end\": self.end,\n \"mention\": self.mention,\n \"id_matches\": self.id_matches,\n \"ref\": self.ref,\n \"versionTitle\": self.versionTitle,\n \"language\": self.language\n }\n\n def __eq__(self, other):\n return self.__hash__() == other.__hash__()\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n id_hash = \"|\".join(sorted(self.id_matches))\n return hash(f\"{self.start}|{self.end}|{self.mention}|{self.ref}|{self.versionTitle}|{self.language}|{id_hash}\")\n\nclass AbstractNamedEntityRecognizer:\n \"\"\"\n Generic NER classifier\n Subclasses implement specific ner strategies\n \"\"\"\n def __init__(self, named_entities, **kwargs):\n raise Exception(\"AbstractNamedEntityRecognizer should not be instantiated. Instantiate a subclass.\")\n\n def fit(self):\n pass\n\n def predict(self, text):\n \"\"\"\n Tags `text` with named entities\n Returns list of `Mentions`\n \"\"\"\n pass\n\nclass NaiveNamedEntityRecognizer(AbstractNamedEntityRecognizer):\n\n def __init__(self, named_entities, **kwargs):\n self.named_entities = named_entities\n self.named_entity_regex = None\n\n def fit(self):\n title_regs = []\n for ne in tqdm(self.named_entities, desc=\"fit ner\"):\n for title in ne.get_titles(lang=\"en\", with_disambiguation=False):\n title_regs += [re.escape(expansion) for expansion in TextNormalizer.get_rabbi_expansions(title)]\n title_regs.sort(key=lambda x: len(x), reverse=True)\n word_breakers = r\"|\".join(re.escape(breaker) for breaker in ['.', ',', '\"', '?', '!', '(', ')', '[', ']', '{', '}', ':', ';', '§', '<', '>', \"'s\"])\n\n self.named_entity_regex = re.compile(fr\"(?:^|\\s|{word_breakers})({'|'.join(title_regs)})(?:\\s|{word_breakers}|$)\")\n\n @staticmethod\n def filter_already_found_mentions(mentions, text, lang):\n text = text.replace('\\xa0', ' ') # strange character\n unique_titles = set(library.get_titles_in_string(text, lang, True))\n all_reg = library.get_multi_title_regex_string(unique_titles, lang)\n reg = regex.compile(all_reg, regex.VERBOSE)\n\n link_indexes = set()\n for match in reg.finditer(text):\n link_indexes |= {i for i in range(match.start(), match.end())}\n return list(filter(lambda m: len(link_indexes & set(range(m.start, m.end))) == 0, mentions))\n\n def predict_segment(self, corpus_segment):\n from data_utilities.util import get_mapping_after_normalization, convert_normalized_indices_to_unnormalized_indices\n\n norm_text = TextNormalizer.normalize_text(corpus_segment.language, corpus_segment.text)\n mentions = []\n for match in re.finditer(self.named_entity_regex, norm_text):\n mentions += [Mention(match.start(1), match.end(1), match.group(1), ref=corpus_segment.ref, versionTitle=corpus_segment.versionTitle, language=corpus_segment.language)]\n mention_indices = [(mention.start, mention.end) for mention in mentions]\n norm_map = get_mapping_after_normalization(corpus_segment.text, TextNormalizer.find_text_to_remove)\n mention_indices = convert_normalized_indices_to_unnormalized_indices(mention_indices, norm_map)\n for mention, (unnorm_start, unnorm_end) in zip(mentions, mention_indices):\n mention.add_metadata(start=unnorm_start, end=unnorm_end)\n mentions = self.filter_already_found_mentions(mentions, corpus_segment.text, corpus_segment.language)\n return mentions\n\n def predict(self, corpus_segments):\n mentions = []\n for corpus_segment in tqdm(corpus_segments, desc=\"ner predict\"):\n mentions += self.predict_segment(corpus_segment)\n return mentions\n\nclass AbstractEntityLinker:\n \"\"\"\n Generic Entity Linker\n Subclasses implement specific el strategies\n \"\"\"\n def __init__(self, named_entities, **kwargs):\n raise Exception(\"AbstractEntityLinker should not be instantiated. Instantiate a subclass.\")\n\n def fit(self):\n pass\n\n def predict(self, text, mentions):\n \"\"\"\n Links mentions in `text` to named entities\n Returns list of `Mentions` with id_matches\n \"\"\"\n pass\n\nclass NaiveEntityLinker(AbstractEntityLinker):\n\n def __init__(self, named_entities):\n self.named_entities = named_entities\n self.named_entity_table = defaultdict(dict)\n\n def fit(self):\n for ne in tqdm(self.named_entities, desc=\"fit el\"):\n for title in ne.get_titles(lang=\"en\", with_disambiguation=False):\n title_expansions = TextNormalizer.get_rabbi_expansions(title)\n for expansion in title_expansions:\n self.named_entity_table[expansion][ne.slug] = ne\n for key, ne_dict in self.named_entity_table.items():\n self.named_entity_table[key] = sorted(ne_dict.values(), key=lambda x: getattr(x, 'numSources', 0), reverse=True)\n\n def predict(self, corpus_segments, mentions):\n for mention in tqdm(mentions, desc=\"el predict\"):\n ne_list = self.named_entity_table.get(mention.mention, None)\n if ne_list is None:\n print(f\"No named entity matches '{mention.mention}'\")\n continue\n mention.add_metadata(id_matches=[ne.slug for ne in ne_list])\n return mentions\n\nclass CorpusSegment:\n\n def __init__(self, text, language, versionTitle, ref):\n self.text = text\n self.language = language\n self.versionTitle = versionTitle\n self.ref = ref\n\nclass CorpusManager:\n\n def __init__(self, tagging_params_file, mentions_output_file, mentions_html_folder):\n self.mentions_output_file = mentions_output_file\n self.mentions_html_folder = mentions_html_folder\n self.ner = None\n self.el = None\n self.mentions = []\n self.corpus_version_queries = []\n self.corpus_segments = []\n self.read_tagging_params_file(tagging_params_file)\n\n def read_tagging_params_file(self, tagging_params_file):\n with open(tagging_params_file, \"r\") as fin:\n tagging_params = json.load(fin)\n named_entities = self.create_named_entities(tagging_params[\"namedEntities\"])\n self.ner = NaiveNamedEntityRecognizer(named_entities)\n self.el = NaiveEntityLinker(named_entities)\n self.ner.fit()\n self.el.fit()\n self.corpus_version_queries = self.create_corpus_version_queries(tagging_params[\"corpus\"])\n\n def tag_corpus(self):\n for version_query in tqdm(self.corpus_version_queries, desc=\"load corpus\"):\n pretagged_file = version_query.get(\"pretaggedFile\", None)\n if pretagged_file is not None:\n with open(pretagged_file, \"r\") as fin:\n pretagged_mentions = json.load(fin)\n for mention in pretagged_mentions:\n self.mentions += [Mention().add_metadata(versionTitle=version_query['versionTitle'], language=version_query['language'], **mention)]\n else:\n version = Version().load(version_query)\n version.walk_thru_contents(self.recognize_named_entities_in_segment)\n ner_mentions = self.ner.predict(self.corpus_segments)\n self.mentions += self.el.predict(self.corpus_segments, ner_mentions)\n\n def save_mentions(self):\n out = [mention.serialize() for mention in tqdm(self.mentions, desc=\"save mentions\")]\n with open(self.mentions_output_file, \"w\") as fout:\n json.dump(out, fout, ensure_ascii=False, indent=2)\n\n def recognize_named_entities_in_segment(self, segment_text, en_tref, he_tref, version):\n self.corpus_segments += [CorpusSegment(segment_text, version.language, version.versionTitle, en_tref)]\n\n @staticmethod\n def create_named_entities(raw_named_entities):\n named_entities = []\n for ne in raw_named_entities:\n if ne.get(\"idIsSlug\", False):\n topic = Topic.init(ne[\"id\"])\n if ne.get(\"getLeaves\", False):\n named_entities += topic.topics_by_link_type_recursively(only_leaves=True)\n else:\n named_entities += [topic]\n else:\n if ne.get(\"namedEntityFile\", False):\n with open(ne[\"namedEntityFile\"], \"r\") as fin:\n manual_named_entities = json.load(fin)\n else:\n manual_named_entities = [ne]\n for temp_ne in manual_named_entities:\n topic = Topic({\n \"slug\": temp_ne[\"id\"],\n \"titles\": temp_ne[\"manualTitles\"]\n })\n named_entities += [topic]\n return named_entities\n\n @staticmethod\n def create_corpus_version_queries(raw_corpus):\n version_queries = []\n for item in raw_corpus:\n title_list = [item[\"title\"]] if item[\"type\"] == \"index\" else library.get_indexes_in_category(item[\"title\"])\n for title in title_list:\n for temp_version_query in item[\"versions\"]:\n version_query_copy = temp_version_query.copy()\n version_query_copy[\"title\"] = title\n version_queries += [version_query_copy]\n return version_queries\n\n @staticmethod\n def add_html_links(mentions, text):\n linked_text = \"\"\n mentions.sort(key=lambda x: x.start)\n dummy_char = \"$\"\n char_list = list(text)\n rabbi_dict = {}\n for m in mentions:\n if m.id_matches is None:\n continue\n rabbi_dict[m.start] = (text[m.start:m.end], m.id_matches)\n char_list[m.start:m.end] = list(dummy_char*(m.end-m.start))\n dummy_text = \"\".join(char_list)\n\n # assert len(dummy_text) == len(text), f\"DUMMY {dummy_text}\\nREAL {text}\"\n\n def repl(match):\n try:\n mention, slugs = rabbi_dict[match.start()]\n except KeyError:\n print(\"KEYERROR\", match.group())\n return match.group()\n # TODO find better way to determine if slug is in topics collection\n slug = slugs[0]\n other_slugs = slugs[1:]\n link = f\"\"\"<a href=\"https://www.sefaria.org/topics/{slug}\" class=\"{\"missing\" if ':' in slug else \"found\"}\">{mention}</a>\"\"\"\n if len(other_slugs) > 0:\n link += f'''<sup>{\", \".join([f\"\"\"<a href=\"https://www.sefaria.org/topics/{temp_slug}\" class=\"{\"missing\" if ':' in temp_slug else \"found\"}\">[{i+1}]</a>\"\"\" for i, temp_slug in enumerate(other_slugs)])}</sup>'''\n return link\n linked_text = re.sub(r\"\\$+\", repl, dummy_text)\n return linked_text\n\n def generate_html_file(self):\n mentions_by_ref = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n for mention in tqdm(self.mentions, desc=\"html group by ref\"):\n mentions_by_ref[Ref(mention.ref).index.title][mention.ref][f\"{mention.versionTitle}|||{mention.language}\"] += [mention]\n for book, ref_dict in tqdm(mentions_by_ref.items(), desc=\"make html\"):\n refs_in_order = sorted(ref_dict.keys(), key=lambda x: Ref(x).order_id())\n html = \"\"\"\n <html>\n <head>\n <style>\n body {\n width: 700px;\n margin-right: auto;\n margin-bottom: 50px;\n margin-top: 50px;\n margin-left: auto;\n }\n .he {\n direction: rtl;\n }\n .missing {\n color: red;\n }\n .found {\n color: green;\n }\n </style>\n </head>\n <body>\n \"\"\"\n for ref in refs_in_order:\n oref = Ref(ref)\n versions = ref_dict[ref]\n html += f\"\"\"\n <p><a href=\"https://www.sefaria.org/{oref.url()}\">{ref}</a></p>\n \"\"\"\n sorted_versions = sorted(versions.items(), key=lambda x: x[0])\n for version_lang, temp_mentions in sorted_versions:\n vtitle, lang = version_lang.split('|||')\n segment_text = oref.text(lang, vtitle=vtitle).text\n linked_text = self.add_html_links(temp_mentions, segment_text)\n html += f\"\"\"\n <p class=\"{lang}\">{linked_text}</p>\n \"\"\"\n html += \"\"\"\n </body>\n </html>\n \"\"\"\n with open(self.mentions_html_folder + f'/{book}.html', \"w\") as fout:\n fout.write(html)\n\n @staticmethod\n def get_snippet(text, mention, padding=30, delim='~'):\n start = text[mention.start-padding:mention.start] if mention.start - padding >= 0 else text[:mention.start]\n end = text[mention.end:mention.end+padding]\n return f\"{start}{delim}{mention.mention}{delim}{end}\"\n\n def cross_validate_mentions_by_lang(self, output_file, common_mistakes_output_file):\n from functools import reduce\n ps = PassageSet()\n ref_passage_map = {\n r: p.full_ref for p in ps for r in p.ref_list\n }\n common_mistakes = defaultdict(lambda: {\"count\": 0, \"rowIds\": []})\n mentions_by_passage = defaultdict(lambda: defaultdict(set))\n for mention in tqdm(self.mentions, desc=\"group by passage\"):\n passage_ref = ref_passage_map.get(mention.ref, mention.ref)\n mentions_by_passage[passage_ref][(mention.versionTitle,mention.language)].add(mention)\n rows = []\n cached_text = {}\n for passage, version_dict in tqdm(mentions_by_passage.items(), desc=\"cross validate\"):\n unique_ids_by_version = {}\n for version_lang, temp_mentions in version_dict.items():\n temp_unique_ids = {}\n for temp_mention in temp_mentions:\n if temp_mention.id_matches is None:\n continue\n temp_unique_ids['|'.join(sorted(temp_mention.id_matches))] = set(temp_mention.id_matches)\n unique_ids_by_version[version_lang] = {\n \"ids\": temp_unique_ids,\n \"mentions\": temp_mentions\n }\n if len(unique_ids_by_version) == 1:\n continue\n for version_lang, temp_mentions_dict in unique_ids_by_version.items():\n versionTitle, language = version_lang\n temp_unique_ids = temp_mentions_dict[\"ids\"]\n temp_mentions = temp_mentions_dict[\"mentions\"]\n\n other_unique_ids = reduce(lambda a, b: a | b, reduce(lambda a, b: a + b, [list(value[\"ids\"].values()) for key, value in unique_ids_by_version.items() if key != version_lang], []), set())\n for temp_id_key, temp_id_set in temp_unique_ids.items():\n _type = \"matched\" if len(temp_id_set & other_unique_ids) > 0 else \"extra\"\n ambiguous = len(temp_id_set) > 1\n if _type == \"matched\" and not ambiguous:\n continue\n mentions_for_id = {m.mention:m for m in temp_mentions if '|'.join(sorted(set(getattr(m, 'id_matches', [])))) == temp_id_key}\n example_mention = list(mentions_for_id.values())[0]\n example_ref = example_mention.ref\n text_key = f\"{version_lang}|||{example_ref}\"\n try:\n temp_text = cached_text[text_key]\n except KeyError:\n temp_text = Ref(example_ref).text(language, vtitle=versionTitle).text\n cached_text[text_key] = temp_text\n common_key = (\n versionTitle,\n language,\n temp_id_key,\n _type,\n ambiguous\n )\n common_mistakes[common_key]['count'] += 1\n common_mistakes[common_key]['rowIds'] += [len(rows)+1]\n rows += [{\n \"rowId\": len(rows)+1,\n \"versionTitle\": versionTitle,\n \"language\": language,\n \"passage\": passage,\n \"mentions\": \" | \".join(mentions_for_id.keys()),\n \"example snippet\": self.get_snippet(temp_text, example_mention),\n \"id\": temp_id_key,\n \"type\": _type,\n \"ambiguous\": ambiguous\n }]\n if len(unique_ids_by_version) > 2:\n you_not_me = other_unique_ids.difference(temp_unique_ids)\n # missing only adds info when there are more than two versions being compared\n for you in you_not_me:\n rows += [{\n \"versionTitle\": versionTitle,\n \"language\": language,\n \"passage\": passage,\n \"id\": you,\n \"type\": \"missing\"\n }]\n if len(rows) > 0 and rows[-1][\"versionTitle\"] != \"---\":\n rows += [{\n \"versionTitle\": \"---\"\n }]\n common_rows = []\n for (versionTitle, language, id_key, _type, ambiguous), temp_dict in sorted(common_mistakes.items(), key=lambda x: x[1]['count'], reverse=True):\n common_rows += [{\n \"versionTitle\": versionTitle,\n \"language\": language,\n \"id\": id_key,\n \"type\": _type,\n \"ambiguous\": ambiguous,\n \"count\": temp_dict['count'],\n \"rowIds\": \", \".join(str(rowId) for rowId in temp_dict['rowIds'])\n }]\n with open(output_file, \"w\") as fout:\n c = csv.DictWriter(fout, [\"rowId\",\"versionTitle\", \"language\", \"id\", \"type\", \"ambiguous\", \"passage\", \"mentions\", \"example snippet\"])\n c.writeheader()\n c.writerows(rows)\n with open(common_mistakes_output_file, \"w\") as fout:\n c = csv.DictWriter(fout, [\"versionTitle\", \"language\", \"id\", \"type\", \"ambiguous\", \"count\", \"rowIds\"])\n c.writeheader()\n c.writerows(common_rows)\n\n def load_mentions(self):\n with open(self.mentions_output_file, \"r\") as fin:\n print(\"Loading mentions...\")\n mentions = json.load(fin)\n print(\"Done\")\n self.mentions = [Mention().add_metadata(**m) for m in tqdm(mentions, desc=\"load mentions\")]\n\nif __name__ == \"__main__\":\n corpus_manager = CorpusManager(\n \"research/knowledge_graph/named_entity_recognition/ner_tagger_input_tanakh.json\",\n \"/Users/nss/Documents/Sefaria-Docs/ner/ner_output_tanakh.json\",\n \"/Users/nss/Documents/Sefaria-Docs/ner/html\"\n )\n corpus_manager.tag_corpus()\n corpus_manager.save_mentions()\n corpus_manager.generate_html_file()\n\n # corpus_manager.load_mentions()\n corpus_manager.cross_validate_mentions_by_lang(\"/Users/nss/Documents/Sefaria-Docs/ner/cross_validated_by_language.csv\", \"/Users/nss/Documents/Sefaria-Docs/ner/cross_validated_by_language_common_mistakes.csv\")\n\n\n\"\"\"\nx-validation algo\n\nfor each sugya\n en_ids = set(ids in en mentions)\n he_ids = set(ids in he mentions)\n\n\"\"\"\n","sub_path":"research/knowledge_graph/named_entity_recognition/ner_tagger.py","file_name":"ner_tagger.py","file_ext":"py","file_size_in_byte":24715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"600767493","text":"from Scene.Scene import Scene\nfrom Director import Director\nfrom Scene.FpsChooseScene import FpsChooseScene\nfrom PyQt5.QtWidgets import QLabel, QPushButton, QGridLayout\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtCore import Qt\n\n\n#设置场景\nclass SettingScene(Scene):\n def __init__(self, parentWindow):\n super().__init__(parentWindow)\n\n #初始化场景\n def init(self):\n #控件\n infoLabel = QLabel(self)\n infoLabel.setAlignment(Qt.AlignCenter)\n infoLabel.setFont(QFont(\"微软雅黑\", 40))\n infoLabel.setText(self.tr(\"设 置\"))\n\n fpsChooseButton = QPushButton(self)\n fpsChooseButton.setFont(QFont(\"微软雅黑\", 15))\n fpsChooseButton.setText(self.tr(\"帧数选择\"))\n fpsChooseButton.clicked.connect(self.fpsChooseButtonClicked)\n\n returnToStartSceneButton = QPushButton(self)\n returnToStartSceneButton.setFont(QFont(\"微软雅黑\", 15))\n returnToStartSceneButton.setText(self.tr(\"返回开始界面\"))\n returnToStartSceneButton.clicked.connect(\n self.returnToStartSceneButtonClicked)\n\n #布局\n layout = QGridLayout(self)\n layout.addWidget(infoLabel, 0, 0, 10, 15)\n layout.addWidget(fpsChooseButton, 10, 5, 3, 5)\n layout.addWidget(returnToStartSceneButton, 13, 5, 3, 5)\n\n #单击帧数选择按钮\n def fpsChooseButtonClicked(self):\n fpsChooseScene = FpsChooseScene(Director().window)\n Director().nowScene = fpsChooseScene\n fpsChooseScene.init()\n fpsChooseScene.show()\n self.deleteLater()\n\n #单击返回开始场景按钮\n def returnToStartSceneButtonClicked(self):\n from Scene.StartScene import StartScene\n startScene = StartScene(Director().window)\n Director().nowScene = startScene\n startScene.init()\n startScene.show()\n self.deleteLater()\n","sub_path":"Scene/SettingScene.py","file_name":"SettingScene.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"438013053","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n \nclass Solution(object):\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head is None or head.next is None:\n return head\n \n head.next = self.deleteDuplicates(head.next)\n if head.val == head.next.val:\n head.next = head.next.next\n return head\n\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head == None:\n return None\n fast = head\n slow = head\n while fast != None:\n if fast.val != slow.val:\n slow = slow.next\n slow.val = fast.val\n fast = fast.next\n\n slow.next = None\n return head","sub_path":"deleteduplicate_83.py","file_name":"deleteduplicate_83.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"533426672","text":"import logging\nimport sys\nfrom datetime import datetime\n\nimport web_crawlers.dividend.parser as dividend_parser\nimport web_crawlers.dividend.util as dividend_util\nfrom utils import log, urls, scraper, custom_exception\nfrom web_crawlers.dividend.db_ops import insert_dividend\n\n\ndef runner():\n \"\"\"\n\n :return:\n \"\"\"\n try:\n\n start_date = '2018-01-01'\n end_date = datetime.strftime(datetime.now(), '%Y-%m-%d')\n\n url = urls.corporate_url.format(start_date=start_date, end_date=end_date)\n page_content = scraper.get_page_content(url=url, timeout_retry_num=2)\n\n if page_content:\n dividen_tbody = page_content.find_all('tbody')[0]\n\n logging.info(\"Getting Dividends URLS...\")\n dividend_url_dict = dividend_util.get_dividend_urls(urls.dividend_url)\n\n logging.info(\"Getting Dividends ...\")\n dividends = dividend_parser.get_dividends(dividen_tbody, dividend_url_dict)\n\n logging.info(\"Inserting Dividends ...\")\n insert_dividend(dividends)\n\n logging.info(\"Complete\")\n\n except custom_exception.PageNotFoundError as e:\n logging.error(log.get_error_msg(e))\n sys.exit(1)\n except Exception as e:\n logging.error(log.get_error_msg(e))\n sys.exit(1)\n","sub_path":"jamstock/web_crawlers/dividend/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"522887224","text":"T = int(input())\nfor t in range(1, T+1):\n s = input()\n\n front = [s[0]]\n back = []\n\n for index in range(1, len(s)):\n if s[index] >= front[-1]:\n front.append(s[index])\n else:\n back.append(s[index])\n\n print(\"Case #{}: {}\".format(t, ''.join(front[::-1] + back)))","sub_path":"codes/CodeJamCrawler/16_1_1/achr/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"441859719","text":"\"\"\"\n This script checks if the new animes that have been found were not already reported to the\n otaku. If so, then they are removed from the list in the text file \"assets/tempData.txt\".\n The previously reported animes are stored in \"assets/outputData.txt\" and this is the file\n used to check that the list in \"assets/tempData.txt\" contains different titles.\n\"\"\"\n\nimport os\npathToHere = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + \"/assets/\"\n\nfo = open(pathToHere+\"outputData.txt\", \"r\")\nfn = open(pathToHere+\"tempData.txt\", \"r\")\n\noldData = fo.readlines()\nnewData = fn.readlines()\n\noldLinks = []\nnewLinks = []\nretainedLines = []\n\nfor line in oldData:\n temp = line.split()\n oldLinks.append(temp[-1])\n\nfor line in newData:\n temp = line.split()\n newLinks.append(temp[-1])\n\ntrulyNew = [x for x in newLinks if x not in oldLinks]\n\nfor line in newData:\n for link in trulyNew:\n if link in line:\n retainedLines.append(line)\n\nfn = open(pathToHere+\"tempData.txt\", \"w\")\nfn.writelines(retainedLines)\n\nfo.close()\nfn.close()\n","sub_path":"pyscripts/checkIfAlreadyNotified.py","file_name":"checkIfAlreadyNotified.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"559745538","text":"import plotly.express as px\nimport plotly\nimport json\nfrom flask import Flask,request, render_template\nfrom keras_preprocessing.image.utils import img_to_array\nimport numpy as np\nimport pandas\nfrom keras.models import load_model\nfrom PIL import Image\n\n#data = pandas.read_csv('df_webapp.csv', index_col = 0)\ndata = pandas.read_csv(\"lastlast.csv\",index_col=0)\ndata.to_html(header=\"true\", table_id=\"table\", index=False)\ndf = data.style.hide_index()\napp = Flask(__name__)\nmodel = load_model('model.h5')\n\n@app.route('/', methods=[\"GET\" , \"POST\"])\ndef home():\n return render_template(\"Accueil1.html\", tables=[data.head(5).to_html(classes='data')], titles=data.columns.values)\n\n@app.route('/predict',methods=[\"GET\",'POST'])\ndef predict():\n imagefile = request.files['imagefile']\n #image_path = \"/Users/flavienbert/Documents/Nicepage Templates/projet_final_final/images/image_app\" + imagefile.filename\n image_path =\"/Users/flavienbert/Documents/My_jedha_projects/creation_app/Deploiement/images/image_app\" + imagefile.filename\n imagefile.save(image_path)\n\n image = Image.open(image_path)\n size = (224,224)\n box = (100,100,500,400)\n image = image.resize(size)\n image = img_to_array(image)\n image = np.expand_dims(image, 0)\n prediction = model.predict(image).tolist()\n liste_des_classes = [\"108\",\"208\",\"308\",\"2008\",\"Aygo\",\"3008\",\"Berlingo\",\"C_HR\",\"C3\",\"C4\",\"C4 Cactus\",\"C5 Aircross\",\"Captur\",\"Clio\",\"Corolla\",\"Golf\",\"Megane\",\"POLO\",\"RAV 4\",\"T-ROC\",'UP!',\"TIGUAN\",\"TWINGO\",\"YARIS\",\"ZOE\"]\n liste_des_classes.sort()\n pred_finale = liste_des_classes[np.argmax(prediction[0])] \n return render_template('Accueil1.html', pred='Le model de votre voiture est une :{}'.format(pred_finale))\n#return render_template('Accueil1.html')#, pred='Le model de votre voiture est une :{}'.format(prediction))\n\n@app.route('/recherche',methods=['POST','GET'])\ndef recherche():\n df = data.copy\n if request.method == 'POST':\n State = request.form['State'].upper()\n Brand = request.form['Brand']\n Model = request.form['Model']\n Gear = request.form['Gear']\n KrM = int(request.form['KrM'])\n Energie = request.form['Energie']\n Year = int(request.form['Year'])\n Price = int(request.form['Price'])\n mask = (data['Brand'] == Brand) & (data['Model'] == Model) &\\\n (data['Gear'] == Gear) &\\\n (data['KM'] <= KrM) &\\\n (data['Energie'] == Energie) & (data['Year'] >= Year) & \\\n (data['Price'] <= Price) & (data['State'] == State)\n df = data.loc[mask,:]\n price_avg = df['Price'].mean()\n price_std = df['Price'].std()\n max_interval = price_avg+price_std\n min_interval = price_avg-price_std\n df['Price_recommendation'] = df['Price'].apply(lambda x: 'Expensive' if x > max_interval\n else 'Good price' if x < min_interval\n else \"In market\"\n )\n fig = px.scatter_mapbox(df,\n lat=\"latitude\",\n lon=\"longitude\",\n color=\"Price_recommendation\",\n zoom=7.0,\n mapbox_style=\"carto-positron\",\n hover_name='Brand',text='State',\n title='Cars recommendation: Brand selection')\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n print('je lai enregistre')\n return render_template('Accueil1.html',tables=[df.head(5).sort_values(by=['Scoring'],ascending=False).to_html(classes='data')], titles=df.columns.values, graphJSON=graphJSON)\n #else:\n # return render_template('Accueil.html',tables=[df.head(5).to_html(classes='data')], titles=df.columns.values, graphJSON=graphJSON)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"FYJ_app/Deploiement/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642854576","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 22 16:29:54 2018\n\n@author: 王永威\n\"\"\"\n'''\ncv2的使用方法练习\n'''\n\n\nimport cv2\n\n#视频打开\nvideo = cv2.VideoCapture(r'E:\\Python\\test2.mp4')\n\n#视频读取\nsuccess,frame = video.read()\n#视频编码\nvideo_FourCC = int(video.get(cv2.CAP_PROP_FOURCC))\n#获取视频帧数\nvideo_fps = video.get(cv2.CAP_PROP_FPS)\n#获取视频的宽高\nvideo_size = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)),int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n#写入视频,电脑缺少编码器\n#videoWriter = cv2.VideoWriter(r'E:\\Python\\test37.avi',video_FourCC,video_fps,video_size)\n#-1是需要指定编码格式\nvideoWriter = cv2.VideoWriter(r'E:\\Python\\test36.avi',-1,video_fps,video_size)\nwhile success:\n cv2.imshow('test22',frame)#显示视频\n cv2.waitKey(int(video_fps))#暂停\n \n videoWriter.write(frame)\n success,frame=video.read()#继续读取帧\n \n#释放视频\ncv2.destroyAllWindows()\nvideo.release()\nvideoWriter.release()","sub_path":"Learn-cv2.py","file_name":"Learn-cv2.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"639035319","text":"\n# oos=\"E:\\\\ACM\\\\论文zhunbei\\\\dmfsgd.tar\\\\\"\n# sys.path.extend([oos+\"common\",oos+'algs',oos+'data'])\n\nimport sys\nfrom common import *\nfrom dmfsgdalg import *\nimport matplotlib.pyplot as plt\nprint('begin')\nclass params():\n\n def __init__(self, loss=2, minibatch=1, linesearch=1, lr=1e-2, _lambda=1e0, dimension=10, maxIters=50, forceNonNegative=True):\n self.loss = loss # loss only choose 1 or 2\n self.minibatch = minibatch\n self.linesearch = linesearch\n self.lr = lr\n self._lambda = _lambda\n self.dimension = dimension\n self.maxIters = maxIters\n self.forceNonNegative = forceNonNegative\n\n\nX = np.loadtxt('meridian_matrix1.txt', delimiter=' ')\n\nk = 32\nW = generateW(X, k)\nparam=params()\nU, V, err, mae = dmfsgd_rtt(X, W,param)\nXhat = np.dot(U,V.T);\nXhat[np.nonzero(Xhat<0)]= 1;\n\n#evaluation\ndmed = medianAbsoluteError(X,Xhat);\nprint('The median absolute error is %f.\\n'% dmed);\nplt.figure(1)\n# plot_cdf(relativeError(X,Xhat),'-'); xlim([0,2])\nplt.plot([i for i in range(51)],err)\nplt.figure(2)\n\nplt.plot([i for i in range(51)],mae)\nplt.show()","sub_path":"testRegreesionByDMFSGD.py","file_name":"testRegreesionByDMFSGD.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"140837978","text":"import os\n\nclass FileIO:\n @staticmethod\n def readAsString(fName):\n try:\n \"\"\"read info from file, if file exists. return a string\"\"\"\n with open(str(fName)) as f:\n data = f.read()\n f.close()\n return data\n except FileNotFoundError:\n # we want a string either way, but this way we can let the calling class decide business logic\n return \"\"\n\n @staticmethod\n def readAsPosInt(fName):\n try:\n \"\"\"read info from file. If file exists, return a positive int, negative for errors\"\"\"\n with open(str(fName)) as f:\n data = f.read()\n f.close()\n if data.isnumeric():\n return int(data)\n else:\n return 0\n except Exception:\n # if there's no file, or the file has invalid data, return -1 for value\n return -1\n\n @staticmethod\n def mkdir(newDir): # returns an int to indicate status, 1 created, 0 already exists, -1 error\n try:\n os.mkdir(str(newDir))\n return 1\n except FileExistsError:\n return 0\n except Exception:\n return -1\n\n @staticmethod\n def pathJoin(directory,file):\n # wrapper for path join to eliminate importing os elsewhere\n return os.path.join(str(directory),str(file))\n\n @staticmethod\n def overwrite(fName, data):\n with open(fName, 'w') as f:\n f.write(str(data))\n\n @staticmethod # not needed in this project, but good to have if we use this class elsewhere\n def append(fName, data):\n with open (str(fName)) as current:\n data = current.read() + data\n current.close()\n with open(str(fName),'w') as f:\n f.write(data)\n f.close()\n","sub_path":"fileIO.py","file_name":"fileIO.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"393779314","text":"from __future__ import division\n\n'''\nNeuroLearn Design Matrix\n========================\n\nClass for working with design matrices.\n\n'''\n\n__author__ = [\"Eshin Jolly\"]\n__license__ = \"MIT\"\n\nfrom pandas import DataFrame, Series\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy.stats import pearsonr\nimport six\nfrom ..external.hrf import glover_hrf\nfrom nltools.stats import (downsample,\n upsample,\n zscore,\n make_cosine_basis\n )\n\nclass Design_Matrix_Series(Series):\n\n \"\"\"\n This is a sub-class of pandas series. While not having additional methods\n of it's own required to retain normal slicing functionality for the\n Design_Matrix class, i.e. how slicing is typically handled in pandas.\n All methods should be called on Design_Matrix below.\n \"\"\"\n\n @property\n def _constructor(self):\n return Design_Matrix_Series\n\n @property\n def _constructor_expanddim(self):\n return Design_Matrix\n\n\nclass Design_Matrix(DataFrame):\n\n \"\"\"Design_Matrix is a class to represent design matrices with convenience\n functionality for convolution, upsampling and downsampling. It plays\n nicely with Brain_Data and can be used to build an experimental design\n to pass to Brain_Data's X attribute. It is essentially an enhanced\n pandas df, with extra attributes and methods. Methods always return a\n new design matrix instance.\n\n Args:\n sampling_rate (float): sampling rate of each row in seconds (e.g. TR in neuroimaging)\n convolved (list, optional): on what columns convolution has been performed; defaults to None\n polys (list, optional): list of polynomial terms in design matrix, e.g. intercept, polynomial trends, basis functions, etc; default None\n\n\n \"\"\"\n\n _metadata = ['sampling_rate', 'convolved', 'polys']\n\n def __init__(self, *args, **kwargs):\n\n sampling_rate = kwargs.pop('sampling_rate',None)\n convolved = kwargs.pop('convolved', [])\n polys = kwargs.pop('polys', [])\n self.sampling_rate = sampling_rate\n self.convolved = convolved\n self.polys = polys\n\n super(Design_Matrix, self).__init__(*args, **kwargs)\n\n @property\n def _constructor(self):\n return Design_Matrix\n\n @property\n def _constructor_sliced(self):\n return Design_Matrix_Series\n\n def _inherit_attributes(self,\n dm_out,\n atts=[\n 'sampling_rate',\n 'convolved',\n 'polys']):\n\n \"\"\"\n This is helper function that simply ensures that attributes are copied over from an the current Design_Matrix to a new Design_Matrix.\n\n Args:\n dm_out (Design_Matrix): the new design matrix to copy attributes to\n atts (list; optional): the list of attributes to copy\n\n Returns:\n dm_out (Design_matrix): new design matrix\n\n \"\"\"\n\n for item in atts:\n setattr(dm_out, item, getattr(self,item))\n return dm_out\n\n def details(self):\n \"\"\"Print class meta data.\n\n \"\"\"\n return '%s.%s(sampling_rate=%s, shape=%s, convolved=%s, polynomials=%s)' % (\n self.__class__.__module__,\n self.__class__.__name__,\n self.sampling_rate,\n self.shape,\n self.convolved,\n self.polys\n )\n\n def append(self, dm, axis=0, keep_separate = True, add_poly = None, add_dct_basis = None, unique_cols = [], include_lower = True,fill_na=0):\n \"\"\"Method for concatenating another design matrix row or column-wise.\n Can \"uniquify\" certain columns when appending row-wise, and by\n default will attempt to do that with all polynomial terms (e.g. intercept, polynomial trends). Can also add new polynomial terms during vertical concatentation (when axis == 0). This will by default create new polynomial terms separately for each design matrix\n\n Args:\n dm (Design_Matrix or list): design_matrix or list of design_matrices to append\n axis (int): 0 for row-wise (vert-cat), 1 for column-wise (horz-cat); default 0\n keep_separate (bool,optional): whether try and uniquify columns;\n defaults to True; only applies\n when axis==0\n add_poly (int,optional): what order polynomial terms to add during append, only applied when axis = 0; default None\n add_dct_basis (int,optional): add discrete cosine bassi function during append, only applied when axis = 0; default None\n only applies when axis==0\n unique_cols (list,optional): what additional columns to try to keep\n separated by uniquifying, only applies when\n axis = 0; defaults to None\n include_lower (bool,optional): whether to also add lower order polynomial terms; only applies when add_poly is not None\n fill_na (str/int/float): if provided will fill NaNs with this value during row-wise appending (when axis = 0) if separate columns are desired; default 0\n\n \"\"\"\n if not isinstance(dm, list):\n to_append = [dm]\n else:\n to_append = dm[:]\n\n # Check all items to be appended are Design Matrices and have the same sampling rate\n if not all([isinstance(elem,self.__class__) for elem in to_append]):\n raise TypeError(\"Each object in list must be a Design_Matrix!\")\n if not all([elem.sampling_rate == self.sampling_rate for elem in to_append]):\n raise ValueError(\"All Design Matrices must have the same sampling rate!\")\n\n if axis == 1:\n if any([not set(self.columns).isdisjoint(elem.columns) for elem in to_append]):\n print(\"Duplicate column names detected. Will be repeated.\")\n if add_poly or unique_cols:\n print(\"add_poly and unique_cols only apply when axis=0...ignoring\")\n return self._horzcat(to_append)\n\n elif axis == 0:\n return self._vertcat(to_append, keep_separate=keep_separate,add_poly=add_poly,add_dct_basis=add_dct_basis,unique_cols=unique_cols,include_lower=include_lower,fill_na=fill_na)\n\n else:\n raise ValueError(\"Axis must be 0 (row) or 1 (column)\")\n\n\n def _horzcat(self, to_append):\n \"\"\"Used by .append(). Append another design matrix, column-wise\n (horz cat). Always returns a new design_matrix.\n\n \"\"\"\n\n if all([elem.shape[0] == self.shape[0] for elem in to_append]):\n out = pd.concat([self] + to_append, axis=1)\n out = self._inherit_attributes(out)\n out.polys = self.polys[:]\n for elem in to_append:\n out.polys += elem.polys\n else:\n raise ValueError(\"All Design Matrices must have the same number of rows!\")\n return out\n\n def _vertcat(self, df, keep_separate, add_poly, add_dct_basis, unique_cols, include_lower,fill_na):\n \"\"\"Used by .append(). Append another design matrix row-wise (vert cat).\n Always returns a new design matrix.\n\n \"\"\"\n\n if unique_cols:\n if not keep_separate:\n raise ValueError(\"unique_cols provided but keep_separate set to False. Set keep_separate to True to separate unique_cols\")\n\n to_append = df[:] # need to make a copy because we're altering df\n\n if keep_separate:\n if not all([set(self.polys) == set(elem.polys) for elem in to_append]):\n raise ValueError(\"Design matrices do not match on their polynomial terms (i.e. intercepts, polynomial trends, basis functions). This makes appending with separation ambigious and is not currently supported. Either make sure all constant terms are the same or make sure no Design Matrix has any constant terms and add them during appending with the 'add_poly' and 'unique_cols' arguments\")\n\n orig = self.copy() # Make a copy of the original cause we might alter it\n\n if add_poly:\n orig = orig.add_poly(add_poly,include_lower)\n for i,d in enumerate(to_append):\n d = d.add_poly(add_poly,include_lower)\n to_append[i] = d\n\n if add_dct_basis:\n orig = orig.add_dct_basis(add_dct_basis)\n for i,d in enumerate(to_append):\n d = d.add_dct_basis(add_dct_basis)\n to_append[i] = d\n\n all_cols = unique_cols + orig.polys\n all_dms = [orig] + to_append\n all_polys = []\n is_data = []\n for i,dm in enumerate(all_dms):\n # Figure out what columns we need to relabel\n cols_to_relabel = [col for col in dm.columns if col in all_cols]\n if cols_to_relabel:\n # Create a dictionary with the new names, e.g. {'intercept': '0_intercept'}\n cols_dict = {}\n # Rename the columns and update the dm\n for c in cols_to_relabel:\n cols_dict[c] = str(i) + '_' + c\n if c not in unique_cols:\n all_polys.append(cols_dict[c])\n dm = dm.rename(columns=cols_dict)\n all_dms[i] = dm\n\n out = pd.concat(all_dms,axis=0,ignore_index=True)\n if fill_na is not None:\n out = out.fillna(fill_na)\n\n out.sampling_rate = self.sampling_rate\n out.convolved = self.convolved\n out.polys = all_polys\n data_cols = [elem for elem in out.columns if elem not in out.polys]\n out = out[data_cols + out.polys]\n else:\n out = pd.concat([self] + to_append,axis=0,ignore_index=True)\n out = self._inherit_attributes(out)\n if add_poly:\n out = out.add_poly(add_poly,include_lower)\n\n return out\n\n def vif(self):\n \"\"\"Compute variance inflation factor amongst columns of design matrix,\n ignoring the intercept. Much faster that statsmodels and more\n reliable too. Uses the same method as Matlab and R (diagonal\n elements of the inverted correlation matrix).\n\n Returns:\n vifs (list): list with length == number of columns - intercept\n\n \"\"\"\n assert self.shape[1] > 1, \"Can't compute vif with only 1 column!\"\n if self.polys:\n out = self.drop(self.polys,axis=1)\n else:\n out = self[self.columns]\n\n try:\n return np.diag(np.linalg.inv(out.corr()), 0)\n except np.linalg.LinAlgError:\n print(\"ERROR: Cannot compute vifs! Design Matrix is singular because it has some perfectly correlated or duplicated columns. Using .clean() method may help.\")\n\n\n def heatmap(self, figsize=(8, 6), **kwargs):\n \"\"\"Visualize Design Matrix spm style. Use .plot() for typical pandas\n plotting functionality. Can pass optional keyword args to seaborn\n heatmap.\n\n \"\"\"\n fig, ax = plt.subplots(1, figsize=figsize)\n ax = sns.heatmap(self, cmap='gray', cbar=False, ax=ax, **kwargs)\n for _, spine in ax.spines.items():\n spine.set_visible(True)\n for i, label in enumerate(ax.get_yticklabels()):\n if i == 0 or i == self.shape[0]-1:\n label.set_visible(True)\n else:\n label.set_visible(False)\n ax.axhline(linewidth=4, color=\"k\")\n ax.axvline(linewidth=4, color=\"k\")\n ax.axhline(y=self.shape[0], color='k', linewidth=4)\n ax.axvline(x=self.shape[1], color='k', linewidth=4)\n plt.yticks(rotation=0)\n\n def convolve(self, conv_func='hrf', columns=None):\n \"\"\"Perform convolution using an arbitrary function.\n\n Args:\n conv_func (ndarray or string): either a 1d numpy array containing output of a function that you want to convolve; a samples by kernel 2d array of several kernels to convolve; or th string 'hrf' which defaults to a glover HRF function at the Design_matrix's sampling_rate\n columns (list): what columns to perform convolution on; defaults\n to all skipping intercept, and columns containing 'poly' or 'cosine'\n\n \"\"\"\n assert self.sampling_rate is not None, \"Design_matrix has no sampling_rate set!\"\n\n if columns is None:\n columns = [col for col in self.columns if 'intercept' not in col and 'poly' not in col and 'cosine' not in col]\n nonConvolved = [col for col in self.columns if col not in columns]\n\n if isinstance(conv_func,six.string_types):\n assert conv_func == 'hrf',\"Did you mean 'hrf'? 'hrf' can generate a kernel for you, otherwise custom kernels should be passed in as 1d or 2d arrays.\"\n\n assert self.sampling_rate is not None, \"Design_matrix sampling rate not set. Can't figure out how to generate HRF!\"\n conv_func = glover_hrf(self.sampling_rate, oversampling=1)\n\n else:\n assert type(conv_func) == np.ndarray, 'Must provide a function for convolution!'\n\n if len(conv_func.shape) > 1:\n assert conv_func.shape[0] > conv_func.shape[1], '2d conv_func must be formatted as, samples X kernels!'\n conv_mats = []\n for i in range(conv_func.shape[1]):\n c = self[columns].apply(lambda x: np.convolve(x, conv_func[:,i])[:self.shape[0]])\n c.columns = [str(col)+'_c'+str(i) for col in c.columns]\n conv_mats.append(c)\n out = pd.concat(conv_mats+ [self[nonConvolved]], axis=1)\n else:\n c = self[columns].apply(lambda x: np.convolve(x, conv_func)[:self.shape[0]])\n c.columns = [str(col)+'_c0' for col in c.columns]\n out = pd.concat([c,self[nonConvolved]], axis=1)\n\n out = self._inherit_attributes(out)\n out.convolved = columns\n return out\n\n def downsample(self, target,**kwargs):\n \"\"\"Downsample columns of design matrix. Relies on\n nltools.stats.downsample, but ensures that returned object is a\n design matrix.\n\n Args:\n target(float): downsampling target, typically in samples not\n seconds\n kwargs: additional inputs to nltools.stats.downsample\n\n \"\"\"\n if target < self.sampling_rate:\n raise ValueError(\"Target must be longer than current sampling rate\")\n\n df = Design_Matrix(downsample(self, sampling_freq=1./self.sampling_rate, target=target,target_type='seconds', **kwargs))\n\n # convert df to a design matrix\n newMat = self._inherit_attributes(df)\n newMat.sampling_rate = target\n return newMat\n\n def upsample(self, target,**kwargs):\n \"\"\"Upsample columns of design matrix. Relies on\n nltools.stats.upsample, but ensures that returned object is a\n design matrix.\n\n Args:\n target(float): downsampling target, typically in samples not\n seconds\n kwargs: additional inputs to nltools.stats.downsample\n\n \"\"\"\n if target > self.sampling_rate:\n raise ValueError(\"Target must be shorter than current sampling rate\")\n\n df = Design_Matrix(upsample(self, sampling_freq=1./self.sampling_rate, target=target, target_type='seconds',**kwargs))\n\n # convert df to a design matrix\n newMat = self._inherit_attributes(df)\n newMat.sampling_rate = target\n return newMat\n\n def zscore(self, columns=[]):\n \"\"\"Z-score specific columns of design matrix. Relies on\n nltools.stats.downsample, but ensures that returned object is a\n design matrix.\n\n Args:\n columns (list): columns to z-score; defaults to all columns\n\n \"\"\"\n colOrder = self.columns\n if not list(columns):\n columns = self.columns\n nonZ = [col for col in self.columns if col not in columns]\n df = zscore(self[columns])\n df = pd.concat([df, self[nonZ]], axis=1)\n df = df[colOrder]\n newMat = self._inherit_attributes(df)\n\n return newMat\n\n def add_poly(self, order=0, include_lower=True):\n \"\"\"Add nth order polynomial terms as columns to design matrix.\n\n Args:\n order (int): what order terms to add; 0 = constant/intercept\n (default), 1 = linear, 2 = quadratic, etc\n include_lower: (bool) whether to add lower order terms if order > 0\n\n \"\"\"\n if order < 0:\n raise ValueError(\"Order must be 0 or greater\")\n\n polyDict = {}\n\n if order == 0 and 'intercept' in self.polys:\n print(\"Design Matrix already has intercept...skipping\")\n return self\n elif 'poly_'+str(order) in self.polys:\n print(\"Design Matrix already has {}th order polynomial...skipping\".format(order))\n return self\n\n if include_lower:\n for i in range(0, order+1):\n if i == 0:\n if 'intercept' in self.polys: print(\"Design Matrix already has intercept...skipping\")\n else:\n polyDict['intercept'] = np.repeat(1, self.shape[0])\n else:\n if 'poly_'+str(i) in self.polys:\n print(\"Design Matrix already has {}th order polynomial...skipping\".format(i))\n else:\n # Unit scale polynomial terms so they don't blow up\n vals = np.arange(self.shape[0])\n vals = (vals - np.mean(vals)) / np.std(vals)\n polyDict['poly_' + str(i)] = vals ** i\n else:\n if order == 0:\n polyDict['intercept'] = np.repeat(1, self.shape[0])\n else:\n polyDict['poly_'+str(order)] = (range(self.shape[0]) - np.mean(range(self.shape[0])))**order\n\n toAdd = Design_Matrix(polyDict,sampling_rate=self.sampling_rate)\n out = self.append(toAdd, axis=1)\n if out.polys:\n new_polys = out.polys + list(polyDict.keys())\n out.polys = new_polys\n else:\n out.polys = list(polyDict.keys())\n return out\n\n def add_dct_basis(self,duration=180):\n \"\"\"Adds cosine basis functions to Design_Matrix columns,\n based on spm-style discrete cosine transform for use in\n high-pass filtering.\n\n Args:\n duration (int): length of filter in seconds\n\n \"\"\"\n assert self.sampling_rate is not None, \"Design_Matrix has no sampling_rate set!\"\n basis_mat = make_cosine_basis(self.shape[0],self.sampling_rate,duration)\n\n basis_frame = Design_Matrix(basis_mat,\n sampling_rate=self.sampling_rate)\n\n basis_frame.columns = ['cosine_'+str(i+1) for i in range(basis_frame.shape[1])]\n\n if self.polys:\n # Only add those we don't already have\n basis_to_add = [b for b in basis_frame.columns if b not in self.polys]\n else:\n basis_to_add = list(basis_frame.columns)\n if not basis_to_add:\n print(\"All basis functions already exist...skipping\")\n return self\n else:\n if len(basis_to_add) != len(basis_frame.columns):\n print(\"Some basis functions already exist...skipping\")\n basis_frame = basis_frame[basis_to_add]\n out = self.append(basis_frame,axis=1)\n new_polys = out.polys + list(basis_frame.columns)\n out.polys = new_polys\n return out\n\n def replace_data(self,data,column_names=None):\n \"\"\"Convenient method to replace all data in Design_Matrix with new data while keeping attributes and polynomial columns untouched.\n\n Args:\n columns_names (list): list of columns names for new data\n\n \"\"\"\n\n if isinstance(data, np.ndarray) or isinstance(data, pd.DataFrame) or isinstance(data, dict):\n if data.shape[0] == self.shape[0]:\n out = Design_Matrix(data,columns=column_names)\n polys = self[self.polys]\n out = pd.concat([out,polys],axis=1)\n out = self._inherit_attributes(out)\n return out\n else:\n raise ValueError(\"New data cannot change the number of rows\")\n else:\n raise TypeError(\"New data must be numpy array, pandas DataFrame or python dictionary type\")\n\n def clean(self,fill_na=0,exclude_polys=False,verbose=True):\n \"\"\"\n Method to fill NaNs in Design Matrix and remove duplicate columns based on data values, NOT names. Columns are dropped if they cause the Design Matrix to become singular i.e. are perfectly correlated. In this case, only the first instance of that column will be retained and all others will be dropped.\n\n Args:\n fill_na (str/int/float): value to fill NaNs with set to None to retain NaNs; default 0\n exclude_polys (bool): whether to skip checking of polynomial terms (i.e. intercept, trends, basis functions); default False\n verbose (bool): print what column names were dropped; default True\n\n \"\"\"\n\n # Temporarily turn off warnings for correlations\n old_settings = np.seterr(all='ignore')\n if fill_na is not None:\n out = self.fillna(fill_na)\n\n if exclude_polys:\n data_cols = [c for c in self.columns if c not in self.polys]\n out = out[data_cols]\n\n keep = []; remove = []\n for i, c in out.iteritems():\n for j, c2 in out.iteritems():\n if i != j:\n r = pearsonr(c,c2)[0]\n if (r > 0.99) and (j not in keep) and (j not in remove):\n keep.append(i)\n remove.append(j)\n if remove:\n out = out.drop(remove, axis=1)\n else:\n print(\"Dropping columns not needed...skipping\")\n if verbose:\n print(\"Dropping columns: \", remove)\n np.seterr(**old_settings)\n return out\n","sub_path":"nltools/data/design_matrix.py","file_name":"design_matrix.py","file_ext":"py","file_size_in_byte":22537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"562389583","text":"import json\nfrom os import environ\nfrom time import time\nfrom traceback import format_tb\nfrom unittest.case import SkipTest\n\nfrom selenium.common.exceptions import WebDriverException\n\nfrom .test_log import print_debug, print_section\n\n\nclass TestAction(object):\n \"\"\"\n Context manager for performing test's actions.\n Any action in test you want to present in interface is needed to be\n included into this context manager:\n\n with TestAction('Open URL in browser'):\n driver.get('http://w3c.org')\n\n In debug mode (environment's variable DEBUG=1) test action writes it's own\n data to stdout in human readable format. On production environment it\n uses print_section function to write data in format understandable by\n tests dispatcher and web interface.\n\n Also you can use nested actions and create actions of custom type to\n treat action's params in different ways:\n\n class ApiRequestAction(TestAction):\n type = 'API_REQUEST'\n\n with TestAction('Open URL in browser'):\n driver.get('http://w3c.org')\n with ApiRequestAction('Perform request to Twitter API'):\n urllib.urlopen('https://userstream.twitter.com/1.1/user.json')\n \"\"\"\n # Serial number of action in test (starts with 1).\n num = None\n # Nested level of action (starts with 0).\n level = None\n # Action's verbose description (for humans %).\n description = None\n # Additional parameters of action (e.g. parameters of API request).\n params = None\n # Action's type. Overrided in TestAction's children classes.\n type = None\n # Unix timestamp of action's start.\n start = None\n # Unix timestamp of action's end.\n end = None\n # Duration of action's execution in seconds.\n duration = None\n # Status of action's execution: OK, ERROR, FAIL, SKIP.\n result = None\n # Text of error for ERROR and FAIL statuses.\n error = None\n # Error's traceback structure for ERROR and FAIL statuses.\n traceback = None\n\n def __init__(self, description, params=None):\n self.description = description\n self.params = params\n # Ugly hack for passing child class'es property \"type\" to __dict__.\n if self.type:\n self.__dict__['type'] = self.type\n\n def __enter__(self):\n from .test_case import env\n env['_actions_counter'] += 1\n self.num = env['_actions_counter']\n self.level = env['_actions_level']\n\n if environ.get('DEBUG'):\n print_debug(self.description, _level='main')\n if self.type:\n print_debug('Action type: %s', self.type, _level='info')\n if self.params:\n print_debug('Action params: ' + json.dumps(\n self.params, indent=2, sort_keys=True, ensure_ascii=False\n ), _level='info')\n\n env['_actions_level'] += 1\n self.start = time()\n\n def __exit__(self, exc_type, exc_value, exc_tb):\n self.end = time()\n self.duration = self.end - self.start\n from .test_case import env\n env['_actions_level'] -= 1\n\n if exc_type:\n if issubclass(exc_type, SkipTest):\n self.result = 'SKIP'\n else:\n if issubclass(exc_type, AssertionError):\n self.result = 'FAIL'\n self.traceback = ''.join(format_tb(exc_tb)[:-1])\n else:\n self.result = 'ERROR'\n self.traceback = ''.join(format_tb(exc_tb))\n if issubclass(exc_type, WebDriverException):\n self.error = '%s: %s' % (exc_type.__name__, exc_value.msg)\n else:\n self.error = '%s: %s' % (\n exc_type.__name__, unicode(exc_value)\n )\n else:\n self.result = 'OK'\n\n # Send action's data to test's log.\n if not environ.get('DEBUG'):\n print_section('TEST_ACTION_S', json.dumps(self.__dict__))\n","sub_path":"er_test_core/test_action.py","file_name":"test_action.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645519060","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport numpy as np\nimport sherpa.astro.ui as sau\nfrom .wstat import wfit\n\nd2r = np.pi / 180.\n\n\ndef print_fit():\n res = sau.get_fit_results()\n print(\"Fit success : \\t\", res.succeeded)\n print(\"Fit results:\")\n print(\"Numpoints :\\t\", res.numpoints)\n print(\"dof :\\t\\t\", res.dof)\n print(\"Final statistic value : \\t\", res.statval)\n print(\"Fitted parameters:\")\n for index, parn in enumerate(res.parnames):\n print(parn, \"\\t\\t{0:.3e}\".format(res.parvals[index]))\n\n\ndef print_conf():\n res = sau.get_conf_results()\n print(\"Confidence limits on fitted parameters:\")\n for index, parn in enumerate(res.parnames):\n print(parn, \"\\t\\t{0:.3e}\".format(res.parvals[index]), \"\\t{0:.3e}\".format(res.parmins[index]),\n \"\\t{0:.3e}\".format(res.parmaxes[index]))\n\n\nclass HESS_spec(object):\n \"\"\"Class to encapsulate HESS specific data for spectral analysis with sherpa.\n \"\"\"\n\n def __init__(self, name, filename=None):\n self.name = name\n if filename is not None:\n sau.load_pha(name, filename)\n self.data = sau.get_data(name)\n self.arf = self.data.get_arf()\n self.rmf = self.data.get_rmf()\n\n # Read keywords from pha header\n try:\n self.threshold = self.data.header['ETH']\n except KeyError:\n print(\"WARNING: no threshold found using 200 GeV\")\n self.threshold = 2e8 # default value 200 GeV\n self.emax = 1e11 # default value 100 TeV\n\n try:\n self.zenith = self.data.header['ZENITH']\n except KeyError:\n print(\"WARNING: no mean zenith angle found using 45 deg\")\n self.zenith = 45.0 # default value 45 deg\n\n try:\n self.offset = self.data.header['OFFSET']\n except KeyError:\n print(\"WARNING: no offset angle found using 1.0 deg\")\n self.offset = 1.0 # default value 1 deg\n\n try:\n self.n_tels = self.data.header['N_TELS']\n except KeyError:\n print(\"WARNING: no number of telescopes found using 0\")\n self.n_tels = 0 # default value\n\n try:\n self.eff = self.data.header['EFFICIEN']\n except KeyError:\n print(\"WARNING: no efficiency found using 1.0\")\n self.eff = 1.00 # default value\n\n try:\n self.tstart = self.data.header['TSTART']\n except KeyError:\n print(\"WARNING: no tstart found using 0\")\n self.tstart = 0. # default value\n\n try:\n self.tstop = self.data.header['TSTOP']\n except KeyError:\n print(\"WARNING: no tstop found using tsart+1800\")\n self.tstop = self.tstart + 1800 # default value\n\n else:\n self.data = sau.get_data(name)\n self.arf = self.data.get_arf()\n self.rmf = self.data.get_rmf()\n\n def set_threshold(self, thres_val):\n self.threshold = thres_val\n\n def set_emax(self, emax):\n self.emax = emax\n\n def notice(self, min_ener, max_ener):\n \"\"\"Notice energy range.\n\n if minimal value required below threshold, use threshold instead\n if maximal value required beyond emax, use emax instead\n \"\"\"\n self.data.notice(max(self.threshold, min_ener), min(self.emax, max_ener))\n\n def set_source(self, model):\n \"\"\"Apply source model to the dataset.\"\"\"\n sau.set_source(self.name, model)\n\n def set_minimalArea(self, areamin):\n \"\"\"Define threshold using minimal area.\n\n Extract true energy value from arf file\n To be implemented\n \"\"\"\n my_arf = sau.get_arf(self.name)\n\n\nclass SpecSource(object):\n \"\"\"Class to load and encapsulate all datasets used for a spectral analysis.\n \"\"\"\n\n def __init__(self, name, filelist=None):\n self.name = name\n\n self.listids = None\n self.noticed_ids = None\n\n if filelist is not None:\n self.loadlist(filelist)\n\n def loadlist(self, listfile):\n \"\"\"Load all datasets in listfile.\n\n expect pha files containing keywords for bkg, arf and rmf files\n store dataid\n \"\"\"\n self.listids = np.empty(len(listfile), dtype=object)\n for index, filename in enumerate(listfile):\n datid = self.name + filename # temporary before I have a better idea\n # self.listids.append(HESS_spec(datid,filename))\n self.listids[index] = HESS_spec(datid, filename)\n self.noticed_ids = np.ones((len(self.listids)), dtype=bool)\n\n # make arrays to deal with run characteristics\n self.offsets = np.array([run.offset for run in self.listids])\n self.zeniths = np.array([run.zenith for run in self.listids])\n self.n_tels = np.array([run.n_tels for run in self.listids])\n self.thresholds = np.array([run.threshold * 1e-9 for run in self.listids]) # in TeV\n self.tstarts = np.array([run.tstart for run in self.listids])\n self.tstops = np.array([run.tstop for run in self.listids])\n self.effs = np.array([run.eff for run in self.listids])\n\n def notice_runs(self, valid=None):\n \"\"\"Select runs to be used for the fit/plot procedures.\n\n input array gives boolean for inclusion or exclusion of run\n \"\"\"\n if valid is None:\n self.noticed_ids = np.ones((len(self.listids)), dtype=bool)\n else:\n self.noticed_ids = self.noticed_ids * valid\n if self.noticed_ids.sum() == 0:\n print(\"Warning: noticed runs list is empty.\")\n\n def get_noticed_list(self):\n return [ids.name for ids in self.listids[self.noticed_ids]]\n\n def notice(self, min_ener, max_ener):\n \"\"\"Notice energy range in TeV. This is applied to all HESS_spec in SpecSource.\"\"\"\n for datid in self.listids:\n datid.notice(min_ener * 1e9, max_ener * 1e9)\n\n def set_source(self, model):\n \"\"\"Set source model.\n\n This is applied to all HESS_spec in SpecSource.\n \"\"\"\n for datid in self.listids:\n datid.set_source(model)\n\n def fit(self, do_covar=False, do_conf=False):\n \"\"\"Perform fit using profile likelihood technique for background estimation and subtraction.\"\"\"\n listnames = self.get_noticed_list() # [ids.name for ids in self.listids[self.noticed_ids]]\n if len(listnames) > 0:\n wfit(listnames)\n print_fit()\n if do_covar is True:\n sau.covar(*listnames)\n if do_conf is True:\n sau.set_conf_opt('max_rstat', 10000)\n sau.conf(*listnames)\n print_conf()\n else:\n print(\"Empty noticed runs list. No fit\")\n\n def group(self, new_ext='_group', valid=None):\n \"\"\"Group spectra.\n \"\"\"\n totON = None\n totOFF = None\n tot_time = 0.\n tot_alpha = 0.\n tot_arf = None\n tot_rmf = None\n ntrue = 0\n nrec = 0\n\n group_dat = None\n group_bkg = None\n group_arf = None\n group_rmf = None\n\n newname = self.name + new_ext\n\n if valid is None:\n group_ids = np.ones((len(self.listids)), dtype=bool)\n elif valid.sum() > 0: # need a better type check obviously\n group_ids = valid\n else:\n print(\"Empty group. Do nothing.\")\n return\n\n # loop over all datasets\n for datid in self.listids[valid]:\n mydat = datid.data\n if totON is None:\n totON = np.zeros_like(mydat.counts)\n totOFF = np.zeros_like(mydat.get_background().counts)\n sau.copy_data(datid.name, newname)\n group_dat = sau.get_data(newname)\n group_dat.name = newname\n group_bkg = group_dat.get_background()\n\n # sum total ON and OFF\n totON += mydat.counts\n totOFF += mydat.get_background().counts\n\n # here we assume the background rate is the same with in each run so that we average alpha with time\n tot_alpha += mydat.exposure / mydat.get_background_scale()\n tot_time += mydat.exposure\n\n # compute average arf\n c_arf = mydat.get_arf().get_y()\n if tot_arf is None:\n tot_arf = np.zeros_like(c_arf)\n group_arf = group_dat.get_arf()\n\n tot_arf += c_arf * mydat.exposure\n\n # Compute average RMF\n c_rmf = mydat.get_rmf()\n\n # for now, we assume that n_grp is always equal to 1 which is the case for HESS rmfs generated with START\n # the channels to be used in the matrix are given by the cumulative sum of n_chan\n chans = c_rmf.n_chan.cumsum()\n\n # if not created, instantiate tmp_rmf\n if tot_rmf is None:\n group_rmf = group_dat.get_rmf()\n ntrue = int(c_rmf.get_dims()[0])\n nrec = int(c_rmf.detchans)\n tot_rmf = np.zeros((ntrue, nrec))\n\n c_rmf.matrix[np.where(np.isnan(c_rmf.matrix))] = 0.\n for i in np.arange(ntrue):\n irec_lo = c_rmf.f_chan[i]\n irec_hi = c_rmf.f_chan[i] + c_rmf.n_chan[i]\n indmin = chans[i]\n indmax = chans[i] + c_rmf.n_chan[i]\n if indmax < c_rmf.matrix.shape[0]:\n tot_rmf[i, irec_lo:irec_hi] += c_rmf.matrix[indmin:indmax] * c_arf[i] * mydat.exposure\n\n tot_arf /= tot_time\n tot_arf = np.abs(tot_arf)\n for i in np.arange(nrec):\n tot_rmf[:, i] /= tot_arf * tot_time\n\n tot_rmf[np.isnan(tot_rmf)] = 0.\n tot_alpha = tot_time / tot_alpha\n\n group_dat.counts = totON\n group_dat.exposure = tot_time\n\n group_bkg.name = newname + '_bkg'\n group_bkg.counts = totOFF\n group_bkg.backscal = 1. / tot_alpha\n group_bkg.exposure = tot_time\n\n group_rmf.name = newname + '_rmf'\n (ntrue, nrec) = tot_rmf.shape\n tot_rmf = np.abs(tot_rmf) # this is a hack and correct as long as negative elements modulus is <<1\n # reproject total rmf into new rmf with correct f_chan, n_chan and matrix\n ix, iy = np.where(tot_rmf > 0.)\n tmp = np.insert(np.diff(ix), 0, 1)\n new_index = np.where(tmp)[0]\n\n # Get first channel for a given true energy\n group_rmf.f_chan *= 0\n group_rmf.f_chan[ix[new_index]] = np.uint32(iy[new_index])\n\n # Find the number of channels\n group_rmf.n_chan *= 0\n group_rmf.n_chan[ix[new_index]] = np.uint32(np.append(iy[new_index - 1][1:], iy[-1]) - iy[new_index] + 1)\n group_rmf.matrix = tot_rmf[ix, iy]\n\n group_arf.name = newname + '_arf'\n group_arf.specresp = tot_arf\n\n group_dat.set_background(group_bkg)\n group_dat.set_arf(group_arf)\n group_dat.set_rmf(group_rmf)\n\n res = HESS_spec(newname)\n res.threshold = np.min(np.array([run.threshold for run in self.listids[valid]]))\n res.emax = 1e11\n return res\n\n def reproject(self, nbins=None, maxima=None, newname=None):\n \"\"\"Function perform reprojection of inidividual spectra (i.e. per run) into bands.\n\n Bands have similar offset, zenith angle and efficiency.\n The reprojection is performed using the group function.\n \"\"\"\n # need to add a check for the format of the nbins and maxima dictionaries\n if nbins is None:\n nbins = {'offset': 5, 'eff': 10., 'zen': 10}\n if maxima is None:\n maxima = {'offset': 2.5, 'eff': 100., 'zen': 70}\n\n off_max = maxima['offset']\n eff_max = maxima['eff']\n zen_max = maxima['zen'] * d2r\n coszen_max = np.cos(zen_max)\n\n n_offset_bins = nbins['offset']\n n_eff_bins = nbins['eff']\n n_zen_bins = nbins['zen']\n\n zen_step = (1.0 - coszen_max) / n_zen_bins\n off_step = off_max / n_offset_bins\n eff_step = eff_max / n_eff_bins\n\n zen_index = np.floor((np.cos(self.zeniths * d2r) - coszen_max) / zen_step).astype(int)\n off_index = np.floor(self.offsets / off_step).astype(int)\n eff_index = np.floor(self.effs / eff_step).astype(int)\n\n tot_index = off_index + 100 * zen_index + 10000 * eff_index\n unique_index, array_index = np.unique(tot_index, return_inverse=True)\n\n # create new specsource object\n if newname is None:\n newspec = SpecSource(self.name + '_grp')\n else:\n newspec = SpecSource(newname)\n\n newspec.listids = np.empty(len(unique_index), dtype=object)\n newspec.noticed_ids = np.ones(len(unique_index), dtype=bool)\n\n newspec.offsets = np.zeros(len(unique_index))\n newspec.zeniths = np.zeros(len(unique_index))\n newspec.effs = np.zeros(len(unique_index))\n newspec.thresholds = np.zeros(len(unique_index))\n\n for ind in range(len(unique_index)):\n newspec.listids[ind] = self.group(new_ext='_' + str(unique_index[ind]), valid=(array_index == ind))\n # cname = self.name+'_'+str(unique_index[ind])\n # newspec.listids[ind] = HESS_spec(cname)\n # newspec.listids[ind].threshold\n # Need to fill list of offsets, zenith and efficiencies\n # Need to check thresholds\n\n return newspec\n","sub_path":"gammapy/hspec/specsource.py","file_name":"specsource.py","file_ext":"py","file_size_in_byte":13575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"582018401","text":"import argparse\nimport os.path\nimport re\nimport subprocess\n\nimport ply.lex\nfrom flatex import expand_file\n\nparser = argparse.ArgumentParser(description='This method takes as inputs ')\n\nparser.add_argument('-i', dest='input',\n help='Input File (Required). It accepts only .tex files')\n\nparser.add_argument('-o', dest='output', default='',\n help='Output File (optional, default: input file with _clean as suffix)')\n\nparser.add_argument('-p', dest='pdflatex', action='store_const',\n const=True, default=False,\n help='If selected, runs pdflatex at the end')\n\nargs = parser.parse_args()\n\n\n\n\n# Usage\n# python stripcomments.py input.tex > output.tex\n# python stripcomments.py input.tex -e encoding > output.tex\n\n# modified from https://gist.github.com/amerberg/a273ca1e579ab573b499\n\n# Usage\n# python stripcomments.py input.tex > output.tex\n# python stripcomments.py input.tex -e encoding > output.tex\n\n# Modification:\n# 1. Preserve \"\\n\" at the end of line comment\n# 2. For \\makeatletter \\makeatother block, Preserve \"%\" \n# if it is actually a comment, and trim the line\n# while preserve the \"\\n\" at the end of the line. \n# That is because remove the % some time will result in\n# compilation failure.\n\ndef strip_comments(source):\n tokens = (\n 'PERCENT', 'BEGINCOMMENT', 'ENDCOMMENT',\n 'BACKSLASH', 'CHAR', 'BEGINVERBATIM',\n 'ENDVERBATIM', 'NEWLINE', 'ESCPCT',\n 'MAKEATLETTER', 'MAKEATOTHER',\n )\n states = (\n ('makeatblock', 'exclusive'),\n ('makeatlinecomment', 'exclusive'),\n ('linecomment', 'exclusive'),\n ('commentenv', 'exclusive'),\n ('verbatim', 'exclusive')\n )\n\n # Deal with escaped backslashes, so we don't\n # think they're escaping %\n def t_BACKSLASH(t):\n r\"\\\\\\\\\"\n return t\n\n # Leaving all % in makeatblock\n def t_MAKEATLETTER(t):\n r\"\\\\makeatletter\"\n t.lexer.begin(\"makeatblock\")\n return t\n\n # One-line comments\n def t_PERCENT(t):\n r\"\\%\"\n t.lexer.begin(\"linecomment\")\n\n # Escaped percent signs\n def t_ESCPCT(t):\n r\"\\\\\\%\"\n return t\n\n # Comment environment, as defined by verbatim package\n def t_BEGINCOMMENT(t):\n r\"\\\\begin\\s*{\\s*comment\\s*}\"\n t.lexer.begin(\"commentenv\")\n\n # Verbatim environment (different treatment of comments within)\n def t_BEGINVERBATIM(t):\n r\"\\\\begin\\s*{\\s*verbatim\\s*}\"\n t.lexer.begin(\"verbatim\")\n return t\n\n # Any other character in initial state we leave alone\n def t_CHAR(t):\n r\".\"\n return t\n\n def t_NEWLINE(t):\n r\"\\n\"\n return t\n\n # End comment environment\n def t_commentenv_ENDCOMMENT(t):\n r\"\\\\end\\s*{\\s*comment\\s*}\"\n # Anything after \\end{comment} on a line is ignored!\n t.lexer.begin('linecomment')\n\n # Ignore comments of comment environment\n def t_commentenv_CHAR(t):\n r\".\"\n pass\n\n def t_commentenv_NEWLINE(t):\n r\"\\n\"\n pass\n\n # End of verbatim environment\n def t_verbatim_ENDVERBATIM(t):\n r\"\\\\end\\s*{\\s*verbatim\\s*}\"\n t.lexer.begin('INITIAL')\n return t\n\n # Leave contents of verbatim environment alone\n def t_verbatim_CHAR(t):\n r\".\"\n return t\n\n def t_verbatim_NEWLINE(t):\n r\"\\n\"\n return t\n\n # End a % comment when we get to a new line\n def t_linecomment_ENDCOMMENT(t):\n r\"\\n\"\n t.lexer.begin(\"INITIAL\")\n\n # Newline at the end of a line comment is presevered.\n return t\n\n # Ignore anything after a % on a line\n def t_linecomment_CHAR(t):\n r\".\"\n pass\n\n def t_makeatblock_MAKEATOTHER(t):\n r\"\\\\makeatother\"\n t.lexer.begin('INITIAL')\n return t\n\n def t_makeatblock_BACKSLASH(t):\n r\"\\\\\\\\\"\n return t\n\n # Escaped percent signs in makeatblock\n def t_makeatblock_ESCPCT(t):\n r\"\\\\\\%\"\n return t\n\n # presever % in makeatblock\n def t_makeatblock_PERCENT(t):\n r\"\\%\"\n t.lexer.begin(\"makeatlinecomment\")\n return t\n\n def t_makeatlinecomment_NEWLINE(t):\n r\"\\n\"\n t.lexer.begin('makeatblock')\n return t\n\n # Leave contents of makeatblock alone\n def t_makeatblock_CHAR(t):\n r\".\"\n return t\n\n def t_makeatblock_NEWLINE(t):\n r\"\\n\"\n return t\n\n # For bad characters, we just skip over it\n def t_ANY_error(t):\n t.lexer.skip(1)\n\n lexer = ply.lex.lex()\n lexer.input(source)\n return u\"\".join([tok.value for tok in lexer])\n\n\nSTART_PATTERN = 'egin{document}'\nEND_PATTERN = 'nd{document}'\n\nMACRO_DICTIONARY = []\n\n\ndef gather_macro(strz):\n \"\"\"\n This method searches for defs, newcommands, edef, gdef,xdef, DeclareMathOperators and renewcommand\n and gets the macro structure out of it. Number\n \"\"\"\n\n subs_regexp = []\n # You can manually specify the number of replacements by changing the 4th argument\n should_parse = True\n # parse preamble\n for i, LINE in enumerate(strz.split('\\n')):\n if should_parse:\n if re.search(START_PATTERN, LINE):\n should_parse = False\n else:\n result = parse_macro_structure(LINE)\n if result:\n # print(result,line)\n MACRO_DICTIONARY.append(result)\n else:\n if re.search(END_PATTERN, LINE):\n break\n else:\n pass\n\n\ndef get_expanded_macro():\n subs_regexp = []\n for reg in MACRO_DICTIONARY:\n expanded_regexp = build_subs_regexp(reg)\n if expanded_regexp:\n subs_regexp.append(expanded_regexp)\n return subs_regexp\n\n\ndef remove_macro(st, o_file):\n subs_regexp = get_expanded_macro()\n should_substitute = False\n final_doc = []\n for i, LINE in enumerate(st.split('\\n')):\n if should_substitute:\n if re.search(END_PATTERN, LINE):\n final_doc.append(LINE)\n break\n else:\n # Perform substitutions\n try:\n LINE = re.sub(r'[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\xff]', '', recursive_expansion(LINE, subs_regexp))\n except Exception as e:\n print(e)\n print(LINE)\n break\n\n else:\n if re.search(START_PATTERN, LINE):\n should_substitute = True\n else:\n pass\n if not LINE.isspace():\n final_doc.append(LINE)\n with open(o_file, 'w') as o:\n for final_line in final_doc:\n if final_line.rstrip():\n o.write(final_line + '\\n')\n\n\ndef parse_macro_structure(ln):\n \"\"\"\n :param ln: a text line\n :return: structure (see below) of the macro inside the line (if any)\n \"\"\"\n regexp = r\"\\\\(.*command|DeclareMathOperator|def|edef|xdef|gdef)({|)(\\\\[a-zA-Z]+)(}|)(\\[([0-9])\\]|| +){(.*(?=\\}))\\}.*$\"\n result = re.search(regexp, ln)\n if result:\n regex = r\"\\\\([[:blank:]]|)(?![a-zA-Z])\"\n macro_structure = {\n 'command_type': result.group(1),\n 'macro_name': result.group(3),\n 'separator_open': result.group(2),\n 'separator_close': result.group(4),\n 'number_of_inputs': result.group(6),\n 'raw_replacement': re.sub(regex, '', result.group(7)),\n }\n return macro_structure\n else:\n return None\n\n\ndef build_subs_regexp(reg):\n \"\"\"\n This method creates the replacement text for the macro.\n TODO:\n - extend this to any input macro\n - recursively expand raw_replacements (up to any degree)\n - build tests\n \"\"\"\n if re.search('declare', reg[\"command_type\"]):\n\n pass\n else:\n if not reg[\"number_of_inputs\"]:\n # The macro has no inputs\n return {'sub': reg[\"raw_replacement\"], 'reg': '\\\\' + reg[\"macro_name\"] + '(?![a-zA-Z])', }\n else:\n # The macro has one or more inputs\n pass\n\n\ndef recursive_expansion(lin, available_regexp):\n for subs in available_regexp:\n if not (re.search(subs[\"reg\"], lin)):\n continue\n else:\n try:\n lin = re.sub(subs[\"reg\"], re.sub(r'([\\\" \\' \\\\\\ ])', r'\\\\\\1', subs[\"sub\"]), lin)\n except Exception as e:\n print(e,lin)\n for subs in available_regexp:\n if not (not (re.search(subs[\"reg\"], lin))):\n return recursive_expansion(lin, available_regexp)\n else:\n continue\n return lin\n\n\n# Begin of actual methods. First check if the input is a LaTex file\nif args.input.endswith('.tex'):\n # Check the number of outputs. If no output is given, create a new one.\n if not args.output:\n a = args.input;\n args.output = a.replace('.tex', '_clean.tex')\n # Assign the macro file address and some temporary files.\n FOLDER_PATH = os.path.abspath(os.path.join(os.path.abspath(args.input), os.pardir))\n MACRO_FILE = os.path.join(FOLDER_PATH, \"user_macro.sty\")\n TEMP_FILE_PRE_EXPANSION = os.path.join(FOLDER_PATH, \"temp_pre.tex\")\n\n # Reads the file preamble to obtain the user-defined macros. We also remove unwanted comments.\n print(\"gather macros from preamble\")\n with open(args.input, 'r') as i:\n line = strip_comments(i.read())\n gather_macro(line)\n # Reads user-macro file to obtain the user-defined macros. We also remove unwanted comments\n print(\"gather macros from user defined file\")\n if os.path.exists(MACRO_FILE):\n with open(MACRO_FILE, 'r') as i:\n line = strip_comments(i.read())\n gather_macro(line)\n # Remove the macros from the main file and writes the output to a temp file.\n print(\"remove macros from main file\")\n with open(args.input, 'r') as i:\n line = strip_comments(i.read())\n remove_macro(line, TEMP_FILE_PRE_EXPANSION)\n\n # Get path of temp file.\n current_path = os.path.split(TEMP_FILE_PRE_EXPANSION)[0]\n\n # Include all the external files\n print(\"include external files in main file\")\n final_text_to_expand = strip_comments(''.join(expand_file(TEMP_FILE_PRE_EXPANSION, current_path, True, False)))\n # Remove temp file\n os.remove(TEMP_FILE_PRE_EXPANSION)\n\n # Remove macros from the entire file and put the result to temp file\n print(\"remove macros from entire file\")\n remove_macro(final_text_to_expand, TEMP_FILE_PRE_EXPANSION)\n\n #get script folder\n script_path = os.path.abspath(os.path.join(__file__, os.pardir))\n preprocess_path = os.path.join(script_path, \"..\", \"Perl\", \"AxessibilityPreprocess.pl\")\n preprocess_compile_path = os.path.join(script_path, \"..\", \"Perl\", \"AxessibilityPreprocesspdfLatex.pl\")\n\n #Call perl scripts to clean dollars, underscores. Eventually, it can call also pdflatex, when -p is selected\n if args.pdflatex:\n print(\"final cleaning file\")\n p = subprocess.Popen(\n [\"perl\", preprocess_compile_path, \"-w\", \"-o\", \"-s\", TEMP_FILE_PRE_EXPANSION, args.output])\n else:\n print(\"final cleaning file and pdf production\")\n p = subprocess.Popen(\n [\"perl\", preprocess_path, \"-w\", \"-o\", \"-s\", TEMP_FILE_PRE_EXPANSION, args.output])\n # close process.\n p.communicate()\n\n # remove spurious file\n os.remove(TEMP_FILE_PRE_EXPANSION)\n os.remove(TEMP_FILE_PRE_EXPANSION.replace('.tex', '.bak'))\nelse:\n print('The file you inserted as input is not a .tex')\n","sub_path":"src/Py/axesscleaner.py","file_name":"axesscleaner.py","file_ext":"py","file_size_in_byte":11558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300496350","text":"import sys\nsys.path.append(\"..\")\nimport os\nimport cv2\nimport numpy as np\nfrom pipeline import CameraCalibration, BirdsEyeView, ImageSection, Point\n\n_cc = CameraCalibration.from_pickle(os.path.join('..', 'calibration.pkl'))\n\n_section = ImageSection(\n top_left=Point(x=580, y=461.75),\n top_right=Point(x=702, y=461.75),\n bottom_right=Point(x=1013, y=660),\n bottom_left=Point(x=290, y=660),\n)\n\n_bev = BirdsEyeView(_section,\n section_width=3.6576, # one lane width in meters\n section_height=2 * 13.8826) # two dash distances in meters\n\n\ndef undistort_and_warp(img: np.ndarray) -> np.ndarray:\n img, _ = _cc.undistort(img, False)\n return _bev.warp(img)\n\n\ndef build_roi_mask() -> np.ndarray:\n h, w = 760, 300 # warped.shape[:2]\n roi = [\n [0, 0], [w, 0],\n [w, 630], [230, h],\n [70, h], [0, 630]\n ]\n roi_mask = np.zeros(shape=(h, w), dtype=np.uint8)\n return cv2.fillPoly(roi_mask, [np.array(roi)], 255, cv2.LINE_4)\n\n\ndef luminance_constancy_lab(lab: np.ndarray, kernel_size: int=127) -> np.ndarray:\n lightness = lab[..., 0]\n blurred = cv2.GaussianBlur(lightness, (kernel_size, kernel_size), 0)\n adjusted = lightness / (blurred + 0.001)\n vmin, vmax = adjusted.min(), adjusted.max()\n adjusted = (adjusted - vmin) / (vmax - vmin)\n adjusted = np.clip(adjusted * 255, 0, 255).astype(np.uint8)\n return np.stack([adjusted, lab[..., 1], lab[..., 2]], axis=2)\n","sub_path":"notebooks/scripts/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"191591812","text":"import fcntl\nimport sys\n\nlock_filename = 'chat.txt'\nlock_file = open(lock_filename, 'a')\nk=1\nwhile(k):\n\ttry:\n\t\tfcntl.lockf(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)\n\t\tk = 0\n\texcept IOError:\n\t\tk = 1\n\nprint('Locked! Running code...')\n\nquit = False\nwhile quit is not True:\n quit = input('Press q to quit ')\n quit = str(quit) == 'q'\n\nprint('Bye!')\nsys.exit(0)","sub_path":"loc.py","file_name":"loc.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"537928097","text":"from collections import defaultdict, namedtuple, Counter, deque\nimport csv\nimport random\nfrom urllib.request import urlretrieve\n\n\n\n\nif __name__ == \"__main__\":\n user = ('bob', 'code')\n\n print(f'{user[0]} is a {user[1]}')\n\n User = namedtuple('User', 'name role')\n\n user = User(name='bob', role='coder')\n\n print(f'{user.name} is a {user.role}')\n\n challenges_done = [('mike', 10), ('julian', 7), ('bob', 5),\n ('mike', 11), ('julian', 8), ('bob', 6)]\n\n\n challenges = {}\n try:\n for name, challenge in challenges_done:\n challenges[name].append(challenge)\n except KeyError as e:\n print(e)\n\n challenges = defaultdict(list) \n for name, challenge in challenges_done:\n challenges[name].append(challenge)\n\n print(challenges)\n\n\n words = \"\"\"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been \nthe industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and \nscrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into \nelectronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of\nLetraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus\nPageMaker including versions of Lorem Ipsum\"\"\".split()\n print(words[:5])\n\n commom_words = {}\n\n print(Counter(words).most_common(5))\n\n movie_data = 'https://raw.githubusercontent.com/pybites/challenges/solutions/13/movie_metadata.csv'\n movies_csv = 'movies.csv'\n urlretrieve(movie_data, movies_csv)\n\n Movie = namedtuple('Movie', 'title year score')\n\n def get_movies_by_director(data=movies_csv):\n directors = defaultdict(list)\n with open(data, encoding='utf-8') as f:\n for line in csv.DictReader(f):\n try:\n director = line['director_name']\n movie = line['movie_title'].replace('\\xa0', '')\n year = int(line['title_year'])\n score = float(line['imdb_score'])\n except ValueError:\n continue\n\n m = Movie(title=movie, year=year, score=score)\n directors[director].append(m)\n \n return directors\n\n directors = get_movies_by_director()\n\n print(directors['Christopher Nolan'])\n\n cnt = Counter()\n for director, movies in directors.items():\n cnt[director] += len(movies)\n\n print(cnt.most_common(5))\n\n\n\n\n","sub_path":"talkpython/04-06-collections/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26968873","text":"filein=open(\"B-large.in\")\r\nfileout=open(\"B-large.out\",\"w\")\r\nasdf=[]\r\nfor get in filein:\r\n asdf.append(get.rstrip('\\n'))\r\na=int(asdf[0])\r\nfor x in range(1,a+1):\r\n b=asdf[x]\r\n count=0\r\n result=0\r\n q='-'\r\n for z in b:\r\n if(z=='-'):\r\n count=count+1\r\n if(q=='+'):\r\n result=result+1\r\n q='-'\r\n else:\r\n if(count!=0):\r\n result=result+1\r\n count=0\r\n q='+'\r\n if(count!=0):\r\n result=result+1\r\n #result=str(result)\r\n zz=str(x)\r\n result=str(result)\r\n #print(result)\r\n fileout.write(\"Case #\"+zz+\": \"+result+'\\n')\r\nfilein.close()\r\nfileout.close()\r\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_theGamer_pncake.py","file_name":"16_0_2_theGamer_pncake.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"184502368","text":"#! /usr/bin/env python\n#\n## Begin copyright\n##\n## /home/jrf/Documents/books/Books20/Docs/Series/table.py\n##\n## Part of the Books20 Project\n##\n## Copyright 2018 James R. Fowler\n##\n## All rights reserved. No part of this publication may be\n## reproduced, stored in a retrival system, or transmitted\n## in any form or by any means, electronic, mechanical,\n## photocopying, recording, or otherwise, without prior written\n## permission of the author.\n##\n##\n## End copyright\n'''\n Definitions for generic table printing\n function using the LaTeX style longtable\n'''\n\n#from __future__ import print_function\n\ndef protect_str(raw_str):\n r'''Make a TeX string with \\ and {} safe for\n python print().\n\n '''\n\n raw_str.replace(r\"\\\\\", r'\\\\\\\\')\n return raw_str\n\n\ndef print_table_comment(tbl_comment):\n '''Print a general TeX comment explaining the table\n and its purpose.\n '''\n raw_comment = r'''{}'''.format(tbl_comment)\n safe_comment = protect_str(raw_comment)\n print(safe_comment)\n\ndef print_table_copyright(tbl_copyright):\n '''Print a general TeX comment with copyright information.\n '''\n raw_copyright = r'''{}'''.format(tbl_copyright)\n safe_copyright = protect_str(raw_copyright)\n print(safe_copyright)\n\ndef print_table_preamble(tbl_preamble):\n '''Print the preamble strings before the start of the\n longtable environment\n '''\n if tbl_preamble:\n safe_preamble = protect_str(tbl_preamble)\n else:\n raw_preamble = r'''\\setlength\\LTleft{0pt}'''\n #\\setlength\\LTright{0pt}'''\n safe_preamble = protect_str(raw_preamble)\n print(safe_preamble)\n\ndef print_table_start(tbl_format):\n '''Print the start of the table and the desired format.\n '''\n raw_format = r'\\begin{}{}'.format('{longtable}', tbl_format)\n safe_format = protect_str(raw_format)\n print(safe_format)\n\ndef print_table_caption(tbl_caption):\n '''Print the table caption string.\n '''\n raw_caption = r' \\caption{}{}{} \\\\'.format('{', tbl_caption, '}')\n safe_caption = protect_str(raw_caption)\n print(safe_caption)\n\ndef print_table_label(tbl_label):\n '''Print the reference label for the table. This reference\n may be used else where in the documemt to provide a link to\n the table.\n '''\n raw_label = r' \\label{}{}{} \\\\'.format('{', tbl_label, '}')\n safe_label = protect_str(raw_label)\n print(safe_label)\n\ndef print_table_heading(numcol, tbl_heading, continue_label):\n '''Print the column headings for the first page of the table\n and and continuation column header for columns on the subsequent\n pages. '''\n\n raw_heading = r''' {0} \\\\\n \\hline\\hline\n \\endfirsthead\n\n \\multicolumn{1}{2}{3}{4}{5}{6}{7} \\\\\n {8} \\\\\n \\hline\\hline\n \\endhead\n\n'''.format(tbl_heading, '{', numcol, '}', '{c}', '{', continue_label, '}', tbl_heading)\n safe_heading = protect_str(raw_heading)\n print(safe_heading)\n #print('\\n', safe_heading)\n\ndef print_table_footer(tbl_footer, continue_footer):\n '''Print the footer for the first page of the table and\n the continuation footer for subsequent pages.\n '''\n raw_footer = r''' \\hline\n {0}\n \\endfoot\n \n \\hline\\hline\n {1}\n \\endlastfoot\n\n'''.format(tbl_footer, continue_footer)\n safe_footer = protect_str(raw_footer)\n print(safe_footer)\n\ndef print_table_end():\n '''Print the table closing string.'''\n raw_end = r'''\\end{}\n\n%%\n%%\n%%\n'''.format('{longtable}')\n safe_end = protect_str(raw_end)\n print('\\n', safe_end)\n","sub_path":"Books20/Docs/Series/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69786388","text":"from importlib import util\nimport os\nimport subprocess\nimport sys\nimport inspect\n\nBRANCH = \"master\"\nSANDBOX = \"/sandbox\"\n\n# get current install.py directory\nrootdir = os.path.dirname(os.path.abspath(__file__))\n\npath = os.path.join(rootdir, \"InstallTools.py\")\n\nif not os.path.exists(path):\n cmd = \"cd %s;rm -f InstallTools.py;curl https://raw.githubusercontent.com/threefoldtech/jumpscaleX/%s/install/InstallTools.py?$RANDOM > InstallTools.py\" % (rootdir, BRANCH)\n subprocess.call(cmd, shell=True)\n\nspec = util.spec_from_file_location(\"IT\", path)\nIT = spec.loader.load_module()\n\nsys.excepthook = IT.my_excepthook\n\nargs={}\n\ndef help():\n T=\"\"\"\n 3bot development environment based on docker\n --------------------------------------------\n\n -h = this help\n\n commands:\n install : get docker & install 3bot\n export --file=$file : export the container\n import --file=$file : import the container & start\n stop : stop the container\n kosmos : is the kosmos shell (JSX shell)\n bash : is the bash shell inside the container\n\n e.g. python3 3bot_dev.py install -d -y -c\n e.g. python3 3bot_dev.py export --file=/tmp/3bot.tar\n\n install options\n ---------------\n\n -y = answer yes on every question (for unattended installs)\n -c = will confirm all filled in questions at the end (useful when using -y)\n -s = from scratch, means will start from empty ubuntu and re-install everything\n -r = reinstall, basically means will try to re-do everything without removing the data\n -d = if set will delete the docker container if it already exists\n\n --debug will launch the debugger if something goes wrong\n\n ## encryption\n\n --secret = std is '1234', if you use 'SSH' then a secret will be derived from the SSH-Agent (only if only 1 ssh key loaded\n --private_key = std is '' otherwise is 24 words, use '' around the private key\n if secret specified and private_key not then will ask in -y mode will autogenerate\n\n ## code related\n\n --codepath = is where the github code will be checked out, default /sandbox/code if it exists otherwise ~/code\n --pull = pull code from git, if not specified will only pull if code directory does not exist yet\n --branch = jumpscale branch: normally 'master' or 'development' for unstable release\n\n \"\"\"\n print(IT.Tools.text_replace(T))\n sys.exit(0)\n\nargs= IT.Tools.cmd_args_get()\n\nif not \"codepath\" in args:\n args[\"codepath\"] = None\n\nif not \"branch\" in args:\n args[\"branch\"]=BRANCH\n\nif \"name\" not in args:\n args[\"name\"] = \"3bot\"\n\nif \"sshkey\" not in args:\n args[\"sshkey\"] = None\n\nif \"h\" in args or args=={}:\n help()\n\nIT.MyEnv.init(basedir=None,config={},readonly=True,codepath=args[\"codepath\"])\n\ndef install_ui(args):\n\n\n if \"s\" in args:\n # args[\"image\"] = \"despiegk/3bot\"\n args[\"image\"] = \"phusion/baseimage\"\n\n if not IT.MyEnv.sshagent_active_check():\n T=\"\"\"\n Did not find an SSH key in ssh-agent, is it ok to continue without?\n It's recommended to have a SSH key as used on github loaded in your ssh-agent\n If the SSH key is not found, repositories will be cloned using https\n\n if you never used an ssh-agent or github, just say \"y\"\n\n \"\"\"\n if \"y\" not in args:\n if not IT.Tools.ask_yes_no(\"OK to continue?\"):\n sys.exit(1)\n\n if \"y\" not in args and \"r\" not in args:\n if IT.Tools.ask_yes_no(\"\\nDo you want to redo the full install? (means redo pip's ...)\"):\n args[\"r\"]=True\n\n if args[\"name\"] in IT.Docker.docker_names():\n if \"d\" not in args:\n if not \"y\" in args:\n if IT.Tools.ask_yes_no(\"docker:%s exists, ok to remove? Will otherwise keep and install inside.\"%args[\"name\"]):\n args[\"d\"]=True\n\n\n if \"image\" in args:\n if \"d\" not in args:\n #because if we specify image we want to delete the running docker\n args[\"d\"]=True\n if \":\" not in args[\"image\"]:\n args[\"image\"]=\"%s:latest\" % args[\"image\"]\n # if args[\"image\"] not in IT.Docker.image_names():\n # if IT.Tools.exists(args[\"image\"]):\n # IT.Tools.shell()\n # else:\n # print(\"Cannot continue, image '%s' specified does not exist.\"%args[\"image\"])\n # sys.exit(1)\n\n if \"pull\" not in args:\n if \"y\" not in args:\n #not interactive ask\n if IT.Tools.ask_yes_no(\"Do you want to pull code changes from git?\"):\n args[\"pull\"]=True\n else:\n #default is not pull\n args[\"pull\"]=False\n\n if \"y\" in args:\n\n if \"secret\" not in args:\n if IT.MyEnv.sshagent_active_check():\n args[\"secret\"] = \"SSH\"\n else:\n args[\"secret\"] = \"1234\"\n if \"private_key\" not in args:\n args[\"private_key\"] = \"\"\n else:\n if \"secret\" not in args:\n if IT.MyEnv.sshagent_active_check():\n args[\"secret\"] = IT.Tools.ask_string(\"Optional: provide secret to use for passphrase, if ok to use SSH-Agent just press 'ENTER'\",default=\"SSH\")\n else:\n args[\"secret\"] = IT.Tools.ask_string(\"please provide secret passphrase for the BCDB.\",default=\"1234\")\n if \"private_key\" not in args:\n args[\"private_key\"] = IT.Tools.ask_string(\"please provide 24 words of the private key, or just press 'ENTER' for autogeneration.\")\n\n # if \"y\" not in args and \"w\" not in args:\n # if IT.Tools.ask_yes_no(\"Do you want to install lua/nginx/openresty & wiki environment?\"):\n # args[\"w\"]=True\n\n\n T=\"\"\"\n\n Jumpscale X Installer\n ---------------------\n\n \"\"\"\n T=IT.Tools.text_replace(T)\n\n if IT.MyEnv.sshagent_active_check():\n T+= \" - sshkey used will be: %s\\n\"%IT.MyEnv.sshagent_key_get()\n\n T+=\" - location of code path is: %s\\n\"%args[\"codepath\"]\n if \"w\" in args:\n T+=\" - will install wiki system at end\\n\"\n if \"3\" in args:\n T+=\" - name of container is: %s\\n\"%args[\"name\"]\n if args[\"container_exists\"]:\n if \"d\" in args:\n T+=\" - will remove the docker, and recreate\\n\"\n else:\n T+=\" - will keep the docker container and install inside\\n\"\n\n if \"image\" in args:\n T+=\" - will use docker image: '%s'\\n\"%args[\"image\"]\n\n portrange = args[\"portrange\"]\n\n a=8000+int(portrange)*10\n b=8004+int(portrange)*10\n portrange_txt=\"%s-%s:8000-8004\"%(a,b)\n port = 9000+int(portrange)*100 + 22\n\n T+=\" - will map ssh port to: '%s'\\n\"%port\n T+=\" - will map portrange '%s' (8000-8004) always in container.\\n\"% portrange_txt\n\n if \"debug\" in args:\n IT.MyEnv.debug = True\n T+=\" - runs in debug mode (means will use debugger when error).\\n\"\n\n T+=\"\\n\"\n print(T)\n\n if \"c\" in args or \"y\" not in args:\n if not IT.Tools.ask_yes_no(\"Ok to continue?\"):\n sys.exit(1)\n\n return args\n\nif \"portrange\" not in args:\n args[\"portrange\"]=1\n\nif \"install\" in args or \"import\" in args:\n args = install_ui(args)\n\ndelete = \"d\" in args\n\nif not \"import\" in args:\n docker=IT.Docker(name=\"3bot\",delete=delete, portrange=args[\"portrange\"],sshkey=args[\"sshkey\"],image=args[\"image\"])\n\nif \"install\" in args:\n docker.jumpscale_install(secret=args[\"secret\"],private_key=args[\"private_key\"])\n\nelif \"stop\" in args:\n if args[\"name\"] in docker.docker_running():\n IT.Tools.execute(\"docker stop %s\"% args[\"name\"])\nelif \"export\" in args:\n if args[\"name\"] in docker.docker_running():\n if \"file\" not in args:\n print(\"specify export file with --file $path\")\n sys.exit(1)\n if not args[\"file\"].endswith(\".tar\"):\n print(\"export file needs to end with .tar\")\n sys.exit(1)\n print(\"export docker:%s to %s, will take a while\"% (args[\"name\"],args[\"file\"]))\n IT.Tools.execute(\"docker export %s -o %s\"% (args[\"name\"],args[\"file\"]))\n else:\n print(\"cannot find docker:%s\"%args[\"name\"])\n sys.exit(1)\nelif \"import\" in args:\n if \"file\" not in args:\n print(\"specify export file with --file $path\")\n sys.exit(1)\n if not IT.Tools.exists(args[\"file\"]):\n print(\"could not find import file:%s\"%args[\"file\"])\n sys.exit(1)\n if not args[\"file\"].endswith(\".tar\"):\n print(\"export file needs to end with .tar\")\n sys.exit(1)\n print(\"import docker:%s to %s, will take a while\"% (args[\"name\"],args[\"file\"]))\n IT.Tools.execute(\"docker import %s local/imported\"% (args[\"file\"]))\n docker=IT.Docker(name=\"3bot\",delete=True, portrange=args[\"portrange\"],sshkey=args[\"sshkey\"],image=\"local/imported\")\nelif \"kosmos\" in args:\n cmd = \"echo\\nssh root@localhost -A -p %s 'source /sandbox/env.sh;kosmos'\"%docker.port\n IT.Tools.execute(cmd,interactive=True,die=False,showout=False)\nelif \"bash\" in args:\n cmd = \"echo\\nssh root@localhost -A -p %s 'source /sandbox/env.sh;bash'\"%docker.port\n IT.Tools.execute(cmd,interactive=True,die=False,showout=False)\n\n\nelse:\n print (help())\n\n","sub_path":"install/3bot_dev.py","file_name":"3bot_dev.py","file_ext":"py","file_size_in_byte":9223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"530620926","text":"from src.circuits.evaluator import BasicEvaluator\nfrom src.circuits.evaluator import SecureEvaluator\nfrom src.circuits.dealer import Dealer\nfrom src.circuits.oracle import Oracle\nfrom examples.svm import circuit as circ\nimport numpy as np\nfrom threading import Thread\nimport copy\nfrom examples.svm.alg import alter_data\nimport asyncio\nimport time\n\n\n\ndef secure_eval_circuit(data,num_iterations,modulus,initial_w=0,initial_b=0,fp_precision=16):\n \"\"\"\n Function that evaluates the perceptron circuit using three SecureEvaluator\n objects. The current protocol also requires a Dealer and an Oracle.\n\n Parameters\n ----------\n data: iterable\n Data to be input into the perceptron algorithm (assumed iterable pairs)\n num_iterations: int\n Number of iterations that algorithm will run for\n modulus: int\n Value representing the modulus of field used\n (optional) initial_w=0: int\n Initial value of w, parameter of perceptron algorithm\n (optional) initial_b=0: int\n Initial value of b, parameter of perceptron algorithm\n (optional) fp_precision=16: int\n Fixed point number precision\n\n Returns\n -------\n w: float\n w value achieved after num_iterations of perceptron\n b: int\n b value achieved after num_iterations of perceptron\n \"\"\"\n\n # alter data to work for svm\n data = alter_data(data)\n\n # account for fixed point precision\n scale = 10**fp_precision\n\n circ1 = copy.deepcopy(circ.circuit)\n circ2 = copy.deepcopy(circ.circuit)\n circ3 = copy.deepcopy(circ.circuit)\n\n # initialize evaluators\n evaluator1 = SecureEvaluator(circ1,circ.in_gates,circ.out_gates,1,modulus,fp_precision=fp_precision)\n evaluator2 = SecureEvaluator(circ2,circ.in_gates,circ.out_gates,2,modulus,fp_precision=fp_precision)\n evaluator3 = SecureEvaluator(circ3,circ.in_gates,circ.out_gates,3,modulus,fp_precision=fp_precision)\n\n #evaluator1 = SecureEvaluator(circ1,circ.in_gates,circ.out_gates,1,oracle,modulus)\n #evaluator2 = SecureEvaluator(circ2,circ.in_gates,circ.out_gates,2,oracle,modulus)\n #evaluator3 = SecureEvaluator(circ3,circ.in_gates,circ.out_gates,3,oracle,modulus)\n\n\n parties = [evaluator1,evaluator2,evaluator3]\n party_dict = {1: evaluator1, 2: evaluator2, 3: evaluator3}\n\n evaluator1.add_parties(party_dict)\n evaluator2.add_parties(party_dict)\n evaluator3.add_parties(party_dict)\n\n # initialize dealer\n dealer = Dealer(parties,modulus,fp_precision=fp_precision)\n\n start_time = time.time()\n\n # split x_data and y_data into 3 lists, one for each party\n # this simulates each party having private input data\n data_len = len(data)\n data1x = []\n data2x = []\n data3x = []\n data1y = []\n data2y = []\n data3y = []\n\n split = int(data_len/3)\n\n for i in range(split):\n data1x.append(data[i][0])\n data1y.append(data[i][1])\n data2x.append(data[split + i][0])\n data2y.append(data[split + i][1])\n data3x.append(data[2*split + i][0])\n data3y.append(data[2*split + i][1])\n\n # use dealer to create shares of all inputs\n dealer.distribute_shares(data1x)\n dealer.distribute_shares(data2x)\n dealer.distribute_shares(data3x)\n\n dealer.distribute_shares(data1y)\n dealer.distribute_shares(data2y)\n dealer.distribute_shares(data3y)\n\n # use dealer to create random values for interactive operations\n num_randomness = 10000 * num_iterations\n dealer.generate_randomness(num_randomness)\n dealer.generate_truncate_randomness(5*num_iterations)\n\n # need to make dimenions of w the same as x\n if initial_w == 0:\n first_x = data[0][0]\n initial_w = np.zeros(len(first_x))\n initial_w = [initial_w,[]]\n\n dealer.distribute_shares(initial_w)\n #dealer.distribute_shares(initial_b)\n\n results = {}\n\n # for each iteration of perceptron algorithm, have each SecureEvaluator\n # compute the circuit, each on their own thread, so they can interact\n res = {}\n for i in range(num_iterations):\n #for i in range(1):\n\n #print(\"iteration: \" + str(i))\n \n t1 = Thread(target=run_eval,args=(evaluator1,i,data_len,results,1,modulus,fp_precision,res))\n t2 = Thread(target=run_eval,args=(evaluator2,i,data_len,results,2,modulus,fp_precision,res))\n t3 = Thread(target=run_eval,args=(evaluator3,i,data_len,results,3,modulus,fp_precision,res))\n\n t1.start()\n t2.start()\n t3.start()\n\n t1.join()\n t2.join()\n t3.join()\n\n #for a in range(150):\n #for a in range(5):\n # print(\"iter \" + str(a) + \": \" + str(unshare(res[str(a)+\"_1\"][0],res[str(a)+\"_2\"][0])))\n\n # extract final outputs, scale them down\n (w,b) = get_w_b(results)\n #return (w / scale, b / scale)\n wout = []\n for el in w:\n wout.append(el / scale)\n bout = b / scale\n elapsed_time = time.time() - start_time\n print(\"elapsed time: \" + str(elapsed_time))\n return (np.array(wout),bout)\n\ndef unshare(share1,share2):\n \"\"\"\n Method for converting shares into their hidden value\n\n Parameters\n ----------\n share1: int or iterable\n Shares of value\n share2: int or iterable\n Shares of same value as share1\n\n Returns\n -------\n res:\n value hidden by share1 and share2\n \"\"\"\n\n if type(share1) == list:\n res = []\n for i in range(len(share1)):\n res.append(share1[i].unshare(share2[i]))\n\n else:\n res = share1.unshare(share2)\n\n return res\n\ndef get_w_b(w_b_shares):\n \"\"\"\n Method for computing (w,b) from their shares\n\n Parameters\n ----------\n w_b_shares: dictionary\n Dictionary of shares for values of (w,b)\n\n Returns\n -------\n w: float\n w value achieved after num_iterations of perceptron\n b: int\n b value achieved after num_iterations of perceptron\n \"\"\"\n\n w1 = w_b_shares[1]['w']\n w2 = w_b_shares[2]['w']\n w3 = w_b_shares[3]['w']\n\n w = [w1[0].unshare(w2[0]), w1[1].unshare(w2[1])]\n b = w1[2].unshare(w2[2])\n\n return (w,b)\n\n\ndef run_eval(evaluator,iter_num,data_length,results_dict,party_index,mod,fp_precision=16,wd={}):\n \"\"\"\n Method to be run by each SecureEvaluator within their Thread (this will be\n called with secure_eval_circuit).\n\n Parameters\n ----------\n evaluator: SecureEvaluator object\n SecureEvaluator that will compute an iteration of perceptron algorithm\n iter_num: int\n Iteration number of perceptron algorithm\n data_length: int\n Integer representing length of input data\n results_dict: dictionary\n Dictionary for each thread to insert ouput values\n party_index: int\n Integer representing evaluator party index\n (optional) fp_precision=16: int\n Fixed point number precision\n \"\"\"\n\n scale = 10**fp_precision\n\n # input will map wire name to index in list of shares\n cur_input = {}\n cur_input[\"in0\"] = iter_num\n cur_input[\"in1\"] = data_length + iter_num\n\n # only load initial b and w\n #if iter_num == 0:\n # cur_input[\"in2\"] = -2\n # cur_input[\"in3\"] = -1\n\n cur_input[\"in2\"] = -1\n\n evaluator.load_secure_inputs(cur_input)\n\n # need to load in constant values\n # -1: for computing <=1, subtract 1 and comp <= 0\n # gam1: need to have 1 - gamma for computing w\n # gamC: need gamma * C also for computing w\n neg1 = int(-1*scale)\n pre_gamma = 1.0 / (1.0 + iter_num)\n gamma = round(pre_gamma * 10**7)\n gamma = int(gamma * scale)\n gamma = int(gamma / 10**7)\n gam1 = int(1*scale - gamma)\n gamC = int(gamma * 1)\n\n load_in_constants = {}\n load_in_constants[\"in3\"] = gam1\n load_in_constants[\"in4\"] = gamC\n load_in_constants[\"in5\"] = neg1\n\n evaluator.load_inputs(load_in_constants)\n\n evaluator.run()\n\n [w] = evaluator.get_outputs()\n evaluator.reset_circuit()\n\n wd[str(iter_num) + \"_\" + str(party_index)] = [w]\n\n #cur_in = {}\n #cur_in[\"in2\"] = w\n #cur_in[\"in3\"] = b\n #evaluator.load_inputs(cur_in)\n\n evaluator.receive_shares([w])\n\n results_dict[party_index] = {\"w\": w}\n\ndef mod_inverse(val, mod):\n g, x, y = egcd(val, mod)\n if g != 1:\n raise Exception('modular inverse does not exist')\n else:\n return x % mod\n\ndef egcd(a,b):\n if a == 0:\n return (b,0,1)\n else:\n g, y, x = egcd(b %a, a)\n return (g, x - (b //a) * y, y)\n\n\nif __name__ == \"__main__\":\n\n MOD = 10001112223334445556667778889991\n\n # 199 bits\n #MOD = 622288097498926496141095869268883999563096063592498055290461\n\n #MOD = 24684249032065892333066123534168930441269525239006410135714283699648991959894332868446109170827166448301044689\n\n import data.iris_data as iris\n\n data = iris.get_iris_data()\n\n num_iter = len(data)\n #num_iter = 10\n\n print(secure_eval_circuit(data,num_iter,MOD,fp_precision=10))","sub_path":"examples/svm/eval_circuit.py","file_name":"eval_circuit.py","file_ext":"py","file_size_in_byte":8871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"193411036","text":"# Solution for Task 2\r\n\r\n# import packages\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.metrics import mean_squared_error, r2_score\r\nfrom sklearn.model_selection import train_test_split\r\nimport pandas as pd\r\n\r\n# load data set\r\ndata = pd.read_csv('dataset_small.csv')\r\n\r\n# fill missing values\r\ndata[\"dti\"]=data[\"dti\"].fillna(data[\"dti\"].mean())\r\n\r\n# select X and y from data set\r\ny = data['int_rate']\r\nX = data[['dti','loan_amnt']]\r\n\r\n# get random train and test data from data set\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\r\n\r\n# Configure model\r\nregr = RandomForestRegressor(max_depth = 2, n_estimators=100, max_features='sqrt')#, random_state = 42)\r\n\r\n# Fit regression model\r\nregr.fit(X_train, y_train)\r\n\r\n# Predict\r\ny_1 = regr.predict(X_test)\r\n\r\n# evaluation\r\nmse1 = mean_squared_error(y_test, y_1)\r\nr2_1 = r2_score(y_test, y_1)\r\nprint('RF: mse = '+ str(mse1) + ' r2 = '+ str(r2_1))\r\n\r\n","sub_path":"2-DataScience/3-simpleModelApplication/skeleton_RF_solution.py","file_name":"skeleton_RF_solution.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"417687134","text":"import cv2\nimport torchvision.transforms as tfs\nimport imgaug\n\n# for imgaug\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nimport numpy as np\nimport PIL\n\nclass ImgAugTransform:\n def __init__(self,aug_level):\n \n frequently = lambda aug: iaa.Sometimes(0.9, aug)\n often = lambda aug: iaa.Sometimes(0.7, aug)\n sometimes = lambda aug: iaa.Sometimes(0.5, aug)\n occasionally = lambda aug: iaa.Sometimes(0.3, aug)\n rarely = lambda aug: iaa.Sometimes(0.1, aug)\n \n if aug_level == 'high':\n self.aug = iaa.Sequential([\n \n sometimes(iaa.Crop(percent=(0, 0.1))),\n rarely(iaa.ContrastNormalization((0.75, 1.5))),\n occasionally(iaa.SigmoidContrast(gain=(3, 10), cutoff=(0.1, 0.2))),\n\n sometimes(iaa.Affine(\n scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n rotate=(-20, 20),\n shear=(-8, 8),\n order=[0, 1],\n cval=(0, 255),\n mode=ia.ALL\n )),\n \n iaa.SomeOf((0, 5),\n [\n\n # Blur each image with varying strength using\n # gaussian blur (sigma between 0 and 3.0),\n # average/uniform blur (kernel size between 2x2 and 7x7)\n # median blur (kernel size between 3x3 and 11x11).\n iaa.OneOf([\n iaa.GaussianBlur((0, 3.0)),\n iaa.AverageBlur(k=(2, 7)),\n iaa.MedianBlur(k=(3, 11)),\n ]),\n\n # Sharpen each image, overlay the result with the original\n # image using an alpha between 0 (no sharpening) and 1\n # (full sharpening effect).\n iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)),\n\n # Search in some images either for all edges or for\n # directed edges. These edges are then marked in a black\n # and white image and overlayed with the original image\n # using an alpha of 0 to 0.7.\n sometimes(iaa.OneOf([\n iaa.EdgeDetect(alpha=(0, 0.7)),\n iaa.DirectedEdgeDetect(\n alpha=(0, 0.7), direction=(0.0, 1.0)\n ),\n ])),\n\n # Add gaussian noise to some images.\n # In 50% of these cases, the noise is randomly sampled per\n # channel and pixel.\n # In the other 50% of all cases it is sampled once per\n # pixel (i.e. brightness change).\n iaa.AdditiveGaussianNoise(\n loc=0, scale=(0.0, 0.03*255), per_channel=0.5\n ),\n\n # Either drop randomly 1 to 10% of all pixels (i.e. set\n # them to black) or drop them on an image with 2-5% percent\n # of the original size, leading to large dropped\n # rectangles.\n iaa.OneOf([\n iaa.Dropout((0.01, 0.1), per_channel=0.5),\n iaa.CoarseDropout(\n (0.03, 0.15), size_percent=(0.01, 0.02),\n per_channel=0.2\n ),\n ]),\n\n # Invert each image's channel with 5% probability.\n # This sets each pixel value v to 255-v.\n iaa.Invert(0.05, per_channel=True), # invert color channels\n\n # Add a value of -10 to 10 to each pixel.\n iaa.Add((-10, 10), per_channel=0.5),\n\n # Change brightness of images (50-150% of original value).\n iaa.Multiply((0.5, 1.0), per_channel=0.5),\n\n # Improve or worsen the contrast of images.\n iaa.LinearContrast((0.5, 2.0), per_channel=0.5),\n\n # In some images move pixels locally around (with random\n # strengths).\n sometimes(\n iaa.ElasticTransformation(alpha=(0.5, 3.5), sigma=0.25)\n ),\n\n # In some images distort local areas with varying strength.\n sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.05)))\n ], random_order=True)\n\n ], random_order=True)\n \n elif aug_level == 'low':\n self.aug = iaa.Sequential([\n iaa.OneOf([\n iaa.Sometimes(0.5, iaa.AdditiveGaussianNoise(scale=(0.0, 0.1*255))),\n iaa.Sometimes(0.1, iaa.AdditiveGaussianNoise(scale=(0.0, 0.3*255)))\n ]),\n \n iaa.Sometimes(0.5, iaa.GammaContrast((0.5, 2.0))),\n iaa.Sometimes(0.5, iaa.imgcorruptlike.Brightness(severity=2)),\n iaa.Sometimes(0.5, iaa.Affine(\n rotate=(-20, 20),\n )),\n ], random_order=True)\n else:\n raise NotImplementedError\n \n def __call__(self, img):\n img = np.array(img)\n img = self.aug.augment_image(img)\n# img = np.ascontiguousarray(res) # this fixes \"some of the strides of a given numpy array are negative\"\n img = PIL.Image.fromarray(np.uint8(img)) # convert to pil image\n return img\n\ndef Common(image):\n\n image = cv2.equalizeHist(image)\n image = cv2.GaussianBlur(image, (3, 3), 0)\n\n return image\n\n\ndef Aug(image):\n img_aug = tfs.Compose([\n tfs.RandomAffine(degrees=(-15, 15), translate=(0.05, 0.05),\n scale=(0.95, 1.05), fillcolor=128)\n ])\n image = img_aug(image)\n\n return image\n\ndef GetTransforms(image, target=None, type='common'):\n # taget is not support now\n if target is not None:\n raise Exception(\n 'Target is not support now ! ')\n # get type\n if type.strip() == 'Common':\n image = Common(image)\n return image\n elif type.strip() == 'None':\n return image\n elif type.strip() == 'Aug':\n image = Aug(image)\n return image\n\n elif type.strip() == 'imgaug_Low':\n imgaugment = ImgAugTransform('low')\n \n compose = tfs.Compose([\n tfs.RandomApply([imgaugment], p=0.7),\n tfs.RandomHorizontalFlip(),\n# normalize,\n ])\n \n image = compose(image)\n\n return image\n \n\n elif type.strip() == 'imgaug_High':\n # look at their normalization\n # maybe replace their data loader with std torch one\n\n imgaugment = ImgAugTransform('high')\n\n compose = tfs.Compose([\n# transforms.RandomResizedCrop(224),\n# transforms.Resize((35,20)),\n tfs.RandomApply([imgaugment], p=0.7),\n tfs.RandomHorizontalFlip(),\n# normalize,\n ])\n \n image = compose(image)\n\n return image\n\n else:\n raise Exception(\n 'Unknown transforms_type : '.format(type))\n","sub_path":"data/imgaug.py","file_name":"imgaug.py","file_ext":"py","file_size_in_byte":7028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"191492692","text":"from sys import path\nfrom os.path import dirname as dir\nfrom shutil import rmtree\n\npath.append(dir(path[0]))\n\nfrom analizer import grammar\n\ndropAll = 0\nif dropAll:\n print(\"Eliminando registros\")\n rmtree(\"data\")\n\n\ns = \"\"\" \nUSE db1;\n/*\nCREATE TABLE demo7 (\n id INTEGER,\n name VARCHAR(20),\n username VARCHAR(20)\n);\n*/\n--SELECT de1.id, caca.name FROM demo5 de1, (SELECT de2.name FROM demo5 de2 WHERE de1.id = de2.id) AS caca;\n--SELECT d.* FROM demo5 d WHERE d.id > 1;\n\"\"\"\nresult = grammar.parse(s)\nprint(result)\n","sub_path":"parser/team29/analizer/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464532067","text":"\"\"\"\nConvert XPath selectors into CSS selectors\n\"\"\"\n\nimport re\n\n_sub_regexes = {\n \"tag\": \"([a-zA-Z][a-zA-Z0-9]{0,10}|\\*)\",\n \"attribute\": \"[.a-zA-Z_:][-\\w:.]*(\\(\\))?)\",\n \"value\": \"\\s*[\\w/:][-/\\w\\s,:;.]*\"\n}\n\n_validation_re = (\n \"(?P<node>\"\n \"(\"\n \"^id\\([\\\"\\']?(?P<idvalue>%(value)s)[\\\"\\']?\\)\"\n \"|\"\n \"(?P<nav>//?)(?P<tag>%(tag)s)\"\n \"(\\[(\"\n \"(?P<matched>(?P<mattr>@?%(attribute)s=[\\\"\\']\"\n \"(?P<mvalue>%(value)s))[\\\"\\']\"\n \"|\"\n \"(?P<contained>contains\\((?P<cattr>@?%(attribute)s,\\s*[\\\"\\']\"\n \"(?P<cvalue>%(value)s)[\\\"\\']\\))\"\n \")\\])?\"\n \"(\\[(?P<nth>\\d)\\])?\"\n \")\"\n \")\" % _sub_regexes\n)\n\nprog = re.compile(_validation_re)\n\n\nclass XpathException(Exception):\n pass\n\n\ndef convert_xpath_to_css(xpath):\n css = \"\"\n position = 0\n\n while position < len(xpath):\n node = prog.match(xpath[position:])\n if node is None:\n raise XpathException(\"Invalid or unsupported Xpath: %s\" % xpath)\n match = node.groupdict()\n\n if position != 0:\n nav = \" \" if match['nav'] == \"//\" else \" > \"\n else:\n nav = \"\"\n\n tag = \"\" if match['tag'] == \"*\" else match['tag'] or \"\"\n\n if match['idvalue']:\n attr = \"#%s\" % match['idvalue'].replace(\" \", \"#\")\n elif match['matched']:\n if match['mattr'] == \"@id\":\n attr = \"#%s\" % match['mvalue'].replace(\" \", \"#\")\n elif match['mattr'] == \"@class\":\n attr = \".%s\" % match['mvalue'].replace(\" \", \".\")\n elif match['mattr'] in [\"text()\", \".\"]:\n attr = \":contains(^%s$)\" % match['mvalue']\n elif match['mattr']:\n if match[\"mvalue\"].find(\" \") != -1:\n match[\"mvalue\"] = \"\\\"%s\\\"\" % match[\"mvalue\"]\n attr = \"[%s=%s]\" % (match['mattr'].replace(\"@\", \"\"),\n match['mvalue'])\n elif match['contained']:\n if match['cattr'].startswith(\"@\"):\n attr = \"[%s*=%s]\" % (match['cattr'].replace(\"@\", \"\"),\n match['cvalue'])\n elif match['cattr'] == \"text()\":\n attr = \":contains(%s)\" % match['cvalue']\n else:\n attr = \"\"\n\n if match['nth']:\n nth = \":nth-of-type(%s)\" % match['nth']\n else:\n nth = \"\"\n\n node_css = nav + tag + attr + nth\n css += node_css\n position += node.end()\n else:\n css = css.strip()\n return css\n","sub_path":"seleniumbase/fixtures/xpath_to_css.py","file_name":"xpath_to_css.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"358183674","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/4/12 11:35\n# @Author : ljf\nimport torch\nfrom torch import nn\n\nclass se_block(nn.Module):\n def __init__(self, in_planes, ratio=8):\n super(se_block, self).__init__()\n self.global_avg_pool = nn.AdaptiveAvgPool2d(output_size=[1, 1])\n self.fc1 = nn.Conv2d(in_planes, in_planes // ratio, 1)\n self.fc2 = nn.Conv2d(in_planes // ratio, in_planes, 1)\n self.sigmoid = nn.Sigmoid()\n self.relu = nn.ReLU()\n\n def forward(self, x):\n avg_pool = self.global_avg_pool(x)\n avg_pool = self.fc1(avg_pool)\n avg_pool = self.relu(avg_pool)\n avg_pool = self.fc2(avg_pool)\n\n weight = self.sigmoid(avg_pool)\n channel_feature = weight * x\n\n return channel_feature\nclass cbam_block(nn.Module):\n def __init__(self, in_planes, kernel_size,ratio=8):\n super(cbam_block, self).__init__()\n self.channel_attention = channel_attention(in_planes,ratio)\n self.spatial_attention = spatial_attention(kernel_size)\n\n def forward(self, x):\n out = self.channel_attention(x)\n out = self.spatial_attention(out)\n return out\n\n\nclass channel_attention(nn.Module):\n def __init__(self, in_planes, ratio=8):\n super(channel_attention, self).__init__()\n self.global_avg_pool = nn.AdaptiveAvgPool2d(output_size=[1,1])\n self.global_max_pool = nn.AdaptiveMaxPool2d(output_size=[1,1])\n self.fc1 = nn.Conv2d(in_planes,in_planes//ratio,1)\n self.fc2 = nn.Conv2d(in_planes//ratio,in_planes,1)\n self.sigmoid = nn.Sigmoid()\n self.relu = nn.ReLU()\n\n def forward(self, x):\n avg_pool = self.global_avg_pool(x)\n avg_pool = self.fc1(avg_pool)\n avg_pool = self.relu(avg_pool)\n avg_pool = self.fc2(avg_pool)\n\n max_pool = self.global_max_pool(x)\n max_pool = self.fc1(max_pool)\n max_pool = self.relu(max_pool)\n max_pool = self.fc2(max_pool)\n\n weight = self.sigmoid(avg_pool+max_pool)\n channel_feature = weight*x\n\n return channel_feature\n\nclass spatial_attention(nn.Module):\n def __init__(self,kernel_size = 7):\n super(spatial_attention, self).__init__()\n assert kernel_size in (3,7) ,\"kernel_size must be 3 or 7\"\n padding = 3 if kernel_size == 7 else 1\n\n self.conv = nn.Conv2d(2,1,kernel_size=kernel_size,padding=padding,bias=False)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n mean_out = torch.mean(x,dim=1,keepdim=True)\n max_out,_ = torch.max(x,dim=1,keepdim=True)\n weight = torch.cat([mean_out,max_out],dim=1)\n weight = self.conv(weight)\n weight = self.sigmoid(weight)\n spatial_feature = weight*x\n return spatial_feature\n\n\n\nclass attention_module(nn.Module):\n def __init__(self, block_name, in_planes, is_residual,kernel_size=7,ratio=8):\n r\"\"\"\n :param block_name(str): \"cbam_block\" or \"se_block\"\n :param is_residual(bool): True or False\n \"\"\"\n super(attention_module, self).__init__()\n if block_name == \"se_block\":\n block = se_block(in_planes,ratio)\n elif block_name == \"cbam_block\":\n block = cbam_block(in_planes,kernel_size,ratio)\n else:\n raise Exception(\n \"'{}' is not a supported attention module!\".format(block_name))\n self.is_residual = is_residual\n self.block = block\n\n def forward(self, x):\n residual = x\n out = self.block(x)\n if self.is_residual:\n out += residual\n return out\n\nif __name__ == \"__main__\":\n input = torch.randn(size=[2,64,32,32])\n model = attention_module(block_name=\"cbam_block\",is_residual=True,in_planes=64)\n output = model(input)\n print(output.size())","sub_path":"ImageClassification/pytorch-classification/models/attention_module.py","file_name":"attention_module.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"562088887","text":"#!/usr/bin/env python3\n# -+-coding: utf-8 -+-\n\n#--------------------------------------------\n# Authors: Frank Boers <f.boers@fz-juelich.de>\n#\n#--------------------------------------------\n# Date: 05.09.19\n#--------------------------------------------\n# License: BSD (3-clause)\n#--------------------------------------------\n# Updates\n#--------------------------------------------\n\nimport numpy as np\nimport wx\nimport sys,logging\n\nfrom jumeg.base import jumeg_logger\nlogger = logging.getLogger('JuMEG')\n\n\nfrom jumeg.gui.wxlib.utils.jumeg_gui_wxlib_utils_controls import JuMEG_wxControlGrid\nfrom tsv.wxutils.jumeg_tsv_wxutils import DLGButtonPanel\n\n__version__=\"2019-09-05-001\"\n\nLEA = wx.ALIGN_LEFT | wx.EXPAND | wx.ALL\n\nclass PopupColourTable(wx.PopupTransientWindow):\n def __init__(self, parent,**kwargs):\n super().__init__(parent,wx.NO_BORDER)\n self._wx_init(**kwargs)\n self._ApplyLayout()\n\n def _wx_init(self,**kwargs):\n self.SetBackgroundColour(kwargs.get(\"bg\",\"GREY60\"))\n w = kwargs.get(\"w\",24)\n self._C = kwargs.get(\"colours\")\n self._caller = kwargs.get(\"caller\")\n self._callback = kwargs.get(\"callback\")\n self._title = kwargs.get(\"title\",\"JuMEG Select Colour\")\n self._colour_text = None\n \n bmp = wx.Bitmap()\n ctrls = []\n \n for i in range( self._C.n_colours ):\n #--- select colour\n ctrls.append( [\"BTBMP\",self._C.labels[i],bmp,(w,w),wx.NO_BORDER|wx.BU_NOTEXT,self._C.colours[i] ,self._C.labels[i],self.ClickOnCtrls] )\n \n #--- calc cols for grid\n n_cols,rest = divmod( len(ctrls),4)\n if rest: n_cols += 1\n \n self._pnl = JuMEG_wxControlGrid(self,label= self._title,control_list=ctrls,cols=n_cols,set_ctrl_prefix=False)\n \n \n def ClickOnCtrls(self,evt):\n obj = evt.GetEventObject()\n \n try:\n if obj.GetToolTip():\n self._colour_text = obj.GetToolTipText()\n #--- call the caller-function in parent\n if self._colour_text:\n self._callback( self._caller,self._colour_text )\n #--- close\n self.Dismiss() # close it\n except:\n logger.exception(\"---> ERROR can not set ToolTip\".format(self._colour_text))\n \n def _ApplyLayout(self):\n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add(self._pnl,1,LEA,2)\n \n self.SetAutoLayout(True)\n self.SetSizer(vbox)\n self.Fit()\n self.Layout()\n \n\nclass GroupDLG(wx.Dialog):\n \"\"\"\n \n Example:\n ---------\n input group dict\n \n labels = ['grad','mag','eeg','stim','eog','emg','ecg','ref_meg']\n grp={\n 'mag': {\"selected\":True,\"colour\":\"RED\", \"prescale\":200,\"unit\":\"fT\"},\n 'grad': {\"selected\":True,\"colour\":\"BLUE\", \"prescale\":200,\"unit\":\"fT\"},\n 'ref_meg':{\"selected\":True,\"colour\":\"GREEN\", \"prescale\":2, \"unit\":\"pT\"},\n 'eeg': {\"selected\":True,\"colour\":\"BLUE\", \"prescale\":1, \"unit\":\"uV\"},\n 'eog': {\"selected\":True,\"colour\":\"PURPLE\", \"prescale\":100,\"unit\":\"uV\"},\n 'emg': {\"selected\":True,\"colour\":\"DARKORANGE\",\"prescale\":100,\"unit\":\"uV\"},\n 'ecg': {\"selected\":True,\"colour\":\"DARKGREEN\", \"prescale\":100,\"unit\":\"mV\"},\n 'stim': {\"selected\":True,\"colour\":\"CYAN\", \"prescale\":1, \"unit\":\"bits\"}\n }\n \n \n \"\"\"\n @property\n def Group(self): return self._GRP\n \n def __init__(self,parent,**kwargs):\n style=wx.CLOSE_BOX|wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX #|wx.RESIZE_BORDER\n super().__init__(parent,title=\"JuMEG Group Settings\",style=style)\n self._init(**kwargs)\n\n def _init(self,**kwargs):\n self._GRP = kwargs.get(\"grp\")\n \n self._wx_init(**kwargs)\n self._wx_button_box()\n self._ApplyLayout()\n \n def _wx_button_box(self):\n \"\"\"\n show DLG cancel apply bts\n :return:\n \"\"\"\n self._pnl_button_box = DLGButtonPanel(self,style=wx.SUNKEN_BORDER)\n \n def _wx_init(self,**kwargs):\n w = kwargs.get(\"w\",24)\n self.SetBackgroundColour(kwargs.get(\"bg\",\"GREY90\"))\n # self._bt=wx.Button(self,-1,\"TEST\")\n \n bmp = wx.Bitmap()\n ctrls = [ [\"STXT\",\"Groups\",\"Groups\"], [\"STXT\",\"Colour\",\"Colour\"], [\"STXT\",\"Scale\",\"Scale\"],[ \"STXT\",\"Unit\",\"Unit\"]]\n n_cols= len(ctrls)\n \n for grp in self._GRP.labels:\n g = grp.upper()\n \n #--- ckbutton select group\n ctrls.append( [\"CK\", g+\".CKBOX\",g,self._GRP.GetSelected(grp),'de/select group',self.ClickOnCtrls] )\n #--- select colour\n label = self._GRP.GetColour(grp)\n ctrls.append( [\"BTBMP\",g+\".colour\",bmp,(w,w),wx.NO_BORDER|wx.BU_NOTEXT,label,label +\"\\nclick to change\",self.ClickOnCtrls] )\n #--- grp prescale\n ctrls.append([\"COMBO\",g.upper()+\".PRESCALE\",str(self._GRP.GetPreScale(grp)),self._GRP.Unit.prescales,'set scaling',self.ClickOnCtrls])\n #--- grp unit wit prefix e.g. m,u,n,p,f,a => mT,uT,...\n self._GRP.Unit.unit = self._GRP.GetUnit(grp) # update Unit CLS\n ctrls.append([\"COMBO\",g+\".UNIT\",self._GRP.Unit.unit,self._GRP.Unit.GetUnits(),'set scaling unit',self.ClickOnCtrls])\n \n self._pnl_groups = JuMEG_wxControlGrid(self,label=\"Group Parameter\",control_list=ctrls,cols=n_cols,set_ctrl_prefix=False,AddGrowableCol=[2,3])\n \n #self._bt.Bind(wx.EVT_BUTTON,self.ClickOnButton)\n \n def _popup_colour_table(self,obj,grp):\n PCT = PopupColourTable(self,title=\"Group: \"+obj.GetName().split(\".\")[0],caller=obj,colours=self._GRP.Colour,callback=self.update_colour)\n pos = wx.GetMousePosition()\n PCT.Position(pos,(0,0))\n PCT.Popup()\n \n def update_colour(self,obj,label):\n \"\"\"\n sets the group colour\n this is the callback executed from PopupColourTable\n may use wx.EVENTS or pubsub\n :param obj: colour bitmapbutton\n :param label:colour label: RED,GREEN has to be in colour-object label list ...\n :return:\n \"\"\"\n grp,key = obj.GetName().lower().split(\".\")\n c = self._GRP.Colour.label2colour(label)\n obj.SetBackgroundColour( c )\n obj.SetToolTipString( label+\"\\nclick to change\")\n self._GRP.SetColour( grp, label )\n \n # logger.info(\"set group: {} colour: {}\".format(grp,self._GRP.GetGroup(grp) ))\n \n def ClickOnCtrls(self,evt):\n obj = evt.GetEventObject()\n grp,key = obj.GetName().lower().split(\".\")\n \n if key == \"colour\":\n self._popup_colour_table(obj,grp)\n return\n \n v = obj.GetValue()\n if key == \"selected\":\n self._GRP.SetSelected(grp,v )\n elif key == \"prescale\":\n self._GRP.SetPreScale(grp,v)\n elif key == \"unit\":\n self._GRP.SetUnit(grp,v)\n \n def ClickOnButton(self,evt):\n pass\n \n def _ApplyLayout(self):\n vbox = wx.BoxSizer(wx.VERTICAL)\n #vbox.Add(self._bt,0,LEA,2)\n vbox.Add(self._pnl_groups,1,LEA,2)\n \n #--- fix size to show combos of scale and unit\n stl = wx.StaticLine(self,size=(350,2) )\n stl.SetBackgroundColour(\"GREY85\")\n vbox.Add(stl,0,LEA,1)\n vbox.Add(self._pnl_button_box,0,LEA,2)\n \n self.SetAutoLayout(True)\n self.SetSizer(vbox)\n self.Fit()\n self.Layout()\n\nclass ChannelDLG(GroupDLG):\n def __init__(self,**kwargs):\n super().__init__(**kwargs)\n \n \nclass MainFrame(wx.Frame):\n \n def __init__(self, parent, title,**kwargs):\n super().__init__(parent, title = title)\n self._init(**kwargs)\n self._ApplyLayout()\n \n def _init(self,**kwargs):\n self.test = wx.Panel(self)\n self.show_group_dialog(**kwargs)\n self.Close()\n \n def _ApplyLayout(self):\n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add(self.test,1,LEA,4)\n self.SetSizer(vbox)\n self.SetAutoLayout(True)\n self.Fit()\n self.Show(True)\n \n def show_group_dialog(self,**kwargs):\n dlg = GroupDLG(self,**kwargs)\n out = dlg.ShowModal()\n \n if out == wx.ID_APPLY:\n grp = dlg.Group.GetGroup(None)\n for g in grp.keys():\n logger.info(\"OUTPUT: {} => {} \\n {}\".format(g,dlg.Group.GetScaling(g),grp.get(g)))\n \n dlg.Destroy()\n\n\n\nif __name__ == \"__main__\":\n opt=None\n\n #--- Testing DEBUG\n from tsv.utils.jumeg_tsv_utils_io_data import JuMEG_TSV_Utils_IO_Data\n from tsv.plot.jumeg_tsv_plot2d_data_options import GroupOptions,JuMEG_TSV_PLOT2D_DATA_OPTIONS\n\n \n verbose = True\n path = \"data\"\n path = \"~/MEGBoers/programs/JuMEG/jumeg-py/jumeg-py-git-fboers-2019-08-21/projects/JuMEGTSV/data\"\n fname = '200098_leda_test_10_raw.fif'\n raw = None\n\n jumeg_logger.setup_script_logging(name=\"JuMEG\",opt=opt,logger=logger)\n \n IO = JuMEG_TSV_Utils_IO_Data()\n raw,bads = IO.load_data(raw,fname,path)\n \n DataOpt = JuMEG_TSV_PLOT2D_DATA_OPTIONS()\n DataOpt.update(raw=raw)\n \n #--- ToDo use only groups from raw\n GRP = GroupOptions()\n \n app = wx.App()\n MainFrame(None,'JuMEG demo',grp=GRP)\n app.MainLoop()\n","sub_path":"jumeg/gui/tsv/wxutils/jumeg_tsv_wxutils_group_settings_dlg.py","file_name":"jumeg_tsv_wxutils_group_settings_dlg.py","file_ext":"py","file_size_in_byte":9494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526500270","text":"\"\"\"add ondelete set null to board-user relationship\n\nRevision ID: c82371f555c8\nRevises: 4b5eb594c3e9\nCreate Date: 2019-03-05 10:43:10.321395\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'c82371f555c8'\ndown_revision = '4b5eb594c3e9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('board', 'writer_id',\n existing_type=mysql.INTEGER(display_width=11),\n nullable=True)\n op.drop_constraint('board_ibfk_1', 'board', type_='foreignkey')\n op.create_foreign_key(None, 'board', 'user', ['writer_id'], ['id'], ondelete='SET NULL')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'board', type_='foreignkey')\n op.create_foreign_key('board_ibfk_1', 'board', 'user', ['writer_id'], ['id'])\n op.alter_column('board', 'writer_id',\n existing_type=mysql.INTEGER(display_width=11),\n nullable=False)\n # ### end Alembic commands ###\n","sub_path":"alembic/versions/c82371f555c8_add_ondelete_set_null_to_board_user_.py","file_name":"c82371f555c8_add_ondelete_set_null_to_board_user_.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"214382147","text":"from fastapi import Depends\n\nfrom rubrix.server.datasets.service import DatasetsService\nfrom rubrix.server.tasks.commons.dao.dao import DatasetRecordsDAO, dataset_records_dao\n\n\nclass TaskService:\n\n _INSTANCE = None\n\n def __init__(self, datasets: DatasetsService, dao: DatasetRecordsDAO):\n self.__datasets__ = datasets\n self.__dao__ = dao\n\n @classmethod\n def get_instance(\n cls,\n datasets: DatasetsService = Depends(DatasetsService.get_instance),\n dao: DatasetRecordsDAO = Depends(dataset_records_dao),\n ) -> \"TaskService\":\n if not cls._INSTANCE:\n cls._INSTANCE = cls(datasets, dao=dao)\n return cls._INSTANCE\n","sub_path":"src/rubrix/server/tasks/commons/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"15200285","text":"import psycopg2\n\nconn = psycopg2.connect(\"postgresql://movie_rental:2h6WBFyGVUv88qgJ@localhost/movies\")\ncur = conn.cursor()\n\nwhile True:\n print(\"Please enter inventory ID\")\n inventory_id = int(input())\n print(\"Please enter customer ID\")\n customer_id = int(input())\n print(\"Please enter staff ID\")\n staff_id = int(input())\n cur.execute(\"\"\"\n INSERT INTO rental (rental_date, inventory_id, customer_id, return_date, staff_id)\n VALUES (NOW(), %s, %s, NOW() + INTERVAL '7 DAYS', %s)\n RETURNING rental_id;\n \"\"\", (inventory_id, customer_id, staff_id));\n rental_id = cur.fetchone()[0]\n print(f\"Rental submitted: ID {rental_id}\")\n conn.commit()\n\ncur.close()\nconn.close()\n","sub_path":"rental/rental.py","file_name":"rental.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"311354724","text":"import os\nfrom flask import current_app as app\n\n\ndef get_chunk(podcast_file_name, byte1=None, byte2=None):\n full_path = os.path.abspath(\n os.path.join(app.root_path, \"static\", \"podcasts\", podcast_file_name)\n )\n file_size = os.stat(full_path).st_size\n start = 0\n length = 102400\n\n if byte1 < file_size:\n start = byte1\n if byte2:\n length = byte2 + 1 - byte1\n else:\n length = file_size - start\n\n with open(full_path, \"rb\") as f:\n f.seek(start)\n chunk = f.read(length)\n return chunk, start, length, file_size\n","sub_path":"app/podcasts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80881455","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy.fftpack import fft, ifft\r\n\r\n\r\nE1, E2, w, sigma, nc = 0.08, 0.046, 0.057, 30*41.34, 15\r\ntl, tr = -3000, 3000\r\ntime = np.linspace(tl, tr, 10001)\r\nnt = len(time)\r\n\r\ndef E_800x(theta,t):\r\n return E1*np.cos(theta)*np.exp(-2*np.log(2)*(t/sigma)**2)*np.cos(w*t)\r\ndef E_800y(theta,t):\r\n return E1*np.sin(theta)*np.exp(-2*np.log(2)*(t/sigma)**2)*np.cos(w*t)\r\ndef E_400(t,tau):\r\n return E2*np.exp(-2*np.log(2)*((t-tau)/sigma)**2)*np.cos(2*w*(t-tau))\r\n\r\n\r\ndef W(E):\r\n Ei, Eh = 15.6, 13.6\r\n W = 4 * (Ei / Eh) ** 2.5 * (1 / abs(E)) * np.exp(-2 / 3 * (Ei / Eh) ** 1.5 * (1 / abs(E)))\r\n return W\r\n\r\n\r\ndef Ne(E,t):\r\n Ng = 2.4 * 10 ** 19 * (0.5292 * 10 ** (-8)) ** 3\r\n Ne = np.zeros(len(t))\r\n Ne[0] = Ng * W(E[0])\r\n # for i in range(len(time)-1):\r\n\r\n for i in range(len(t) - 1):\r\n Ne[i + 1] = Ne[i] + (Ng - Ne[i]) * W(E[i + 1]) * (t[1] - t[0])\r\n return Ne\r\n\r\n\r\ndef Fourier(dJ_dt,t):\r\n num = 10 * len(t)\r\n dJ_dt_N = np.pad(dJ_dt, (num, num), 'constant')\r\n Four_fft = fft(dJ_dt_N)\r\n return Four_fft\r\n\r\n\r\n\r\nplt.figure(figsize=(11,6))\r\n\r\nplt.ion()\r\nspace = np.linspace(0,2*np.pi,100)\r\nfor theta in space:\r\n E = E_800x(theta,time)+E_400(time,0)\r\n dJ_dt = Ne(E,time)*E\r\n plt.xlim(0,8)\r\n plt.ylim(0,7e-7)\r\n plt.plot(np.linspace(0,3000,210021),abs(Fourier(dJ_dt,time)))\r\n plt.pause(0.01)\r\n plt.clf()\r\nplt.ioff()\r\n# THz_new = abs(Fourier(dJ_dt,time))\r\n# THz_new[560:209460] = 0\r\n\r\n\r\n\r\n\r\n# plt.ion()\r\n# space = np.linspace(0,1002*np.pi,100)\r\n# for theta in space:\r\n# plt.ylim(-0.1,0.1)\r\n# plt.plot(time,E_800x(0,time))\r\n# plt.plot(time,E_400(time,theta))\r\n# plt.pause(0.01)\r\n# plt.clf()\r\n# plt.ioff()\r\nplt.show()\r\n\r\n\r\n","sub_path":"PC/THz intensity of relative phase.py","file_name":"THz intensity of relative phase.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83992789","text":"#!/usr/bin/python3\n\nimport pytest\n\ndef test_empty(USDC, WETH, accounts, SwapRouter, CellarPoolShareContract):\n SwapRouter.exactOutputSingle([WETH, USDC, 3000, accounts[2], 2 ** 256 - 1, 10000 * 10 ** 6, 5 * 10 ** 18, 0], {\"from\": accounts[2], \"value\": 5 * 10 ** 18})\n USDC.approve(CellarPoolShareContract, 10000 * 10 ** 6, {\"from\": accounts[2]})\n USDC_amount = 10000 * 10 ** 6\n ETH_amount = 5 * 10 ** 18\n cellarAddParams = [USDC_amount, ETH_amount, 0, 0, accounts[2], 2 ** 256 - 1]\n CellarPoolShareContract.addLiquidityEthForUniV3(cellarAddParams, {\"from\": accounts[2], \"value\": 5 * 10 ** 18})\n CellarPoolShareContract.setValidator(accounts[2], True, {\"from\": accounts[0]})\n for i in range(3):\n SwapRouter.exactOutputSingle([WETH, USDC, 3000, accounts[3], 2 ** 256 - 1, 10000 * 10 ** 6, 5 * 10 ** 18, 0], {\"from\": accounts[3], \"value\": 5 * 10 ** 18})\n USDC.approve(SwapRouter, 100000 * 10 ** 6, {\"from\": accounts[3]})\n SwapRouter.exactInputSingle([USDC, WETH, 3000, accounts[3], 2 ** 256 - 1, 10000 * 10 ** 6, 5 * 10 ** 17, 0], {\"from\": accounts[3]})\n WETH.withdraw(WETH.balanceOf(accounts[3]), {\"from\": accounts[3]})\n tx = CellarPoolShareContract.reinvest({\"from\": accounts[2]})\n bal = CellarPoolShareContract.balanceOf(accounts[2])\n cellarRemoveParams = [bal, 0, 0, accounts[2], 2 ** 256 - 1]\n CellarPoolShareContract.removeLiquidityFromUniV3(cellarRemoveParams, {\"from\": accounts[2]})\n assert CellarPoolShareContract.balanceOf(accounts[2]) == 0\n\ndef test_add_liquidity_ETH(USDC, WETH, accounts, SwapRouter, CellarPoolShareContract):\n SwapRouter.exactOutputSingle([WETH, USDC, 3000, accounts[0], 2 ** 256 - 1, 6000 * 10 ** 6, 6 * 10 ** 18, 0], {\"from\": accounts[0], \"value\": 6 * 10 ** 18})\n SwapRouter.exactOutputSingle([WETH, USDC, 3000, accounts[1], 2 ** 256 - 1, 6000 * 10 ** 6, 6 * 10 ** 18, 0], {\"from\": accounts[1], \"value\": 6 * 10 ** 18})\n USDC.approve(CellarPoolShareContract, 3000 * 10 ** 6, {\"from\": accounts[0]})\n USDC.approve(CellarPoolShareContract, 3000 * 10 ** 6, {\"from\": accounts[1]})\n USDC_amount = 1000 * 10 ** 6\n ETH_amount = 1 * 10 ** 18\n cellarAddParams = [USDC_amount, ETH_amount, 0, 0, accounts[0], 2 ** 256 - 1]\n CellarPoolShareContract.addLiquidityEthForUniV3(cellarAddParams, {\"from\": accounts[0], \"value\": 1 * 10 ** 18})\n CellarPoolShareContract.addLiquidityEthForUniV3(cellarAddParams, {\"from\": accounts[0], \"value\": 1 * 10 ** 18})\n CellarPoolShareContract.addLiquidityEthForUniV3(cellarAddParams, {\"from\": accounts[0], \"value\": 1 * 10 ** 18})\n cellarAddParams = [USDC_amount, ETH_amount, 0, 0, accounts[1], 2 ** 256 - 1]\n CellarPoolShareContract.addLiquidityEthForUniV3(cellarAddParams, {\"from\": accounts[1], \"value\": 1 * 10 ** 18})\n CellarPoolShareContract.addLiquidityEthForUniV3(cellarAddParams, {\"from\": accounts[1], \"value\": 1 * 10 ** 18})\n CellarPoolShareContract.addLiquidityEthForUniV3(cellarAddParams, {\"from\": accounts[1], \"value\": 1 * 10 ** 18})\n assert CellarPoolShareContract.balanceOf(accounts[0]) == CellarPoolShareContract.balanceOf(accounts[1])\n\ndef test_reinvest(USDC, WETH, accounts, SwapRouter, CellarPoolShareContract, Contract):\n bal = CellarPoolShareContract.balanceOf(accounts[1])\n cellarRemoveParams = [bal // 3, 0, 0, accounts[1], 2 ** 256 - 1]\n USDC_balance = USDC.balanceOf(accounts[1])\n WETH_balance = WETH.balanceOf(accounts[1])\n CellarPoolShareContract.removeLiquidityFromUniV3(cellarRemoveParams, {\"from\": accounts[1]})\n USDC_diff = USDC.balanceOf(accounts[1]) - USDC_balance\n WETH_diff = WETH.balanceOf(accounts[1]) - WETH_balance\n USDC_balance = USDC.balanceOf(accounts[1])\n WETH_balance = WETH.balanceOf(accounts[1])\n SwapRouter.exactOutputSingle([WETH, USDC, 3000, accounts[2], 2 ** 256 - 1, 10000 * 10 ** 6, 10 * 10 ** 18, 0], {\"from\": accounts[2], \"value\": 10 * 10 ** 18})\n USDC.approve(SwapRouter, 2 ** 256 - 1, {\"from\": accounts[2]})\n SwapRouter.exactInputSingle([USDC, WETH, 3000, accounts[2], 2 ** 256 - 1, 10000 * 10 ** 6, 1 * 10 ** 18, 0], {\"from\": accounts[2]})\n CellarPoolShareContract.setValidator(accounts[1], True, {\"from\": accounts[0]})\n USDC_balance0 = USDC.balanceOf(accounts[0])\n WETH_balance0 = WETH.balanceOf(accounts[0])\n CellarPoolShareContract.reinvest({\"from\": accounts[1]})\n USDC_balance0 = USDC.balanceOf(accounts[0]) - USDC_balance0\n WETH_balance0 = WETH.balanceOf(accounts[0]) - WETH_balance0\n assert USDC_balance0 > 0 or WETH_balance0 > 0\n CellarPoolShareContract.removeLiquidityFromUniV3(cellarRemoveParams, {\"from\": accounts[1]})\n USDC_diff_2 = USDC.balanceOf(accounts[1]) - USDC_balance\n WETH_diff_2 = WETH.balanceOf(accounts[1]) - WETH_balance\n assert USDC_diff_2 > USDC_diff or WETH_diff_2 > WETH_diff","sub_path":"tests/test_03_reinvest.py","file_name":"test_03_reinvest.py","file_ext":"py","file_size_in_byte":4783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"547072837","text":"# -*- coding: utf-8; -*-\nfrom django.db import models\nfrom django.test import TestCase\nimport datetime\nfrom decimal import Decimal\nfrom django_any.contrib.default import any_model_with_defaults\nfrom django.db.models.fields import NOT_PROVIDED\nfrom django.core.files.base import ContentFile\nfrom django_any.tests.model_creation_simple import SimpleModel\n\n\nclass SimpleModelWithDefaults(models.Model):\n big_integer_field = models.BigIntegerField(default=8223372036854775807)\n char_field = models.CharField(max_length=5, default='USSR')\n boolean_field = models.BooleanField(default=True)\n comma_separated_field = models.CommaSeparatedIntegerField(max_length=50, default='1,2,3')\n date_field = models.DateField(default=datetime.date(2010, 12, 10))\n datetime_field = models.DateTimeField(datetime.datetime.now)\n decimal_field = models.DecimalField(decimal_places=2, max_digits=10, default=Decimal('0.5'))\n email_field = models.EmailField(default='admin@dev.null')\n float_field = models.FloatField(default=0.7)\n integer_field = models.IntegerField(default=42)\n ip_field = models.IPAddressField(default='127.0.0.1')\n null_boolead_field = models.NullBooleanField(default=None)\n positive_integer_field = models.PositiveIntegerField(default=4)\n small_integer = models.PositiveSmallIntegerField(default=1)\n slug_field = models.SlugField(default='any_model_default')\n text_field = models.TextField(default='Lorem ipsum')\n time_field = models.TimeField(default=datetime.time(hour=11, minute=14))\n url_field = models.URLField(verify_exists=False, default='http://yandex.ru')\n\n class Meta:\n app_label = 'django_any'\n\n\nclass AnyModelWithDefaults(TestCase):\n sample_args = dict(\n big_integer_field = 1,\n char_field = 'USA',\n boolean_field = False,\n comma_separated_field = '5,6,7',\n date_field = datetime.date(2012, 12, 10),\n datetime_field = datetime.datetime(1985, 12, 10),\n decimal_field = Decimal('1.5'),\n email_field = 'root@dev.null',\n float_field = 1.5,\n integer_field = 777,\n ip_field = '1.2.3.4',\n null_boolead_field = True,\n positive_integer_field = 777,\n small_integer = 12,\n slug_field = 'some_model',\n text_field = 'Here I come',\n time_field = datetime.time(hour=9, minute=10, second=11),\n url_field = 'http://google.com',\n )\n\n def test_default_provided_called_with_no_args(self):\n result = any_model_with_defaults(SimpleModelWithDefaults)\n\n self.assertEqual(type(result), SimpleModelWithDefaults)\n self.assertEqual(len(result._meta.fields), len(SimpleModelWithDefaults._meta.local_fields))\n\n for field, original_field in zip(result._meta.fields, SimpleModelWithDefaults._meta.local_fields):\n value = getattr(result, field.name)\n if field.name != 'null_boolead_field':\n self.assertTrue(value is not None, \"%s is uninitialized\" % field.name)\n self.assertTrue(isinstance(field, original_field.__class__), \"%s has correct field type\" % field.name)\n if original_field.default is not NOT_PROVIDED:\n self.assertEqual(original_field.default, value)\n\n def test_default_provided_called_with_args(self):\n result = any_model_with_defaults(SimpleModelWithDefaults, **self.sample_args)\n\n for field, original_field in zip(result._meta.fields, SimpleModelWithDefaults._meta.local_fields):\n self.assertNotEqual(original_field.default, getattr(result, field.name))\n\n","sub_path":"django_any/tests/contrib/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"552583477","text":"# from flask import Flask\n\n# app = Flask(__name__)\n\n# PORT = 4390\n\n\n# @app.route('/')\n# def homepage():\n# return \"Howdy hacker!!!\"\n\n\n# if __name__ == '__main__':\n# app.run(debug=True, port=PORT)\n\n\n#!/usr/bin/env python\n# encoding: utf-8\nimport os\nfrom bottle import run, post\n\nfrom pdpyras import APISession\nimport requests\nimport pypd\nfrom datetime import datetime, timedelta\nimport json\nfrom urllib import parse as urlparse\n\n\n@post('/hello')\n# def hello():\n# return 'Hello World!'\ndef slack(event):\n message_from_slack = dict(urlparse.parse_qsl(event[\"body\"]))\n response_url = message_from_slack[\"response_url\"]\n user_email = message_from_slack[\"text\"]\n message_for_slack = \"*Request body _after_ decoding:*\\n\" + user_email\n\n response_json = {\n 'attachments': [\n {\n 'text': message_for_slack,\n 'callback_id': \"slashcommand\",\n 'actions': [\n {\n 'name': 'slashcommand_bu',\n 'text': 'A Button',\n 'type': \"button\",\n 'value': 0\n }\n ]\n }\n ]\n }\n\n return {\n 'statusCode': 200,\n 'body': json.dumps(response_json)\n }\n\n\nif __name__ == '__main__':\n port = os.environ.get('PORT', 5000)\n run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"478645666","text":"def main():\n \n words = str(input(\"Input Sentence:\")).split() # retrieves the senetence from the user\n pigLatin(words) # calls the pig latin converter function\n\n# this function converts a sentence to pig latin\ndef pigLatin(words):\n \n # this loop seperates the first letter in the word from the rest and rearranges it adding AY to the end\n for word in words:\n firstLetter = word[0]\n secondPart = word[1:]\n \n print(secondPart.upper() + firstLetter.upper() + \"AY\", end = \" \") # prints out the sentence in pig latin\n print() # prints space\n\n# function call to main\nmain()\n","sub_path":"week7/hw07_4.py","file_name":"hw07_4.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"125666426","text":"import os\nfrom qiskit.converters import circuit_to_dag\nimport numpy as np\n\ndef check_valid(circuit):\n '''\n If the input circuit is not fully connected, it does not need CutQC to be split into smaller circuits.\n CutQC hence only cuts a circuit if it is fully connected.\n Furthermore, CutQC only supports 2-qubit gates.\n '''\n if circuit.num_unitary_factors()!=1:\n raise ValueError('Input circuit is not fully connected thus does not need cutting. Number of unitary factors = %d'%circuit.num_unitary_factors())\n if circuit.num_clbits>0:\n raise ValueError('Please remove classical bits from the circuit before cutting')\n dag = circuit_to_dag(circuit)\n for op_node in dag.topological_op_nodes():\n if len(op_node.qargs)>2:\n raise ValueError('CutQC currently does not support >2-qubit gates')\n if op_node.op.name=='barrier':\n raise ValueError('Please remove barriers from the circuit before cutting')\n\ndef read_prob_from_txt(filename):\n if os.path.isfile(filename):\n txt_file = open(filename,'r')\n lines = txt_file.readlines()\n assert len(lines)==1\n prob = lines[0].rstrip().split(' ')\n prob = np.array(prob,dtype=float)\n else:\n prob = np.array([])\n return prob","sub_path":"cutqc/helper_fun.py","file_name":"helper_fun.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"76289764","text":"from functools import cmp_to_key\n\nimport random\nimport os.path\nimport json\n\n##----------------------------------------------------------------##\nfrom gii.core import app, signals, slot, printTraceBack, RemoteCommand\nfrom gii.core.model import *\nfrom gii.core.AssetUtils import *\nfrom gii.core.mime import *\n\nfrom gii.qt import QtEditorModule\n\nfrom gii.qt.IconCache import getIcon\nfrom gii.qt.dialogs import alertMessage, requestConfirm, requestString\nfrom gii.qt.controls.GenericTreeWidget import GenericTreeWidget, GenericTreeFilter\nfrom gii.qt.controls.SimpleTitleBar import SimpleTitleBar\nfrom gii.qt.helpers import makeBrush, makeFont, restrainWidgetToScreen\n\nfrom gii.moai.MOAIRuntime import MOAILuaDelegate\nfrom gii.SceneEditor import SceneEditorModule\n\nfrom gii.SearchView import requestSearchView, registerSearchEnumerator\n\n##----------------------------------------------------------------##\nfrom qtpy import QtCore, QtWidgets, QtGui, uic\nfrom qtpy.QtCore import Qt, QObject\nfrom qtpy.QtGui import QBrush, QColor, QPen, QIcon, QPalette\nfrom qtpy.QtWidgets import QApplication, QStyle\nfrom qtpy.QtCore import QEventLoop, QEvent\n\n##----------------------------------------------------------------##\nfrom mock import _MOCK, _MOCK_EDIT, isMockInstance, MOCKPreviewCanvas\n##----------------------------------------------------------------##\n\n\ndef getModulePath( path ):\n\timport os.path\n\treturn os.path.dirname( __file__ ) + '/' + path\n\n\n_brushAnimatable = makeBrush( color = '#5f3d26' )\n_fontAnimatable = makeFont( bold = True, italic = True )\n\ndef makeSceneGraphMimeData( source, objects ):\n\tids =[]\n\tfor obj in objects:\n\t\tif isMockInstance( obj, 'Entity' ):\n\t\t\tguid = obj['__guid']\n\t\t\tif guid:\n\t\t\t\tids.append( guid )\n\toutput = {\n\t\t'source': source,\n\t\t'ids': ids\n\t}\n\toutputData = json.dumps( output ).encode('utf-8')\n\tdata = QtCore.QMimeData()\n\tdata.setData( GII_MIME_ENTITY_REF, outputData )\n\treturn data\n\n##----------------------------------------------------------------##\nclass SceneGraphEditor( SceneEditorModule ):\n\tdef __init__(self):\n\t\tsuper( SceneGraphEditor, self ).__init__()\n\t\tself.sceneDirty = False\n\t\tself.sceneState = None\n\t\tself.activeSceneNode = None\n\t\tself.refreshScheduled = False\n\t\tself.previewing = False\n\t\tself.workspaceState = None\n\t\tself.recentScenes = []\n\n\t\tself.groupSoloVis = False\n\t\tself.groupSoloOpacity = False\n\t\tself.groupSoloEdit = True\n\n\t\tself.lockRootGroup = False\n\t\tself.previousManualRootGroupName = None\n\t\tself.previousRootGroupName = None\n\n\tdef getName( self ):\n\t\treturn 'scenegraph_editor'\n\n\tdef getDependency( self ):\n\t\treturn [ 'scene_editor', 'mock' ]\n\n\tdef onRegister( self, name ):\n\t\tmodulePreview = self.getModule( 'game_preview' )\n\t\tmodulePreview.registerPreviewCanvas( MOCKPreviewCanvas )\n\n\tdef onLoad( self ):\n\t\t#UI\n\t\tself.windowTitle = 'Scenegraph'\n\t\tself.container = self.requestDockWindow( 'SceneGraphEditor',\n\t\t\ttitle = 'Scenegraph',\n\t\t\tsize = (200,200),\n\t\t\tminSize = (200,200),\n\t\t\tdock = 'left'\n\t\t\t)\n\n\t\t#Components\n\t\tself.groupManager = GroupManagerWidget()\n\t\tself.groupManager.owner = self\n\t\tself.groupManager.hide()\n\n\t\tself.headerRootGroup = self.container.addWidget(\n\t\t\tHeaderRootGroupWidget( self.container ),\n\t\t\texpanding = True\n\t\t)\n\t\tself.headerRootGroup.owner = self\n\n\t\tself.treeFilter = self.container.addWidget(\n\t\t\tGenericTreeFilter(\n\t\t\t\tself.container\n\t\t\t),\n\t\t\texpanding = False\n\t\t)\n\t\tself.tree = self.container.addWidget( \n\t\t\t\tSceneGraphTreeWidget( \n\t\t\t\t\tself.container,\n\t\t\t\t\tsorting = True,\n\t\t\t\t\teditable = True,\n\t\t\t\t\tmultiple_selection = True,\n\t\t\t\t\tdrag_mode = 'internal'\n\t\t\t\t)\n\t\t\t)\n\t\tself.treeFilter.setTargetTree( self.tree )\n\t\tself.tree.module = self\n\t\tself.tool = self.addToolBar( 'scene_graph', self.container.addToolBar() )\n\t\t\n\t\tself.entityCreatorMenu=self.addMenu( 'main/scene/entity_create',\n\t\t\tdict( label = 'Create Entity' )\n\t\t)\n\n\t\tself.componentCreatorMenu=self.addMenu( 'main/scene/component_create',\n\t\t\tdict( label = 'Create Component' )\n\t\t)\n\n\n\t\t#menu\n\t\tself.addMenuItem(\n\t\t\t'main/file/open_scene', \n\t\t\tdict( label = 'Open Scene', shortcut = 'ctrl+shift+o' )\n\t\t\t)\n\n\t\tself.addMenuItem(\n\t\t\t'main/file/open_recent_scene', \n\t\t\tdict( label = 'Open Recent Scene', shortcut = 'ctrl+alt+o' )\n\t\t\t)\n\n\t\tself.addMenuItem( 'main/file/close_scene', \n\t\t\tdict( label = 'Close Scene', shortcut = 'Ctrl+W' )\n\t\t\t)\n\t\tself.addMenuItem( 'main/scene/save_scene',\n\t\t\tdict( label = 'Save', shortcut = 'Ctrl+S' )\n\t\t\t)\n\t\tself.addMenuItem( 'main/scene/locate_scene_asset',\n\t\t\tdict( label = 'Locate Scene Asset' )\n\t\t\t)\n\n\t\tself.addMenu( 'main/scene/----' )\n\t\tself.addMenuItem( 'main/scene/toggle_introspector_lock',\n\t\t\tdict( label = 'Toggle Introspector Lock', shortcut = 'Ctrl+I' )\n\t\t)\n\n\t\tself.addMenuItem( 'main/scene/lock_scenegroup',\n\t\t\tdict( label = 'Lock Scene Graph', type = 'check' )\n\t\t)\n\n\t\tself.addMenu( 'main/scene/----' )\n\t\tself.addMenuItem( 'main/scene/reallocate_scene_guid',\n\t\t\tdict( label = 'Reallocate Entity GUIDs' )\n\t\t\t)\n\n\t\tself.addMenu( 'main/scene/----' )\n\t\tself.addMenuItem( 'main/scene/change_root_group', dict( label = 'Change Scene Group', shortcut = 'ctrl+j' ) )\n\t\t\n\t\tself.addMenuItem( 'main/asset/----' )\n\t\tself.addMenuItem( 'main/asset/sync_mock_asset', dict( label = 'Sync MOCK Assets' ) )\n\n\t\t##\n\t\tself.addMenu( 'component_context', dict( label = 'Selected Component' ) )\n\t\tself.addMenuItem( 'component_context/remove_component', dict( label = 'Remove' ) )\n\t\tself.addMenuItem( 'component_context/----' )\n\t\tself.addMenuItem( 'component_context/copy_component', \tdict( label = 'Copy' ) )\n\t\tself.addMenuItem( 'component_context/paste_component', \tdict( label = 'Paste Component Here' ) )\n\t\tself.addMenuItem( 'component_context/----' )\n\t\tself.addMenuItem( 'component_context/toggle_bypass',\tdict( label = 'Toggle Bypassing Component' ) )\n\t\tself.addMenuItem( 'component_context/----' )\n\t\tself.addMenuItem( 'component_context/move_component_up', dict( label = 'Move Up' ) )\n\t\tself.addMenuItem( 'component_context/move_component_down', dict( label = 'Move Down' ) )\n\t\tself.addMenuItem( 'component_context/----' )\n\t\tself.addMenuItem( 'component_context/edit_component_alias', dict( label = 'Edit Alias' ) )\n\t\tself.addMenuItem( 'component_context/----' )\n\t\tself.addMenuItem( 'component_context/show_component_source', dict( label = 'Show Source File' ) )\n\n\t\tself.addMenu( 'main/entity', dict( label = 'Entity' ) )\n\t\t\n\t\tself.addMenuItem( 'main/entity/add_empty_entity', dict( label = 'Create Empty', shortcut = 'ctrl+alt+N' ) )\n\t\tself.addMenuItem( 'main/entity/add_entity', dict( label = 'Create', shortcut = 'ctrl+shift+N' ) )\n\t\t\n\t\tself.addMenuItem( 'main/entity/----' )\n\t\tself.addMenuItem( 'main/entity/load_prefab', dict( label = 'Load Prefab', shortcut = 'ctrl+alt+shift+N' ) )\n\t\tself.addMenuItem( 'main/entity/load_prefab_in_container', dict( label = 'Load Prefab In Container', shortcut = 'ctrl+shift+=' ) )\n\t\t\n\t\tself.addMenuItem( 'main/entity/----' )\n\t\tself.addMenuItem( 'main/entity/remove_entity', dict( label = 'Remove' ) )\n\t\tself.addMenuItem( 'main/entity/clone_entity', dict( label = 'Clone', shortcut = 'ctrl+d' ) )\n\t\t\n\t\tself.addMenuItem( 'main/entity/----' )\n\t\tself.addMenuItem( 'main/entity/add_component', dict( label = 'Add Component', shortcut = 'ctrl+alt+=' ) )\n\t\tself.addMenuItem( 'main/entity/assign_layer', dict( label = 'Assign Layer', shortcut = 'ctrl+alt+L' ) )\n\t\tself.addMenuItem( 'main/entity/toggle_visibility', dict( label = 'Toggle Visibility' ) )\n\t\tself.addMenuItem( 'main/entity/freeze_entity_pivot', dict( label = 'Freeze Pivot' ) )\n\t\tself.addMenuItem( 'main/entity/replace_entity_class',dict( label = 'Replace Entity' ) )\n\t\tself.addMenuItem( 'main/entity/reset_group_loc', dict( label = 'Reset Group Location' ) )\n\n\t\tself.addMenuItem( 'main/entity/----' )\n\t\tself.addMenuItem( 'main/find/find_entity', dict( label = 'Find In Scene', shortcut = 'ctrl+f' ) )\n\t\tself.addMenuItem( 'main/find/find_entity_in_group', dict( label = 'Find In Group', shortcut = 'ctrl+alt+f' ) )\n\t\tself.addMenuItem( 'main/find/find_entity_group', dict( label = 'Find Group' ) )\n\t\tself.addMenuItem( 'main/find/find_asset_in_entity', dict( label = 'Find Asset In Entity', shortcut = 'ctrl+e' ) )\n\n\t\t#Toolbars\n\t\tself.addTool( 'scene_graph/select_scene', label ='Select Scene', icon = 'settings' )\n\t\tself.addTool( 'scene_graph/----' )\n\t\tself.addTool( 'scene_graph/create_group', label ='+ Group', icon = 'add_folder' )\n\t\tself.addTool( 'scene_graph/----' )\n\t\tself.addTool( 'scene_graph/make_proto', label = 'Convert To Proto', icon = 'proto_make' )\n\t\tself.addTool( 'scene_graph/save_prefab', label = 'Save to Prefab', icon = 'prefab_make' )\n\t\tself.addTool( 'scene_graph/----' )\n\t\tself.addTool( 'scene_graph/create_proto_instance', label = 'Create Proto Instance', icon = 'proto_instantiate' )\n\t\tself.addTool( 'scene_graph/create_proto_container', label = 'Create Proto Container', icon = 'proto_container' )\n\t\tself.addTool( 'scene_graph/----' )\n\t\tself.addTool( 'scene_graph/refresh_tree', label = 'R', icon = 'refresh' )\n\n\t\tself.addTool( 'scene/refresh', label = 'refresh', icon='refresh' )\n\n\t\t#ShortCuts\n\t\tself.addShortcut( self.container, 'ctrl+/', 'scene_editor/toggle_entity_visibility' )\n\t\t# self.addShortcut( self.container, 'ctrl+alt+/', 'scene_editor/toggle_entity_group_solo' )\n\n\t\t#SIGNALS\n\t\tsignals.connect( 'moai.clean', self.onMoaiClean )\n\n\t\tsignals.connect( 'scene.clear', self.onSceneClear )\n\t\tsignals.connect( 'scene.change', self.onSceneChange )\n\n\t\tsignals.connect( 'selection.changed', self.onSelectionChanged )\n\t\tsignals.connect( 'selection.hint', self.onSelectionHint )\n\n\t\tsignals.connect( 'preview.start', self.onPreviewStart )\n\t\tsignals.connect( 'preview.stop' , self.onPreviewStop )\n\n\t\t# signals.connect( 'animator.start', self.onAnimatorStart )\n\t\t# signals.connect( 'animator.stop' , self.onAnimatorStop )\n\n\t\tsignals.connect( 'entity.added', self.onEntityAdded )\n\t\tsignals.connect( 'entity.removed', self.onEntityRemoved )\n\t\tsignals.connect( 'entity.renamed', self.onEntityRenamed )\n\t\tsignals.connect( 'entity.reorder', self.onEntityReorder )\n\t\tsignals.connect( 'entity.modified', self.onEntityModified )\n\t\tsignals.connect( 'entity.visible_changed', self.onEntityVisibleChanged )\n\t\tsignals.connect( 'entity.pickable_changed', self.onEntityPickableChanged )\n\n\n\t\tsignals.connect( 'prefab.unlink', self.onPrefabUnlink )\n\t\tsignals.connect( 'prefab.relink', self.onPrefabRelink )\n\t\tsignals.connect( 'prefab.pull', self.onPrefabPull )\n\n\t\tsignals.connect( 'proto.unlink', self.onPrefabUnlink )\n\t\tsignals.connect( 'proto.relink', self.onPrefabRelink )\n\n\t\tsignals.connect( 'app.ready', self.postAppReady )\n\n\n\t\tsignals.connect( 'component.added', self.onComponentAdded )\n\t\tsignals.connect( 'component.removed', self.onComponentRemoved )\n\n\t\tsignals.connect( 'project.presave', self.preProjectSave )\n\n\t\tsignals.connect( 'asset.modified', self.onAssetModified )\n\t\tsignals.connect( 'asset.imported_all', self.postAssetImport )\n\n\n\t\tregisterSearchEnumerator( sceneObjectSearchEnumerator )\n\t\tregisterSearchEnumerator( entityNameSearchEnumerator )\n\t\tregisterSearchEnumerator( componentNameSearchEnumerator )\n\t\tregisterSearchEnumerator( layerNameSearchEnumerator )\n\n\t\tself.delegate = MOAILuaDelegate( self )\n\t\tself.delegate.load( getModulePath( 'SceneGraphEditor.lua' ) )\n\n\t\tself.detectedModifiedProto = {}\n\n\tdef onStart( self ):\n\t\tself.refreshCreatorMenu()\n\n\tdef postAppReady( self ):\n\t\tself.openPreviousScene()\n\n\tdef openPreviousScene( self ):\n\t\tpreviousScene = self.getWorkspaceConfig( 'previous_scene', None )\n\t\tif previousScene:\n\t\t\tnode = self.getAssetLibrary().getAssetNode( previousScene )\n\t\t\tif node:\n\t\t\t\tnode.edit()\n\n\tdef confirmStop( self ):\n\t\tif self.affirmSceneSaved() == 'cancel': return False\n\t\treturn True\n\n\tdef onStop( self ):\n\t\tif self.activeSceneNode:\n\t\t\tself.setWorkspaceConfig( 'previous_scene', self.activeSceneNode.getNodePath() )\n\t\telse:\n\t\t\tself.setWorkspaceConfig( 'previous_scene', False )\n\n\tdef onSetFocus( self ):\n\t\tself.container.show()\n\t\tself.container.raise_()\n\t\tself.container.setFocus()\n\n\tdef getActiveSceneNode( self ):\n\t\treturn self.activeSceneNode\n\t\t\n\tdef getActiveScene( self ):\n\t\treturn self.delegate.safeCallMethod( 'editor', 'getScene' )\n\n\tdef getActiveSceneRootGroup( self ):\n\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\tif scene:\n\t\t\treturn scene.getRootGroup( scene )\n\t\telse:\n\t\t\treturn None\n\n\tdef getRootSceneGroups( self ):\n\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\tif scene:\n\t\t\tgroups = scene.getRootGroups( scene )\n\t\t\treturn [ g for g in groups.values() ]\n\t\telse:\n\t\t\treturn []\n\n\tdef listRootGroupsForSearch( self, typeId, context, option ):\n\t\tgroups = self.getRootSceneGroups()\n\t\tresult = []\n\t\tfor g in groups:\n\t\t\tif g._isDefault:\n\t\t\t\tname = '<DEFAULT>'\n\t\t\telse:\n\t\t\t\tname = g.getName( g )\n\t\t\tentry = ( g, name, 'scene_group', 'entity_group' )\n\t\t\tresult.append( entry )\n\t\treturn result\n\n\tdef getAssetPathsInUse( self ):\n\t\tif not self.activeSceneNode:\n\t\t\treturn []\n\t\tassets = self.delegate.safeCallMethod( 'editor', 'getAssetsInUse' )\n\t\tif assets:\n\t\t\treturn list(assets.keys())\n\t\telse:\n\t\t\treturn []\n\n\tdef getAssetsInUse( self, assetType = None ):\n\t\tlib = self.getAssetLibrary()\n\t\tresult = [ lib.getAssetNode( path ) for path in self.getAssetPathsInUse() ]\n\t\tif assetType:\n\t\t\tresult1 = []\n\t\t\tfor node in result:\n\t\t\t\tif node:\n\t\t\t\t\tif node.getType() == assetType:\n\t\t\t\t\t\tresult1.append( node )\n\t\t\tresult = result1\n\t\treturn result\n\n\tdef onAssetModified( self, node ):\n\t\tif node.getType() == 'proto':\n\t\t\tif not self.detectedModifiedProto:\n\t\t\t\tself.detectedModifiedProto = {}\n\t\t\tself.detectedModifiedProto[ node.getPath() ] = True\n\n\tdef postAssetImport( self ):\n\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\tif not self.detectedModifiedProto: return\n\t\tif not scene: return\n\t\tneedReload = False\n\t\tprotoInstances = _MOCK.findProtoInstances( scene )\n\t\tfor protoPath in self.detectedModifiedProto.keys():\n\t\t\tif needReload: break\n\t\t\tfor instance in protoInstances.values():\n\t\t\t\tif _MOCK.hasProtoHistory( instance, protoPath ):\n\t\t\t\t\tneedReload = True\n\t\t\t\t\tbreak\n\t\tself.detectedModifiedProto = False\n\t\tif needReload:\n\t\t\tself.reopenScene()\n\n\tdef updateButtonPanelGroup( self ):\n\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\tgroup = scene.getDefaultRootGroup( scene )\n\t\tif group._isDefault:\n\t\t\tself.headerRootGroup.setButtonText( '<DEFAULT>' )\n\t\telse:\n\t\t\tself.headerRootGroup.setButtonText( group.getName( group ) )\n\n\tdef changeToPreviousRootGroup( self ):\n\t\ttargetGroupName = self.workspaceState.get( 'active_root_group', self.previousRootGroupName )\n\t\tif self.lockRootGroup and self.previousManualRootGroupName:\n\t\t\ttargetGroupName = self.previousManualRootGroupName\n\n\t\tif targetGroupName:\n\t\t\treturn self.changeRootGroupByName( targetGroupName )\n\t\telse:\n\t\t\treturn False\n\n\tdef changeRootGroup( self, group, manual = False ):\n\t\tres = self.delegate.safeCallMethod( 'editor', 'changeRootGroup', group )\n\t\tif res and res != 'same' :\n\t\t\tself.previousRootGroupName = group.name\n\t\t\tif manual: self.previousManualRootGroupName = group.name\n\t\t\tself.updateButtonPanelGroup()\n\t\t\tself.onSceneGroupChange()\n\t\treturn res\n\n\tdef changeRootGroupByName( self, name, manual = False ):\n\t\tgroup = self.delegate.safeCallMethod( 'editor', 'getRootGroup', name )\n\t\tif group:\n\t\t\treturn self.changeRootGroup( group, manual )\n\t\telse:\n\t\t\treturn False\n\n\tdef setGroupSoloVis( self, soloVis ):\n\t\tself.groupSoloVis = soloVis\n\t\tself.onSceneGroupChange()\n\n\tdef setGroupSoloOpacity( self, soloOpacity ):\n\t\tself.groupSoloOpacity = soloOpacity\n\t\tself.onSceneGroupChange()\n\n\tdef setGroupSoloEdit( self, soloEdit ):\n\t\tself.groupSoloEdit = soloEdit\n\t\tself.onSceneGroupChange()\n\t\t\n\tdef addRootGroup( self ):\n\t\tname = requestString('Create Scene Group:', 'Enter Group Name:' )\n\t\tif not name: return False\n\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\tif scene.getRootGroup( scene, name ):\n\t\t\talertMessage( 'warn', \n\t\t\t\t'Duplicated scene group name: %s' % name\n\t\t\t)\n\t\t\treturn False\n\n\t\tcmd = self.doCommand(\n\t\t\t'scene_editor/create_root_group', \n\t\t\tname = name\n\t\t)\n\t\tif not cmd: return False\n\t\tgroup = cmd.getResult()\n\t\treturn group\n\n\tdef removeRootGroup( self, group ):\n\t\tif group._isDefault:\n\t\t\talertMessage( 'warn', \n\t\t\t\t'Can not remove DEFAULT scene group'\n\t\t\t)\n\t\t\treturn False\n\t\tif self.doCommand(\n\t\t\t'scene_editor/remove_root_group', \n\t\t\tgroup = group\n\t\t):\n\t\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\t\tif scene.getDefaultRootGroup( scene ) == group:\n\t\t\t\tscene.setDefaultRootGroup( scene )\n\t\t\t\tself.updateButtonPanelGroup()\n\t\t\t\tself.onSceneGroupChange()\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef cloneRootGroup( self, group ):\n\t\tpass\n\n\tdef renameRootGroup( self, group ):\n\t\tif group._isDefault:\n\t\t\talertMessage( 'warn', \n\t\t\t\t'Can not rename DEFAULT scene group'\n\t\t\t)\n\t\t\treturn False\n\t\tname0 = group.getName( group )\n\t\tname = requestString('Rename Scene Group <%s>' % name0, 'Enter New Name (%s):' % name0 )\n\t\tif not name: return False\n\t\tif name == name0: return False\n\t\t\n\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\tif scene.getRootGroup( scene, name ):\n\t\t\talertMessage( 'warn', \n\t\t\t\t'Duplicated scene group name: %s' % name\n\t\t\t)\n\t\t\treturn False\n\n\t\tif self.doCommand(\n\t\t\t'scene_editor/rename_root_group', \n\t\t\tgroup = group,\n\t\t\tname = name\n\t\t):\n\t\t\tself.updateButtonPanelGroup()\n\t\t\tself.onSceneGroupChange()\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef listRecentScenes( self, typeId, context, option ):\n\t\tentries = []\n\t\tlib = self.getAssetLibrary()\n\t\tfor path in reversed( self.recentScenes ):\n\t\t\tnode = lib.getAssetNode( path )\n\t\t\tif node:\n\t\t\t\tentry = ( node, path, 'scene', 'scene' )\n\t\t\t\tentries.append( entry )\n\t\treturn entries\n\n\tdef locateProto( self, protoNode ):\n\t\tif not self.delegate.safeCallMethod( 'editor', 'locateProto', protoNode.getPath() ): return\n\t\tif self.getModule('scene_view'):\n\t\t\tself.getModule('scene_view').focusSelection()\n\n\tdef locateEntityByGUID( self, guid ):\n\t\tif not self.delegate.safeCallMethod( 'editor', 'locateEntityByGUID', guid ): return\n\t\tif self.getModule('scene_view'):\n\t\t\tself.getModule('scene_view').focusSelection()\n\n\tdef openSceneByPath( self, path ):\n\t\tassetNode = self.getAssetLibrary().getAssetNode( path )\n\t\tif assetNode:\n\t\t\treturn self.openScene( assetNode )\n\t\treturn None\n\n\tdef openScene( self, node ):\n\t\tsceneView = self.getModule( 'scene_view' )\n\t\tif self.activeSceneNode == node:\n\t\t\tif self.getModule( 'scene_view' ):\n\t\t\t\tself.getModule( 'scene_view' ).setFocus()\n\n\t\telse:\n\t\t\tif not self.closeScene(): return False\n\t\t\tif sceneView: sceneView.makeCanvasCurrent()\n\t\t\tself.activeSceneNode = node\n\t\t\tsignals.emitNow( 'scene.pre_open', node )\n\t\t\t\n\t\t\tif sceneView: sceneView.makeCanvasCurrent()\n\t\t\tscene = self.delegate.safeCallMethod( 'editor', 'openScene', node.getPath() )\n\t\t\tif not scene:\n\t\t\t\t#todo: raise something\n\t\t\t\talertMessage( 'error', \n\t\t\t\t\t'%s\\n\\nfailed to open scene, see console for detailed information.' % node.getPath() )\n\t\t\t\tself.activeSceneNode = None\n\t\t\t\treturn False\n\t\t\t\n\t\t\tself.sceneState = 'ok'\n\n\t\t\tsignals.emitNow( 'scene.open', self.activeSceneNode, scene )\n\t\t\tself.setFocus()\n\t\t\tself.loadWorkspaceState( False )\n\t\t\tif sceneView: sceneView.makeCanvasCurrent()\n\t\t\tself.delegate.safeCallMethod( 'editor', 'postOpenScene' )\n\t\t\ttoolMgr = self.getModule( 'scene_tool_manager' )\n\t\t\tif toolMgr:\n\t\t\t\ttoolMgr.resetTool()\n\t\t\tself.changeSelection( None )\n\n\t\t\tif self.changeToPreviousRootGroup() == True:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tself.updateButtonPanelGroup()\n\t\t\t\tself.onSceneGroupChange()\n\t\t\t\n\t\t\tself.setWorkspaceConfig( 'active_scene', self.activeSceneNode.getNodePath() )\n\t\t\t\n\t\treturn True\n\n\tdef affirmSceneSaved( self ):\n\t\tif self.sceneDirty:\n\t\t\tres = requestConfirm( 'scene modified!', 'save scene before close?' )\n\t\t\tif res == True: #save\n\t\t\t\tself.saveScene()\n\t\t\t\treturn True\n\t\t\telif res == None: #cancel\n\t\t\t\treturn 'cancel'\n\t\t\telif res == False: #no save\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\n\tdef closeScene( self ):\n\t\tif self.previewing:\n\t\t\talertMessage( 'Previewing', 'stop prevewing before closing scene' )\n\t\t\treturn False\n\n\t\tif not self.activeSceneNode: return True\n\t\tif self.affirmSceneSaved() == 'cancel': return False\n\n\t\tpath = self.activeSceneNode.getPath()\n\t\ttry:\n\t\t\tself.recentScenes.remove( path )\n\t\texcept Exception as e:\n\t\t\tpass\n\t\t\t\n\t\tself.saveWorkspaceState()\n\t\t\n\t\tself.sceneState = None\n\t\tself.tree.clear()\n\t\tself.getApp().clearCommandStack( 'scene_editor' )\n\t\tsignals.emitNow( 'scene.close', self.activeSceneNode )\n\t\tself.delegate.safeCallMethod( 'editor', 'closeScene' )\t\t\n\t\tself.recentScenes.append( path )\n\t\tself.markSceneDirty( False )\n\t\tself.activeSceneNode = None\n\t\tself.workspaceState = None\n\t\t\n\t\treturn True\n\n\tdef onSceneClear( self ):\n\t\t# self.tree.clear()\n\t\tpass\n\n\tdef findEntityByGUID(self,guid):\n\t\treturn self.delegate.safeCallMethod('editor','findEntityByGUID',guid)\n\n\tdef findComByGUID(self,guid):\n\t\treturn self.delegate.safeCallMethod('editor','findComByGUID',guid)\n\n\tdef markSceneDirty( self, dirty = True ):\n\t\tif not self.previewing:\n\t\t\tif self.activeSceneNode:\n\t\t\t\tif dirty != self.sceneDirty:\n\t\t\t\t\tself.sceneDirty = dirty\n\n\tdef saveWorkspaceState( self ):\n\t\tself.retainWorkspaceState()\n\t\ttreeFoldState = self.workspaceState['tree_state']\n\t\tcontainerFoldState = self.workspaceState['container_state']\n\t\tentityLockState = self.workspaceState['entity_lock_state']\n\t\tactiveRootGroupName = self.workspaceState['active_root_group']\n\t\tself.activeSceneNode.setWorkspaceData( 'tree_state', treeFoldState )\n\t\tself.activeSceneNode.setWorkspaceData( 'container_state', containerFoldState )\n\t\tself.activeSceneNode.setWorkspaceData( 'entity_lock_state', entityLockState )\n\t\tself.activeSceneNode.setWorkspaceData( 'active_root_group', activeRootGroupName )\n\n\tdef loadWorkspaceState( self, restoreState = True ):\n\t\ttreeFoldState = self.activeSceneNode.getWorkspaceData( 'tree_state', None )\t\t\n\t\tcontainerFoldState = self.activeSceneNode.getWorkspaceData( 'container_state', None )\t\t\n\t\tentityLockState = self.activeSceneNode.getWorkspaceData( 'entity_lock_state', None )\t\n\t\tactiveRootGroupName = self.activeSceneNode.getWorkspaceData( 'active_root_group', None )\n\n\t\t#Legacy support\n\t\tif not treeFoldState:\n\t\t\ttreeFoldState = self.activeSceneNode.getMetaData( 'tree_state', None )\t\t\n\t\tif not containerFoldState:\n\t\t\tcontainerFoldState = self.activeSceneNode.getMetaData( 'container_state', None )\t\t\n\t\tif not entityLockState:\n\t\t\tentityLockState = self.activeSceneNode.getMetaData( 'entity_lock_state', None )\t\n\t\t\t\n\t\tself.workspaceState = {\n\t\t\t'tree_state' : treeFoldState,\n\t\t\t'container_state' : containerFoldState,\n\t\t\t'entity_lock_state' : entityLockState,\n\t\t\t'active_root_group' : activeRootGroupName,\n\t\t}\t\t\n\t\tif restoreState: self.restoreWorkspaceState()\n\n\tdef retainWorkspaceState( self ):\n\t\t#tree node foldstate\n\t\ttreeFoldState = None\n\t\tif self.workspaceState:\n\t\t\ttreeFoldState = self.workspaceState.get( 'tree_state', None )\n\t\tif not treeFoldState:\n\t\t\ttreeFoldState = {}\n\t\t\t\n\t\tfor key, value in self.tree.saveFoldState().items():\n\t\t\ttreeFoldState[ key ] = value\n\t\t#save introspector foldstate\n\t\tintrospectorFoldState = self.delegate.safeCallMethod( 'editor', 'saveIntrospectorFoldState' )\n\t\tentityLockState = self.delegate.safeCallMethod( 'editor', 'saveEntityLockState' )\n\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\tg = scene.getDefaultRootGroup( scene )\n\t\tself.workspaceState = {\n\t\t\t'tree_state' : treeFoldState,\n\t\t\t'container_state' : introspectorFoldState,\n\t\t\t'entity_lock_state' : entityLockState,\n\t\t\t'active_root_group' : g.name\n\t\t}\n\n\tdef restoreWorkspaceState( self ):\n\t\tif not self.workspaceState: return\n\t\ttreeState = self.workspaceState.get( 'tree_state', None )\n\t\tif treeState:\n\t\t\tself.tree.loadFoldState( treeState )\t\n\t\t\n\t\tcontainerState = self.workspaceState.get( 'container_state', None )\n\t\tif containerState:\n\t\t\tself.delegate.safeCallMethod( 'editor', 'loadIntrospectorFoldState', containerState )\n\t\t\n\t\tlockState = self.workspaceState.get( 'entity_lock_state', None )\n\t\tif lockState:\n\t\t\tself.delegate.safeCallMethod( 'editor', 'loadEntityLockState', lockState )\n\n\n\tdef onSceneGroupChange( self ):\n\t\tscene = self.delegate.safeCallMethod( 'editor', 'getScene' )\n\t\tscene.updateSolo( scene, self.groupSoloVis, self.groupSoloOpacity, self.groupSoloEdit )\n\t\tsignals.emit( 'scene.update' )\n\t\tsignals.emit( 'entity.gizmo_changed', None )\n\t\tsceneView = self.getModule( 'scene_view' )\n\t\tif sceneView:\n\t\t\tgroup = self.getActiveSceneRootGroup()\n\t\t\tif group:\n\t\t\t\tsceneView.setInfo( 'Group:' + group.name )\n\t\t\telse:\n\t\t\t\tsceneView.setInfo( '' )\n\n\t\treturn self.onSceneChange()\n\n\tdef onSceneChange( self ):\n\t\tself.tree.rebuild()\n\t\tself.restoreWorkspaceState()\n\t\tself.tree.refreshAllContent()\n\t\tself.tree.verticalScrollBar().setValue( 0 )\n\t\t\n\tdef saveScene( self ):\n\t\tif not self.activeSceneNode: return\n\t\t\n\t\tif self.sceneState == 'error':\n\t\t\tif not requestConfirm(\n\t\t\t\t'Warning',\n\t\t\t\t'There are errors in current scene, saving might cause corruption, confirm?'\n\t\t\t):\n\t\t\t\treturn False\n\n\t\tsignals.emitNow( 'scene.save' )\n\t\tpath = self.activeSceneNode.getAbsFilePath()\n\t\tres = self.delegate.safeCallMethod( 'editor', 'saveScene', path )\n\t\tsignals.emitNow( 'scene.saved' )\n\t\tif res:\n\t\t\tself.saveWorkspaceState()\n\t\t\tself.markSceneDirty( False )\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef reopenScene( self ):\n\t\tif not self.activeSceneNode: return\n\t\tif self.previewing: return\n\t\tsceneNode = self.activeSceneNode\n\t\tself.closeScene()\n\t\tself.openScene( sceneNode )\n\n\tdef refreshScene( self ):\n\t\tif not self.activeSceneNode: return\n\t\tif self.previewing: return\n\n\t\tself.refreshScheduled = False\n\t\tnode = self.activeSceneNode\n\n\t\tif self.sceneState == 'ok':\n\t\t\tself.retainWorkspaceState()\n\t\t\n\t\t#TODO: confirm scene saving if dirty\n\t\tif self.delegate.safeCallMethod( 'editor', 'refreshScene' ):\n\t\t\tself.sceneState = 'ok'\n\t\t\tself.restoreWorkspaceState()\n\t\telse:\n\t\t\talertMessage( 'Warning', 'error while refreshing current scene' )\n\t\t\tself.sceneState = 'error'\n\n\t\tself.refreshCreatorMenu()\n\t\tself.onSceneGroupChange()\n\n\tdef scheduleRefreshScene( self ):\n\t\tif not self.activeSceneNode: return\n\t\tself.refreshScheduled = True\n\n\tdef refreshCreatorMenu( self ):\n\t\tdef addEntityMenuItem( name ):\n\t\t\tif name == '----': \n\t\t\t\tself.entityCreatorMenu.addChild( '----' )\n\t\t\t\treturn\n\t\t\tself.entityCreatorMenu.addChild({\n\t\t\t\t\t'name' : 'create_entity_'+name,\n\t\t\t\t\t'label' : name,\n\t\t\t\t\t'command' : 'scene_editor/create_entity',\n\t\t\t\t\t'command_args' : dict( name = name )\n\t\t\t\t})\n\n\t\tdef addComponentMenuItem( name ):\n\t\t\tif name == '----': \n\t\t\t\tself.componentCreatorMenu.addChild( '----' )\n\t\t\t\treturn\n\t\t\tself.componentCreatorMenu.addChild({\n\t\t\t\t\t'name' : 'create_component_'+name,\n\t\t\t\t\t'label' : name,\n\t\t\t\t\t'command' : 'scene_editor/create_component',\n\t\t\t\t\t'command_args' : dict( name = name )\n\t\t\t\t})\n\n\t\tself.entityCreatorMenu.clear()\n\t\tself.componentCreatorMenu.clear()\n\n\t\tregistry = _MOCK.getEntityRegistry()\n\t\t#entity\n\t\tkeys = sorted( registry.keys() )\n\t\taddEntityMenuItem( 'Entity' )\n\t\taddEntityMenuItem( '----' )\n\t\tfor entityName in sorted( registry.keys() ):\n\t\t\tif entityName!='Entity': addEntityMenuItem( entityName )\n\n\t\t#component\n\t\tregistry = _MOCK.getComponentRegistry()\n\t\tfor comName in sorted( registry.keys() ):\n\t\t\taddComponentMenuItem( comName )\n\n\tdef needUpdate( self ):\n\t\treturn True\n\t\t\n\tdef onUpdate( self ):\n\t\tif self.refreshScheduled:\n\t\t\tself.refreshScene()\n\n\tdef preProjectSave( self, prj ):\n\t\tif self.activeSceneNode:\n\t\t\t# _MOCK.game.previewingScene = self.activeSceneNode.getNodePath()\n\t\t\tself.setWorkspaceConfig( 'active_scene', self.activeSceneNode.getNodePath() )\n\n\tdef getAutoCompletion( self, full = False ):\n\t\tscene = self.getActiveScene()\n\t\tif not scene: return []\n\t\tv = {}\n\t\tfor ent in scene.entities.keys():\n\t\t\tif ent.FLAG_INTERNAL: continue\n\t\t\tif ent.FLAG_EDITOR_OBJECT: continue\n\t\t\tif full:\n\t\t\t\tname = ent.getFullName( ent, False )\n\t\t\telse:\n\t\t\t\tname = ent.getName( ent )\n\t\t\tif len( name ) >= 3:\n\t\t\t\tv[ name ] = True\n\t\tentityNames = list( v.keys() )\n\t\treturn entityNames\n\n\tdef onMoaiClean( self ):\n\t\tself.tree.clear()\n\n\t\n\tdef onTool( self, tool ):\n\t\tname = tool.name\n\t\tif name == 'refresh_tree':\n\t\t\tself.tree.rebuild()\n\n\t\telif name == 'refresh':\n\t\t\tself.scheduleRefreshScene()\n\t\t\t\n\t\telif name == 'save_prefab':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select a perfab node to store',\n\t\t\t\tcontext = 'asset',\n\t\t\t\ttype = 'prefab',\n\t\t\t\ton_selection = lambda obj: self.createPrefab( obj )\t\t\t\t\n\t\t\t\t)\n\t\t\n\t\telif name == 'make_proto':\n\t\t\tself.makeProto()\n\n\t\telif name == 'create_proto_instance' or name == 'load_prefab':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select a proto to instantiate',\n\t\t\t\tcontext = 'asset',\n\t\t\t\ttype = 'proto;prefab',\n\t\t\t\ton_selection = \n\t\t\t\t\tlambda obj: \n\t\t\t\t\t\tself.doCommand( 'scene_editor/create_proto_instance', proto = obj.getNodePath() )\n\t\t\t\t)\n\n\t\telif name == 'create_proto_container':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select a proto to create contained instance',\n\t\t\t\tcontext = 'asset',\n\t\t\t\ttype = 'proto;prefab',\n\t\t\t\ton_selection = \n\t\t\t\t\tlambda obj: \n\t\t\t\t\t\tself.doCommand( 'scene_editor/create_proto_container', proto = obj.getNodePath() )\n\t\t\t\t)\n\n\t\telif name == 'select_scene':\n\t\t\tself.doCommand( 'scene_editor/select_scene' )\n\n\t\telif name == 'create_group':\n\t\t\tself.doCommand( 'scene_editor/entity_group_create' )\n\n\t\telif name == 'group_entity':\n\t\t\tself.doCommand( 'scene_editor/group_entities' )\n\t\t\t\n\tdef onMenu( self, menu ):\n\t\tname = menu.name\n\t\tif name == 'close_scene':\n\t\t\tif self.previewing:\n\t\t\t\talertMessage( 'Warning', 'Stop previewing before closing scene' )\n\t\t\t\treturn\n\t\t\tself.closeScene()\n\n\t\telif name == 'open_scene':\n\t\t\tif self.previewing:\n\t\t\t\talertMessage( 'Warning', 'Stop previewing before opening scene' )\n\t\t\t\treturn\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select scene to open',\n\t\t\t\tcontext = 'asset',\n\t\t\t\ttype = 'scene',\n\t\t\t\ton_selection = self.openScene\n\t\t\t\t)\n\t\t\t\n\t\telif name == 'save_scene':\n\t\t\tif self.previewing:\n\t\t\t\talertMessage( 'Warning', 'Stop previewing before saving' )\n\t\t\t\treturn\n\t\t\tself.saveScene()\n\n\t\telif name == 'open_recent_scene':\n\t\t\tif self.previewing:\n\t\t\t\talertMessage( 'Warning', 'Stop previewing before opening scene' )\n\t\t\t\treturn\n\t\t\trequestSearchView(\n\t\t\t\tinfo = 'open recently opened scene',\n\t\t\t\tcontext = 'asset',\n\t\t\t\ttype = 'scene',\n\t\t\t\ton_selection = self.openScene,\n\t\t\t\ton_search = self.listRecentScenes,\n\t\t\t\tsort_method = 'none'\n\t\t\t\t)\n\n\t\telif name == 'change_root_group':\n\t\t\trequestSearchView(\n\t\t\t\tinfo = 'change active scene group',\n\t\t\t\tcontext = 'scene',\n\t\t\t\ttype = 'scene',\n\t\t\t\ton_selection = lambda obj: self.changeRootGroup( obj, manual = True ),\n\t\t\t\ton_search = self.listRootGroupsForSearch,\n\t\t\t\tsort_method = 'none'\n\t\t\t\t)\n\n\t\telif name == 'sync_mock_asset':\n\t\t\tself.getModule( 'mock' ).syncBuiltinAsset()\n\n\t\telif name == 'locate_scene_asset':\n\t\t\tif self.activeSceneNode:\n\t\t\t\tassetBrowser = self.getModule( 'asset_browser' )\n\t\t\t\tif assetBrowser:\n\t\t\t\t\tassetBrowser.locateAsset( self.activeSceneNode )\n\n\t\telif name == 'add_entity':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select entity type to create',\n\t\t\t\tcontext = 'entity_creation',\n\t\t\t\ton_selection = lambda obj: \n\t\t\t\t\tself.doCommand( 'scene_editor/create_entity', name = obj )\n\t\t\t\t)\n\n\t\telif name == 'add_component':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select component type to create',\n\t\t\t\tcontext = 'component_creation',\n\t\t\t\ton_selection = lambda obj: \n\t\t\t\t\tself.doCommand( 'scene_editor/create_component', name = obj )\n\t\t\t\t)\n\n\t\telif name == 'add_empty_entity':\n\t\t\tself.doCommand( 'scene_editor/create_entity', name = 'Empty' )\n\n\t\telif name == 'load_prefab':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select a proto to instantiate',\n\t\t\t\tcontext = 'asset',\n\t\t\t\ttype = 'proto;prefab',\n\t\t\t\ton_selection = \n\t\t\t\t\tlambda obj: \n\t\t\t\t\t\tself.doCommand( 'scene_editor/create_proto_instance', proto = obj.getNodePath() )\n\t\t\t\t)\n\n\t\telif name == 'load_prefab_in_container':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select a perfab node to instantiate( PefabContainer )',\n\t\t\t\tcontext = 'asset',\n\t\t\t\ttype = 'prefab;proto',\n\t\t\t\ton_selection = \n\t\t\t\t\tlambda obj: \n\t\t\t\t\t\tself.doCommand( 'scene_editor/create_prefab_container', prefab = obj.getNodePath() )\n\t\t\t\t)\n\n\t\telif name == 'remove_entity':\n\t\t\tself.doCommand( 'scene_editor/remove_entity' )\n\n\t\telif name == 'replace_entity_class':\n\t\t\tif self.previewing:\n\t\t\t\talertMessage( 'Warning', 'Cannot replace entity class while previewing' )\n\t\t\t\treturn\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select target entity class to replace with',\n\t\t\t\ton_search = self.onSearchEntityClass,\n\t\t\t\ton_selection = \n\t\t\t\t\tlambda clas: \n\t\t\t\t\t\tself.doCommand( 'scene_editor/replace_entity_class', targetClass = clas )\n\t\t\t)\t\t\t\t\n\n\t\telif name == 'clone_entity':\n\t\t\tself.doCommand( 'scene_editor/clone_entity' )\n\n\t\telif name == 'find_entity':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'search for entity in current scene',\n\t\t\t\tcontext = 'scene',\n\t\t\t\ttype = 'entity',\n\t\t\t\ton_selection = lambda x: self.selectEntity( x, focus_tree = True ) ,\n\t\t\t\ton_test = self.selectEntity\n\t\t\t\t)\n\n\t\t\n\t\telif name == 'find_entity_in_group':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'search for entity in current entity group',\n\t\t\t\tcontext = 'scene',\n\t\t\t\ttype = 'entity_in_group',\n\t\t\t\ton_selection = lambda x: self.selectEntity( x, focus_tree = True ) ,\n\t\t\t\ton_test = self.selectEntity\n\t\t\t\t)\n\n\t\telif name == 'find_entity_group':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'search for group in current scene',\n\t\t\t\tcontext = 'scene',\n\t\t\t\ttype = 'group',\n\t\t\t\ton_selection = lambda x: self.selectEntity( x, focus_tree = True ) ,\n\t\t\t\ton_test = self.selectEntity\n\t\t\t\t)\n\n\t\telif name == 'find_asset_in_entity':\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'list all asset used in current Entity',\n\t\t\t\ton_search = self.onSearchAssetInEntity,\n\t\t\t\ton_selection = self.getModule( 'asset_browser' ).locateAsset,\n\t\t\t\ton_test = self.getModule( 'asset_browser' ).selectAsset\n\t\t\t\t)\n\n\t\telif name == 'create_group':\n\t\t\tself.doCommand( 'scene_editor/entity_group_create' )\n\n\t\telif name == 'remove_component':\n\t\t\tcontext = menu.getContext()\n\t\t\tif context:\n\t\t\t\tself.doCommand( 'scene_editor/remove_component', target = context )\n\n\t\telif name == 'copy_component':\n\t\t\tcontext = menu.getContext()\n\t\t\tif context:\n\t\t\t\tself.onCopyComponent( context )\n\n\t\telif name == 'paste_component':\n\t\t\tcontext = menu.getContext()\n\t\t\tif context:\n\t\t\t\tself.onPasteComponent( context.getEntity( context ), context )\n\n\t\telif name == 'toggle_bypass':\n\t\t\tcontext = menu.getContext()\n\t\t\tif context:\n\t\t\t\tcom = context\n\t\t\t\tbypassed = com[ 'FLAG_BYPASSED' ]\n\t\t\t\tself.doCommand( 'scene_editor/set_bypassed', target = com, value = not bypassed )\n\n\t\telif name == 'move_component_up':\n\t\t\tcontext = menu.getContext()\n\t\t\tif context:\n\t\t\t\tself.onChangeComponentOrder( context, -1 )\n\n\t\telif name == 'move_component_down':\n\t\t\tcontext = menu.getContext()\n\t\t\tif context:\n\t\t\t\tself.onChangeComponentOrder( context, 1 )\n\n\t\telif name == 'show_component_source':\n\t\t\tcontext = menu.getContext()\n\t\t\tif context:\n\t\t\t\tsrc = context.getClassSourceFile( context ) or ''\n\t\t\t\tif src.startswith( '@' ):\n\t\t\t\t\tpath = src[ 1: ]\n\t\t\t\t\tif os.path.exists( path ):\n\t\t\t\t\t\topenFileInOS( path )\n\t\t\t\t\telse:\n\t\t\t\t\t\talertMessage( 'File not found', 'Cannot find source file:' + path )\n\t\t\t\telse:\n\t\t\t\t\talertMessage( 'Invalid Source Path', 'Unknown source:' + path )\n\n\t\telif name == 'edit_component_alias':\n\t\t\tcontext = menu.getContext()\n\t\t\tif context:\n\t\t\t\toldAlias = context._alias or ''\n\t\t\t\talias = requestString( 'Edit Alias', 'Enter Alias:', oldAlias )\n\t\t\t\tif alias != None:\n\t\t\t\t\tif not alias: alias = False\n\t\t\t\t\tself.doCommand( 'scene_editor/rename_component', target = context, alias = alias )\n\n\t\telif name == 'assign_layer':\n\t\t\tif not self.tree.getSelection(): return\n\t\t\trequestSearchView( \n\t\t\t\tinfo = 'select layer to assign',\n\t\t\t\tcontext = 'scene_layer',\n\t\t\t\ttype = _MOCK.Entity,\n\t\t\t\ton_selection = self.assignEntityLayer\n\t\t\t\t)\n\n\t\telif name == 'toggle_visibility':\n\t\t\tself.doCommand( 'scene_editor/toggle_entity_visibility' )\n\n\t\telif name == 'freeze_entity_pivot':\n\t\t\tself.doCommand( 'scene_editor/freeze_entity_pivot' )\n\n\t\telif name == 'reset_group_loc':\n\t\t\tself.doCommand( 'scene_editor/reset_group_loc' )\n\n\t\telif name == 'reallocate_scene_guid':\n\t\t\tif requestConfirm( \n\t\t\t\t'Reallocating GUID',\n\t\t\t\t'not UNDOABLE operation, confirm?\\n'\n\t\t\t\t):\n\t\t\t\tself.doCommand( 'scene_editor/reallocate_scene_guid' )\n\t\t\t\tself.markSceneDirty()\n\n\t\telif name == 'toggle_introspector_lock':\n\t\t\tm = self.getModule( 'introspector' )\n\t\t\tlocked = None\n\t\t\tfor instance in m.instances:\n\t\t\t\tif instance.locked:\n\t\t\t\t\tlocked = True\n\t\t\tfor instance in m.instances:\n\t\t\t\tinstance.setLocked( not locked )\n\n\t\telif name == 'lock_scenegroup':\n\t\t\tchecked = menu.getValue()\n\t\t\tself.lockRootGroup = checked\n\t\t\tg = self.getActiveSceneRootGroup()\n\t\t\tif g:\n\t\t\t\tself.previousManualRootGroupName = g.name\n\n\tdef onSelectionChanged( self, selection, key ):\n\t\tif key != 'scene': return\n\t\tif self.tree.syncSelection:\n\t\t\tself.tree.blockSignals( True )\n\t\t\tfor e in selection:\n\t\t\t\tif not ( isMockInstance( e, 'EntityGroup' ) or isMockInstance( e, 'Entity' ) ): continue\n\t\t\t\trootGroup = e.getRootGroup( e )\n\t\t\t\tif rootGroup:\n\t\t\t\t\tself.changeRootGroup( rootGroup )\n\t\t\t\t\tbreak\n\t\t\tself.tree.selectNode( None )\n\t\t\tfor e in selection:\n\t\t\t\tself.tree.selectNode( e, add = True)\t\t\t\t\n\t\t\tself.tree.blockSignals( False )\n\n\tdef selectEntity( self, target, **option ):\n\t\tif option.get( 'focus_tree', False ):\n\t\t\tself.tree.setFocus()\n\t\tself.changeSelection( target )\n\n\t##----------------------------------------------------------------##\n\tdef renameEntity( self, target, name ):\n\t\tself.doCommand( 'scene_editor/rename_entity', target = target, name = name )\n\n\tdef addEntityNode( self, entity ):\n\t\tself.tree.addNode( entity, expanded = False )\n\t\tself.tree.setNodeExpanded( entity, False )\n\n\tdef addEntityGroupNode( self, entity ):\n\t\tself.tree.addNode( entity, expanded = True )\n\t\tself.tree.setNodeExpanded( entity, True )\n\n\tdef removeEntityNode( self, entity ):\n\t\tself.tree.removeNode( entity )\n\n\tdef assignEntityLayer( self, layerName ):\n\t\t#TODO:command pattern\n\t\tif not layerName: return\n\t\tself.doCommand( 'scene_editor/assign_layer', target = layerName )\n\n\tdef onSelectionHint( self, selection ):\n\t\tif selection._entity:\n\t\t\tself.changeSelection( selection._entity )\t\t\t\n\t\telse:\n\t\t\tself.changeSelection( selection )\n\n\tdef onSearchAssetInEntity( self, typeId, context, option ):\n\t\tcollected = self.delegate.callMethod( 'editor', 'getAssetInSelectedEntity' )\n\t\tlib = self.getAssetLibrary()\n\t\tresult = []\n\t\tfor path in collected.values():\n\t\t\tnode = lib.getAssetNode( path )\n\t\t\tif node:\n\t\t\t\tentry = ( node, path, node.getType(), lib.getAssetIcon( node.getType() ) )\n\t\t\t\tresult.append( entry )\n\t\treturn result\n\n\tdef onPreviewStart( self ):\n\t\tif not self.activeSceneNode: return\n\t\tself.retainWorkspaceState()\n\t\tself.delegate.safeCallMethod( 'editor', 'retainScene' )\n\t\tself.delegate.safeCallMethod( 'editor', 'startScenePreview' )\n\t\tself.previewing = True\n\n\tdef onPreviewStop( self ):\n\t\tif not self.activeSceneNode: return\n\t\tself.changeSelection( None )\n\t\tself.tree.clear()\n\t\tself.delegate.safeCallMethod( 'editor', 'stopScenePreview' )\n\t\tself.previewing = False\n\t\tif self.delegate.safeCallMethod( 'editor', 'restoreScene' ):\n\t\t\tself.restoreWorkspaceState()\n\n\tdef onAnimatorStart( self ):\n\t\tself.retainWorkspaceState()\n\t\tself.delegate.safeCallMethod( 'editor', 'retainScene' )\n\n\tdef onAnimatorStop( self ):\n\t\tself.tree.clear()\n\t\tself.delegate.safeCallMethod( 'editor', 'clearScene' )\n\t\tif self.delegate.safeCallMethod( 'editor', 'restoreScene' ):\n\t\t\tself.restoreWorkspaceState()\n\n\t##----------------------------------------------------------------##\n\tdef updateEntityPriority( self ):\n\t\tif not self.activeSceneNode: return\n\t\tself.markSceneDirty()\n\n\tdef onEntityRenamed( self, entity, newname ):\n\t\tself.tree.refreshNodeContent( entity )\n\t\tself.markSceneDirty()\n\n\tdef onEntityReorder( self, entity ):\n\t\tself.tree.setSortingEnabled( False )\n\t\tself.tree.setSortingEnabled( True )\n\t\tself.markSceneDirty()\n\n\tdef onEntityVisibleChanged( self, entity ):\n\t\tself.tree.refreshNodeContent( entity )\n\t\tself.markSceneDirty()\n\n\tdef onEntityPickableChanged( self, entity ):\n\t\tself.tree.refreshNodeContent( entity )\n\t\tself.markSceneDirty()\n\n\tdef onEntityAdded( self, entity, context = None ):\n\t\tif context in ( 'new', 'clone', 'drag', 'instance' ):\n\t\t\tpnode = entity.parent\n\t\t\tif pnode:\n\t\t\t\tself.tree.setNodeExpanded( pnode, True )\n\t\t\tif context != 'clone':\n\t\t\t\tself.tree.selectNode( entity )\n\t\t\tif context == 'new':\n\t\t\t\tself.setFocus()\n\t\t\t\tself.tree.setFocus()\n\t\t\t\tself.tree.editNode( entity )\n\t\t\t\t\n\t\tsignals.emit( 'scene.update' )\n\t\tself.markSceneDirty()\n\n\tdef onEntityRemoved( self, entity ):\n\t\tsignals.emit( 'scene.update' )\n\t\tself.markSceneDirty()\n\n\tdef onEntityModified( self, entity, context = None ):\n\t\tself.markSceneDirty()\n\n\t##----------------------------------------------------------------##\n\tdef onComponentAdded( self, com, entity ):\n\t\tsignals.emit( 'scene.update' )\n\t\tself.markSceneDirty()\n\n\tdef onComponentRemoved( self, com, entity ):\n\t\tsignals.emit( 'scene.update' )\n\t\tself.markSceneDirty()\n\n\n\t##----------------------------------------------------------------##\n\tdef onPrefabUnlink( self, entity ):\n\t\tself.tree.refreshNodeContent( entity, updateChildren = True )\n\n\tdef onPrefabPull( self, entity ):\n\t\tself.markSceneDirty()\n\t\tself.tree.selectNode( entity )\n\n\tdef onPrefabRelink( self, entity ):\n\t\tself.tree.refreshNodeContent( entity, updateChildren = True )\n\n\tdef createPrefab( self, targetPrefab ):\n\t\tselection = self.getSelection()\n\t\tif not selection: return\n\t\tif len( selection ) > 1:\n\t\t\treturn alertMessage( 'multiple entities cannot be converted into prefab' )\n\t\ttarget = selection[0]\n\t\tif requestConfirm( 'convert prefab', 'Push selected Entity into Prefab?\\n' + targetPrefab.getNodePath() ):\n\t\t\tself.doCommand( 'scene_editor/create_prefab', \n\t\t\t\tentity = target, \n\t\t\t\tprefab = targetPrefab.getNodePath(),\n\t\t\t\tfile = targetPrefab.getAbsFilePath()\n\t\t\t)\n\n\tdef makeProto( self ):\n\t\tselection = self.getSelection()\n\t\tif not selection: return\n\t\tif len( selection ) > 1:\n\t\t\tif requestConfirm( 'convert protos', 'Convert multiple Entities into Protos?' ):\n\t\t\t\tfor target in selection:\n\t\t\t\t\tself.doCommand( 'scene_editor/make_proto', \n\t\t\t\t\t\tentity = target\n\t\t\t\t\t)\n\t\t\t\t\tself.tree.refreshNodeContent( target )\n\n\t\telse:\n\t\t\ttarget = selection[0]\n\t\t\tif not target: return\n\t\t\tif requestConfirm( 'convert proto', 'Convert this Entity into Proto?' ):\n\t\t\t\tself.doCommand( 'scene_editor/make_proto', \n\t\t\t\t\tentity = target\n\t\t\t\t)\n\t\t\t\tself.tree.refreshNodeContent( target )\n\n\tdef createProtoInstance( self ):\n\t\tpass\n\n\n\t##----------------------------------------------------------------##\n\tdef copyEntityToClipboard( self ):\n\t\tentityGroupData = self.delegate.callMethod( 'editor', 'makeSceneSelectionCopyData' )\n\t\tif not entityGroupData: \n\t\t\talertMessage( 'not implemented', 'failed to copy entities' )\n\t\t\treturn False\n\t\tclip = QtWidgets.QApplication.clipboard()\n\t\tmime = QtCore.QMimeData()\n\t\ttext = ''\n\t\tfor s in self.getSelection():\n\t\t\tif text == '':\n\t\t\t\ttext = text + s.name\n\t\t\telse:\n\t\t\t\ttext = text + '\\n' + s.name\n\t\tmime.setText( text )\n\t\tmime.setData( GII_MIME_ENTITY_DATA, entityGroupData.encode('utf-8') )\n\t\tif len( self.getSelection() ) == 1:\n\t\t\tent = self.getSelection()[ 0 ]\n\t\t\tscenePath = self.activeSceneNode.getPath()\n\t\t\turl = self.getApp().makeURL( 'scene', path = scenePath, entity_id = ent.__guid )\n\t\t\tmime.setUrls( [ QtCore.QUrl( url ) ] )\n\t\tclip.setMimeData( mime )\n\t\treturn True\n\n\tdef cutEntityToClipboard( self ):\n\t\tif not self.copyEntityToClipboard():\n\t\t\treturn False\n\t\tself.doCommand( 'scene_editor/remove_entity' )\n\t\treturn True\n\n\tdef pasteEntityFromClipboard( self, pos = 'into' ):\n\t\tclip = QtWidgets.QApplication.clipboard()\n\t\tmime = clip.mimeData()\n\t\tif mime.hasFormat( GII_MIME_ENTITY_DATA ):\n\t\t\tdata = mime.data( GII_MIME_ENTITY_DATA )\n\t\t\tself.doCommand( 'scene_editor/paste_entity',\n\t\t\t\tdata = str( data, encoding = 'utf-8' ),\n\t\t\t\tpos = pos\n\t\t\t)\n\n\t##----------------------------------------------------------------##\n\tdef onCopyComponent( self, targetComponent ):\n\t\tcomponentData = self.delegate.callMethod( 'editor', 'makeComponentCopyData', targetComponent )\n\t\tif not componentData: return False\n\t\tclip = QtWidgets.QApplication.clipboard()\n\t\tmime = QtCore.QMimeData()\n\t\tmime.setData( GII_MIME_COMPONENT_DATA, componentData.encode( 'utf-8' ) )\n\t\tclip.setMimeData( mime )\n\t\treturn True\n\n\tdef onPasteComponent( self, targetEntity, beforeComponent = None ):\n\t\tclip = QtWidgets.QApplication.clipboard()\n\t\tmime = clip.mimeData()\n\t\tif mime.hasFormat( GII_MIME_COMPONENT_DATA ):\n\t\t\tdata = mime.data( GII_MIME_COMPONENT_DATA )\n\t\t\tself.doCommand( 'scene_editor/paste_component',\n\t\t\t\ttargetEntity = targetEntity,\n\t\t\t\tdata = str( data, encoding = 'utf-8' ),\n\t\t\t\tbefore = beforeComponent\n\t\t\t)\n\t\telse:\n\t\t\talertMessage( 'no data', 'no component data' )\n\n\tdef onChangeComponentOrder( self, targetComponent, delta ):\n\t\tself.doCommand( 'scene_editor/change_component_order',\n\t\t\t\ttarget = targetComponent,\n\t\t\t\tdelta = delta\n\t\t\t)\n\t\t\n\n##----------------------------------------------------------------##\nclass RootGroupTitleButton( QtWidgets.QToolButton ):\n\tdef __init__( self, *args ):\n\t\tsuper( RootGroupTitleButton, self ).__init__( *args )\n\t\tself.setFixedHeight( 20 )\n\t\tself.setToolButtonStyle( Qt.ToolButtonTextBesideIcon )\n\t\tself.setIcon( getIcon( 'entity_group' ) )\n\t\tself.setText( '<DEFAULT>' )\n\t\tself.setSizePolicy( QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed )\n\n\nclass HeaderRootGroupWidget( QtWidgets.QWidget ):\n\tdef __init__( self, *args ):\n\t\tsuper( HeaderRootGroupWidget, self ).__init__( *args )\n\t\tself.owner = None\n\t\tlayout = QtWidgets.QHBoxLayout( self )\n\t\tlayout.setContentsMargins( 0 , 0 , 0 , 0 )\n\t\tlayout.setSpacing( 1 )\n\t\t\n\t\tself.buttonSoloVis = QtWidgets.QToolButton( self )\n\t\tself.buttonSoloOpacity = QtWidgets.QToolButton( self )\n\t\tself.buttonSoloEdit = QtWidgets.QToolButton( self )\n\n\t\tself.buttonSoloVis.setObjectName( 'ButtonSoloVis' )\n\t\tself.buttonSoloOpacity.setObjectName( 'ButtonSoloVis' )\n\t\tself.buttonSoloEdit.setObjectName( 'ButtonSoloEdit' )\n\n\t\tself.buttonSoloVis.setCheckable( True )\n\t\tself.buttonSoloOpacity.setCheckable( True )\n\t\tself.buttonSoloEdit.setCheckable( True )\n\t\tself.buttonSoloEdit.setChecked( True )\n\t\tself.buttonSoloVis.setText( 'Vis' )\n\t\tself.buttonSoloOpacity.setText( 'Opac' )\n\t\tself.buttonSoloEdit.setText( 'Edit' )\n\t\t\n\t\tself.buttonPanelGroup =\tRootGroupTitleButton( self )\n\t\t\n\t\tself.label = QtWidgets.QLabel( self )\n\t\tself.label.setText( ' Solo:')\n\n\t\tlayout.addWidget( self.buttonPanelGroup )\n\t\tlayout.addWidget( self.label )\n\t\tlayout.addWidget( self.buttonSoloVis )\n\t\tlayout.addWidget( self.buttonSoloOpacity )\n\t\tlayout.addWidget( self.buttonSoloEdit )\n\n\t\tself.buttonSoloVis.clicked.connect( self.onSoloVisChange )\n\t\tself.buttonSoloOpacity.clicked.connect( self.onSoloOpacityChange )\n\t\tself.buttonSoloEdit.clicked.connect( self.onSoloEditChange )\n\t\tself.buttonPanelGroup.clicked.connect( self.onShowPanelGroupManager )\n\t\tself.setFixedHeight( 20 )\n\n\tdef setButtonText( self, text ):\n\t\tself.buttonPanelGroup.setText( text )\n\n\tdef onShowPanelGroupManager( self ):\n\t\tpos = self.buttonPanelGroup.mapToGlobal(\n\t\t\tself.buttonPanelGroup.pos()\n\t\t)\n\t\tself.owner.groupManager.start( pos )\n\n\tdef onSoloVisChange( self ):\n\t\tsoloVis = self.buttonSoloVis.isChecked()\n\t\tself.owner.setGroupSoloVis( soloVis )\n\n\tdef onSoloOpacityChange( self ):\n\t\tsoloOpacity = self.buttonSoloOpacity.isChecked()\n\t\tself.owner.setGroupSoloOpacity( soloOpacity )\n\n\tdef onSoloEditChange( self ):\n\t\tsoloEdit = self.buttonSoloEdit.isChecked()\n\t\tself.owner.setGroupSoloEdit( soloEdit )\n\t\n\n##----------------------------------------------------------------##\nclass WindowAutoHideEventFilter( QObject ):\n\tdef eventFilter(self, obj, event):\n\t\te = event.type()\t\t\n\t\tif e == QEvent.KeyPress and event.key() == Qt.Key_Escape:\n\t\t\tobj.hide()\n\t\telif e == QEvent.WindowDeactivate:\n\t\t\tobj.hide()\n\n\t\treturn QObject.eventFilter( self, obj, event )\n\n\n##----------------------------------------------------------------##\nclass SceneGroupListView( GenericTreeWidget ):\n\tdef __init__( self, *args, **option ):\n\t\tsuper( SceneGroupListView, self ).__init__( *args, **option )\n\t\tself.setAttribute(Qt.WA_MacShowFocusRect, False)\n\n\tdef getOwner( self ):\n\t\treturn self.parent().getOwner()\n\n\tdef getHeaderInfo( self ):\n\t\treturn [('Scene Group', 170), ('State',30 ) ]\n\n\tdef getRootNode( self ):\n\t\treturn self.getOwner()\n\n\tdef getNodeParent( self, node ):\n\t\tif node == self.getOwner():\n\t\t\treturn None\n\t\treturn self.getOwner()\n\n\tdef getNodeChildren( self, node ):\n\t\tif node == self.getOwner():\n\t\t\treturn self.getOwner().getRootSceneGroups()\n\n\tdef updateItemContent( self, item, node, **option ):\n\t\tif node == self.getOwner():\n\t\t\treturn\n\t\titem.setIcon( 0, getIcon( 'entity_group' ) )\n\t\tif node._isDefault:\n\t\t\titem.setText( 0 , '<DEFAULT>' )\n\t\telse:\n\t\t\tname = node.getName( node )\n\t\t\titem.setText( 0, name )\n\n\tdef getItemFlags( self, node ):\n\t\tif node == self.getOwner(): return {}\n\t\tif node._isDefault:\n\t\t\treturn { 'editable' : False }\n\t\telse:\n\t\t\treturn { 'editable' : True }\n\n\tdef onItemActivated(self, item, col):\n\t\tres = self.getOwner().changeRootGroup( item.node, True )\n\t\tif not res: return\n\t\tself.parent().close()\n\t\tif res == 'same':\n\t\t\talertMessage( 'Already Openend', 'Scene group already selected' )\n\n##----------------------------------------------------------------##\nclass GroupManagerWidget( QtWidgets.QWidget ):\n\tdef __init__( self, *args ):\n\t\tsuper( GroupManagerWidget, self ).__init__( *args )\n\t\tself.setWindowFlags( Qt.Window | Qt.FramelessWindowHint )\n\t\t# self.setWindowModality( Qt.WindowModal )\n\t\tlayout = QtWidgets.QVBoxLayout( self )\n\t\tlayout.setContentsMargins( 5 , 5 , 5 , 5 )\n\t\tlayout.setSpacing( 5 )\n\n\t\tself.owner = False\n\t\tself.toolBar = toolBar = QtWidgets.QToolBar( self )\n\t\tself.tree = SceneGroupListView( self )\n\t\tself.toolBar.setFixedHeight( 20 )\n\t\t\n\t\tself.actionAdd = toolBar.addAction( 'Add' )\n\t\tself.actionRemove = toolBar.addAction( 'Remove' )\n\t\tself.actionRename = toolBar.addAction( 'Rename' )\n\t\t# self.actionClone = toolBar.addAction( 'Clone' )\n\n\t\tself.actionAdd.triggered.connect( self.onActionAdd )\n\t\tself.actionRemove.triggered.connect( self.onActionRemove )\n\t\tself.actionRename.triggered.connect( self.onActionRename )\n\t\t# self.actionAdd.triggered.connect( self.onActionClone )\n\t\t\n\t\tself.actionAdd.setIcon ( getIcon( 'add' ) )\n\t\tself.actionRemove.setIcon ( getIcon( 'remove' ) )\n\t\tself.actionRename.setIcon ( getIcon( 'pencil' ) )\n\t\t# self.actionClone.setIcon ( getIcon( 'clone' ) )\n\n\t\tself.titleBar = SimpleTitleBar( self )\n\t\tself.titleBar.setTitle( 'Scene Groups' )\n\n\t\tlayout.addWidget( self.titleBar )\n\t\tlayout.addWidget( self.toolBar )\n\t\tlayout.addWidget( self.tree )\n\n\t\tself.setMinimumSize( 200, 300 )\n\t\tself.setMaximumWidth( 250 )\n\n\n\n\tdef getOwner( self ):\n\t\treturn self.owner\n\n\tdef start( self, pos = None ):\n\t\tif not pos:\n\t\t\tpos = QtGui.QCursor.pos()\t\t\n\t\tself.move( pos )\n\t\trestrainWidgetToScreen( self )\n\t\tself.tree.rebuild()\n\t\tself.show()\n\t\tself.raise_()\n\n\tdef onActionAdd( self ):\n\t\tgroup = self.getOwner().addRootGroup()\n\t\tif group:\n\t\t\tself.tree.addNode( group )\t\t\t\n\t\t\tself.getOwner().changeRootGroup( group )\n\n\tdef onActionRemove( self ):\n\t\tfor node in self.tree.getSelection():\n\t\t\tif self.getOwner().removeRootGroup( node ):\n\t\t\t\tself.tree.rebuild()\n\t\t\tbreak\n\n\tdef onActionRename( self ):\n\t\tfor node in self.tree.getSelection():\n\t\t\tif self.getOwner().renameRootGroup( node ):\n\t\t\t\tself.tree.refreshNodeContent( node )\n\t\t\tbreak\n\n\tdef onActionClone( self ):\n\t\tpass\n\n\tdef event( self, ev ):\n\t\te = ev.type()\t\t\n\t\tif e == QEvent.KeyPress and ev.key() == Qt.Key_Escape:\n\t\t\tself.hide()\n\n\t\telif e == QEvent.WindowDeactivate:\n\t\t\tself.hide()\n\n\t\treturn super( GroupManagerWidget, self ).event( ev )\n\n\n##----------------------------------------------------------------##\ndef _sortEntity( a, b ):\n\treturn b._priority - a._priority\n\n# _BrushEntityNormal = QtGui.QBrush()\n# _BrushEntityLocked = QtGui.QBrush( QColorF( 0.6,0.6,0.6 ) )\n# _BrushEntityHidden = QtGui.QBrush( QColorF( 1,1,0 ) )\n# _BrushEntityPrefab = QtGui.QBrush( QColorF( .5,.5,1 ) )\n\n\nclass SceneGraphTreeItemDelegate(QtWidgets.QStyledItemDelegate):\n\t_textBrush = QBrush( QColor( '#dd5200' ) )\n\t_textPen = QPen( QColor( '#dddddd' ) )\n\t_textPenGroup = QPen( QColor( '#ada993' ) )\n\t_backgroundBrushHovered = QBrush( QColor( '#454768' ) )\n\t_backgroundBrushSelected = QBrush( QColor( '#515c84' ) )\n\t\n\tdef paint(self, painter, option, index):\n\t\tpainter.save()\n\t\tindex0 = index.sibling( index.row(), 0 )\n\t\tutype = index0.data( Qt.UserRole )\n\n\t\t# # set background color\n\t\tif option.state & QStyle.State_Selected:\n\t\t\tpainter.setPen ( Qt.NoPen )\n\t\t\tpainter.setBrush( SceneGraphTreeItemDelegate._backgroundBrushSelected )\n\t\t\tpainter.drawRect(option.rect)\n\t\telif option.state & QStyle.State_MouseOver:\n\t\t\tpainter.setPen ( Qt.NoPen )\n\t\t\tpainter.setBrush( SceneGraphTreeItemDelegate._backgroundBrushHovered )\n\t\t\tpainter.drawRect(option.rect)\n\n\t\trect = option.rect\n\t\ticon = QIcon( index.data( Qt.DecorationRole ) )\n\t\trect.adjust( 5, 0, 0, 0 )\n\t\tif icon and not icon.isNull():\n\t\t\ticon.paint( painter, rect, Qt.AlignLeft )\n\t\t\trect.adjust( 22, 0, 0, 0 )\n\t\ttext = index.data(Qt.DisplayRole)\n\t\tif utype == 1: #GROUP\n\t\t\tpainter.setPen( SceneGraphTreeItemDelegate._textPenGroup )\n\t\telse:\n\t\t\tpainter.setPen( SceneGraphTreeItemDelegate._textPen )\n\t\tpainter.drawText( rect, Qt.AlignLeft | Qt.AlignVCenter, text )\n\t\tpainter.restore()\n\n\nclass ReadonlySceneGraphTreeItemDelegate( SceneGraphTreeItemDelegate ):\n\tdef createEditor( *args ):\n\t\treturn None\n\n##----------------------------------------------------------------##\nclass SceneGraphTreeWidget( GenericTreeWidget ):\n\tdef __init__( self, *args, **kwargs ):\n\t\tsuper( SceneGraphTreeWidget, self ).__init__( *args, **kwargs )\n\t\tself.syncSelection = True\n\t\tself.adjustingRange = False\n\t\tself.verticalScrollBar().rangeChanged.connect( self.onScrollRangeChanged )\n\t\tself.setIndentation( 13 )\n\n\tdef getHeaderInfo( self ):\n\t\treturn [('Entity',240), ('V',27 ), ('L',27 ), ( 'Layer', -1 ) ]\n\n\tdef getReadonlyItemDelegate( self ):\n\t\treturn ReadonlySceneGraphTreeItemDelegate( self )\n\n\tdef getDefaultItemDelegate( self ):\n\t\treturn SceneGraphTreeItemDelegate( self )\n\n\tdef getRootNode( self ):\n\t\treturn self.module.getActiveSceneRootGroup()\n\n\t# def mimeData( self, items ):\n\t# \t#TODO: scene source\n\t# \treturn makeSceneGraphMimeData( 'main', [ item.node for item in items ] )\n\n\tdef saveFoldState( self ):\n\t\t#TODO: other state?\n\t\tresult = {}\n\t\tfor node, item in self.nodeDict.items():\n\t\t\tif not item: continue\n\t\t\tguid = node['__guid']\n\t\t\texpanded = item.isExpanded()\n\t\t\tresult[ guid ] = { 'expanded': expanded }\n\t\treturn result\n\n\tdef loadFoldState( self, data ):\n\t\tfor node, item in self.nodeDict.items():\n\t\t\tif not item: continue\n\t\t\tguid = node['__guid']\n\t\t\tstate = data.get( guid )\n\t\t\tif state:\n\t\t\t\titem.setExpanded( state['expanded'] )\n\n\tdef saveTreeStates( self ):\n\t\tpass\n\n\tdef loadTreeStates( self ):\n\t\tpass\n\n\tdef getNodeParent( self, node ): # reimplemnt for target node\t\n\t\tp = node.getParentOrGroup( node )\n\t\tif p and not p.FLAG_EDITOR_OBJECT :\n\t\t\treturn p\n\t\treturn None\n\n\tdef getNodeChildren( self, node ):\n\t\tif isMockInstance( node, 'EntityGroup' ):\n\t\t\toutput = []\n\t\t\t#groups\n\t\t\tfor group in node.childGroups:\n\t\t\t\toutput.append( group )\n\t\t\t#entities\n\t\t\tfor ent in node.entities:\n\t\t\t\tif ( not ent.parent ) and ( not ( ent.FLAG_EDITOR_OBJECT or ent.FLAG_INTERNAL ) ):\n\t\t\t\t\toutput.append( ent )\n\t\t\t# output = sorted( output, key = cmp_to_key( _sortEntity ) )\n\t\t\treturn output\n\n\t\telse: #entity\n\t\t\toutput = []\n\t\t\tfor ent in node.children:\n\t\t\t\tif not ( ent.FLAG_EDITOR_OBJECT or ent.FLAG_INTERNAL ):\n\t\t\t\t\toutput.append( ent )\n\t\t\t# output = sorted( output, key = cmp_to_key( _sortEntity ) )\n\t\t\treturn output\n\n\tdef compareNodes( self, node1, node2 ):\n\t\treturn node1._priority >= node2._priority\n\n\tdef createItem( self, node ):\n\t\treturn SceneGraphTreeItem()\n\n\tdef updateHeaderItem( self, item, col, info ):\n\t\tif info[0] == 'V':\n\t\t\titem.setText( col, '')\n\t\t\titem.setIcon( col, getIcon( 'entity_vis' ) )\n\t\telif info[0] == 'L':\n\t\t\titem.setText( col, '')\n\t\t\titem.setIcon( col, getIcon( 'entity_lock' ) )\n\n\tdef getEntityType( self, obj ):\n\t\tif obj['FLAG_PROTO_SOURCE']:\n\t\t\tprotoState = 'proto'\n\t\telif obj['PROTO_INSTANCE_STATE']:\n\t\t\tprotoState = 'instance-proto'\n\t\telif obj[ '__prefabId' ]:\n\t\t\tprotoState = 'instance-prefab'\n\t\telif obj['__proto_history']:\n\t\t\tprotoState = 'instance-sub'\n\t\telse:\n\t\t\tprotoState = False\n\n\t\tif isMockInstance( obj, 'ProtoContainer' ):\n\t\t\tcategory = 'container-proto'\n\t\telif isMockInstance( obj, 'PrefabContainer' ):\n\t\t\tcategory = 'container-prefab'\n\t\telif isMockInstance( obj, 'UIView' ):\n\t\t\tcategory = 'uiview'\n\t\telif isMockInstance( obj, 'UIWidget' ):\n\t\t\tcategory = 'uiwidget'\n\t\telse:\n\t\t\tcategory = 'normal'\n\n\t\treturn ( category, protoState )\n\n\n\tdef updateItemContent( self, item, node, **option ):\n\t\tname = None\n\t\titem.setData( 0, Qt.UserRole, 0 )\n\n\t\tif isMockInstance( node, 'EntityGroup' ):\n\t\t\titem.setText( 0, node.name or '<unnamed>' )\n\t\t\titem.setIcon( 0, getIcon('entity_group') )\n\t\t\titem.setData( 0, Qt.UserRole, 1 )\n\n\t\telif isMockInstance( node, 'Entity' ):\n\t\t\tnode.forceUpdate( node )\n\t\t\tcategory, protoState = self.getEntityType( node )\n\t\t\t\n\t\t\tif protoState:\n\t\t\t\ticonPath = 'entity/%s.%s' % ( category, protoState )\n\t\t\t\ticonFallback = 'entity/normal.%s' % protoState \n\t\t\telse:\n\t\t\t\ticonPath = 'entity/%s' % category\n\t\t\t\ticonFallback = 'entity/normal'\n\n\t\t\titem.setIcon( 0, getIcon( iconPath, iconFallback ) )\n\t\t\titem.setText( 0, node.name or '<unnamed>' )\n\t\n\t\t\tlayerName = node.getLayer( node )\n\t\t\tif isinstance( layerName, tuple ):\n\t\t\t\titem.setText( 3, '????' )\n\t\t\telse:\n\t\t\t\titem.setText( 3, layerName )\n\n\t\t#update icon\n\t\tif node.isVisible( node ):\n\t\t\titem.setIcon( 1, getIcon( 'entity_vis' ) )\n\t\telif node.isLocalVisible( node ):\n\t\t\titem.setIcon( 1, getIcon( 'entity_parent_invis' ) )\n\t\telse:\n\t\t\titem.setIcon( 1, getIcon( 'entity_invis' ) )\n\n\t\tif node.isEditLocked( node ):\n\t\t\tif node.isLocalEditLocked( node ):\n\t\t\t\titem.setIcon( 2, getIcon( 'entity_lock' ) )\n\t\t\telse:\n\t\t\t\titem.setIcon( 2, getIcon( 'entity_parent_lock' ) )\n\t\telse:\n\t\t\titem.setIcon( 2, getIcon( 'entity_nolock' ) )\n\n\t\t\t\n\tdef onItemSelectionChanged(self):\n\t\tif not self.syncSelection: return\n\t\titems = self.selectedItems()\n\t\tif items:\n\t\t\tselections=[item.node for item in items]\n\t\t\tself.module.changeSelection(selections)\n\t\telse:\n\t\t\tself.module.changeSelection(None)\n\n\tdef dropEvent( self, ev ):\t\t\n\t\tp = self.dropIndicatorPosition()\n\t\tpos = False\n\t\tif p == QtWidgets.QAbstractItemView.OnItem: #reparent\n\t\t\tpos = 'on'\n\t\telif p == QtWidgets.QAbstractItemView.AboveItem:\n\t\t\tpos = 'above'\n\t\telif p == QtWidgets.QAbstractItemView.BelowItem:\n\t\t\tpos = 'below'\n\t\telse:\n\t\t\tpos = 'viewport'\n\n\t\ttarget = self.itemAt( ev.pos() )\n\t\tok = False\n\t\tif pos == 'on':\n\t\t\tok = self.module.doCommand( 'scene_editor/reparent_entity', target = target.node )\n\t\telif pos == 'viewport':\n\t\t\tok = self.module.doCommand( 'scene_editor/reparent_entity', target = 'root' )\n\t\telif pos == 'above' or pos == 'below':\n\t\t\tok = self.module.doCommand( 'scene_editor/reparent_entity', target = target.node, mode = 'sibling' )\n\n\t\tif ok:\n\t\t\tsuper( GenericTreeWidget, self ).dropEvent( ev )\n\t\telse:\n\t\t\tev.setDropAction( Qt.IgnoreAction )\n\n\tdef onDeletePressed( self ):\n\t\tself.syncSelection = False\n\t\titem0 = self.currentItem()\n\t\titem1 = self.itemBelow( item0 )\n\t\tself.module.doCommand( 'scene_editor/remove_entity' )\n\t\tif item1:\n\t\t\tself.setFocusedItem( item1 )\n\t\tself.syncSelection = True\n\t\tself.onItemSelectionChanged()\n\n\tdef onItemChanged( self, item, col ):\n\t\tself.module.renameEntity( item.node, item.text(0) )\n\n\tdef onClipboardCopy( self ):\n\t\tself.module.copyEntityToClipboard()\n\t\treturn True\n\n\tdef onClipboardCut( self ):\n\t\tself.module.cutEntityToClipboard()\n\t\treturn True\n\n\tdef onClipboardPaste( self ):\n\t\tself.module.pasteEntityFromClipboard()\n\t\treturn True\n\n\tdef onScrollRangeChanged( self, min, max ):\n\t\tif self.adjustingRange: return\n\t\tself.adjustingRange = True\n\t\tif max > min:\n\t\t\tpageStep = self.verticalScrollBar().pageStep()\n\t\t\tself.verticalScrollBar().setRange( min, max + 1 )\n\t\tself.adjustingRange = False\n\n\tdef mousePressEvent( self, ev ):\n\t\tif ev.button() == Qt.LeftButton:\n\t\t\titem = self.itemAt( ev.pos() )\n\t\t\tif item:\n\t\t\t\tcol = self.columnAt( ev.pos().x() )\n\t\t\t\tif col == 1:\n\t\t\t\t\tnode = self.getNodeByItem( item )\n\t\t\t\t\tself.module.doCommand( 'scene_editor/toggle_entity_visibility', target = node )\n\t\t\t\t\tself.refreshNodeContent( node, updateChildren = True )\n\t\t\t\t\treturn\n\t\t\t\telif col == 2:\n\t\t\t\t\tnode = self.getNodeByItem( item )\n\t\t\t\t\tself.module.doCommand( 'scene_editor/toggle_entity_lock', target = node )\n\t\t\t\t\tself.refreshNodeContent( node, updateChildren = True )\n\t\t\t\t\treturn\n\t\t\t\n\t\treturn super( SceneGraphTreeWidget, self ).mousePressEvent( ev )\n\n\n##----------------------------------------------------------------##\n#TODO: allow sort by other column\nclass SceneGraphTreeItem(QtWidgets.QTreeWidgetItem):\n\tdef __lt__(self, other):\n\t\tnode0 = self.node\n\t\tnode1 = hasattr(other, 'node') and other.node or None\n\t\tif not node1:\n\t\t\treturn True\n\t\tif not node0:\n\t\t\treturn False\n\t\ttree = self.treeWidget()\n\t\torder = tree.sortOrder()\n\t\n\t\tgroup0 = isMockInstance( node0, 'EntityGroup' )\n\t\tgroup1 = isMockInstance( node1, 'EntityGroup' )\n\t\tif group0 != group1:\n\t\t\tif order == 0:\n\t\t\t\tif group0: return True\n\t\t\t\tif group1: return False\n\t\t\telse:\n\t\t\t\tif group0: return False\n\t\t\t\tif group1: return True\n\t\t\n\t\tproto0 = node0[ 'FLAG_PROTO_SOURCE' ]\n\t\tproto1 = node1[ 'FLAG_PROTO_SOURCE' ]\n\t\tif proto0 != proto1:\n\t\t\tif order == 0:\n\t\t\t\tif proto0: return True\n\t\t\t\tif proto1: return False\n\t\t\telse:\n\t\t\t\tif proto0: return False\n\t\t\t\tif proto1: return True\n\n\t\tif isMockInstance( node0, 'UIWidget' ) and isMockInstance( node1, 'UIWidget' ):\n\t\t\tz0 = node0.zorder\n\t\t\tz1 = node1.zorder\n\t\t\tif z0 != z1:\n\t\t\t\tif order == 0:\n\t\t\t\t\treturn z0 < z1\n\t\t\t\telse:\n\t\t\t\t\treturn z0 > z1\n\t\treturn super( SceneGraphTreeItem, self ).__lt__( other )\n\n##----------------------------------------------------------------##\nSceneGraphEditor().register()\n\n##----------------------------------------------------------------##\ndef sceneObjectSearchEnumerator( typeId, context, option ):\n\tif not context in ['scene', 'all']: return None\n\tmodelMgr = ModelManager.get()\n\tobjects = modelMgr.enumerateObjects( typeId, context, option )\n\tif not objects: return None\n\tresult = []\n\tfor obj in objects:\n\t\tname = modelMgr.getObjectRepr( obj )\n\t\ttypeName = modelMgr.getObjectTypeRepr( obj )\n\t\tentry = ( obj, name, typeName, None )\n\t\tresult.append( entry )\n\treturn result\n\ndef entityNameSearchEnumerator( typeId, context, option ):\n\tif not context in [ 'entity_creation' ] : return None\n\tregistry = _MOCK.getEntityRegistry()\n\tresult = []\n\tfor name in sorted( registry.keys() ):\n\t\tentry = ( name, name, 'Entity', None )\n\t\tresult.append( entry )\n\treturn result\n\ndef componentNameSearchEnumerator( typeId, context, option ):\n\tif not context in [ 'component_creation' ] : return None\n\tregistry = _MOCK.getComponentRegistry()\n\tresult = []\n\tfor name in sorted( registry.keys() ):\n\t\tentry = ( name, name, 'Entity', None )\n\t\tresult.append( entry )\n\treturn result\n\t\t\ndef layerNameSearchEnumerator( typeId, context, option ):\n\tif not context in [ 'scene_layer' ] : return None\n\tlayers = _MOCK.game.layers\n\tresult = []\n\tfor name in sorted( [ layer.name for layer in layers.values() ] ):\n\t\tif name == '_GII_EDITOR_LAYER': continue\n\t\tentry = ( name, name, 'Layer', None )\n\t\tresult.append( entry )\n\treturn result\n\n##----------------------------------------------------------------##\nclass RemoteCommandGetSceneAutoCompletion( RemoteCommand ):\n\tname = 'get_scene_auto_completion'\n\tdef run( self, *args ):\n\t\tresult = []\n\t\tif 'entity_full' in args:\n\t\t\tresult += app.getModule( 'scenegraph_editor' ).getAutoCompletion( True )\n\t\telif 'entity' in args:\n\t\t\tresult += app.getModule( 'scenegraph_editor' ).getAutoCompletion( False )\n\t\t\n\t\tif 'scene' in args:\n\t\t\tlib = app.getAssetLibrary()\n\t\t\tscenes = lib.enumerateAsset( 'scene' )\n\t\t\tresult += [ node.getPath() for node in scenes ]\n\n\t\tif 'quest' in args:\n\t\t\tresult += [ n for n in _MOCK_EDIT.listQuestNodeNames().values() ]\n\n\t\tif result:\n\t\t\treturn '\\n'.join( result )\n\t\telse:\n\t\t\treturn None\n\n\n##----------------------------------------------------------------##\n@slot( 'app.open_url' )\ndef URLSceneHandler( url ):\n\tif url.get( 'base', None ) != 'scene': return\n\tdata = url['data']\n\tpath = data.get( 'path', None )\n\tif not path:\n\t\tprint( 'no scene path' )\n\t\treturn\n\tapp.getModule( 'asset_browser' ).locateAsset( path )\n\tapp.getModule( 'scenegraph_editor' ).openSceneByPath( path )\n\t\n\t#TODO: focus target entity/component\n\tentityGUID = data.get( 'entity_id', None )\n\tif entityGUID:\n\t\tdef callback():\n\t\t\tapp.getModule( 'scenegraph_editor' ).locateEntityByGUID( entityGUID )\n\n\t\tapp.callLater( 0.2, callback )\n\n\t#TODO: camera\n\tcameraData = data.get( 'camera', None )\n\tif cameraData:\t\t\n\t\tapp.getModule( 'scene_view' ).loadCameraState( cameraData )\n\t\n\n\n","sub_path":"lib/mock/SceneGraphEditor/SceneGraphEditor.py","file_name":"SceneGraphEditor.py","file_ext":"py","file_size_in_byte":65126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127991359","text":"import matplotlib.pyplot as plt\r\nfrom scipy.io import wavfile # get the api\r\nfrom scipy.fftpack import fft\r\nfrom pylab import *\r\n\r\ndef f(filename):\r\n # song files are in ogg... we need it to be in wav.\r\n fs, data = wavfile.read(filename) \r\n \r\n # songs have multiple channels, but we only need one channel\r\n a = data.T[0]\r\n \r\n # this is 8-bit track, b is now normalized on [-1,1)\r\n #b=[(ele/2**16)*2-1 for ele in a] \r\n\r\n # create a list of complex number\r\n c = fft(a)\r\n\r\n # only need half of the fft list (because the internet says so)\r\n d = len(c)//2 \r\n\r\n #bam, it is plotted and saved. \r\n #plt.plot(abs(c[:(d-1)]),'r')\r\n #savefig(filename+'.png',bbox_inches='tight')\r\n\t\r\n return c\r\n\r\nguitar = f(\"auldlangguitar.wav\")\r\nviolin = f(\"auldlangviolin.wav\")\r\nharmon = f(\"auldlangharmonica.wav\")\r\ncombine= f(\"combined.wav\")\r\ncut = combine[:-14]\r\ncombined2 = guitar + violin\r\n\r\nplt.plot(np.abs(guitar), 'r')\r\n#plt.show()\r\nsavefig('guitarplot.png',bbox_inches='tight')\r\n\r\ngc = np.dot(guitar, combined2)\r\nvc = np.dot(violin, combined2)\r\nhc = np.dot(harmon, combined2)\r\n\r\nng = guitar #/ np.linalg.norm(guitar)\r\nnv = violin #/ np.linalg.norm(violin)\r\nnh = harmon #/ np.linalg.norm(harmon)\r\nnc = combined2 #/ np.linalg.norm(cut)\r\n\r\na = np.column_stack((ng, nv, nh))\r\n\r\nx, res, rank, s = np.linalg.lstsq(a, nc)\r\nplt.plot(np.abs(ng * x[0]), 'r')\r\n#plt.show()\r\nsavefig('decompguitarplot.png',bbox_inches='tight')\r\ndecompGuitar = np.fft.ifft(ng * 1 + nv *1)\r\nprint(\"X\\n\")\r\nprint(x)\r\n\r\n\r\nprint(\"decomp real\")\r\nprint(np.real(decompGuitar))\r\ntest = np.fft.ifft(guitar)\r\n\r\ndecompreal = (decompGuitar)\r\ndecompreal = decompreal #/ np.min(np.abs(decompreal[np.nonzero(decompreal)]))\r\n\r\n\r\norigfs, origdata = wavfile.read(\"auldlangguitar.wav\")\r\nb = np.column_stack((decompGuitar.astype(origdata.dtype), decompGuitar.astype(origdata.dtype)))\r\nwavfile.write(\"decompguitar.wav\", origfs, b)\r\nnp.savetxt(\"guitar.csv\", test.astype(uint8) , delimiter= \",\")\r\nnp.savetxt(\"combined.csv\", combine, delimiter= \",\")\r\nnp.savetxt(\"channel2.csv\", decompreal.astype(uint8), delimiter= \",\")\r\nprint(\"decomp orig\")\r\nprint(np.min(decompreal[np.nonzero(decompreal)]))\r\n","sub_path":"fft_prototype.py","file_name":"fft_prototype.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"34504532","text":"\"\"\"\nMask R-CNN\nTrain on the toy Balloon dataset and implement color splash effect.\n\nCopyright (c) 2018 Matterport, Inc.\nLicensed under the MIT License (see LICENSE for details)\nWritten by Waleed Abdulla\nEdit by HHQ\n\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\n\nimport cv2\nimport colorsys\nimport random\nfrom skimage.measure import find_contours\nfrom matplotlib.patches import Polygon\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches, lines\nimport IPython.display\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import model as modellib, utils\n\n# Path to trained weights file\nCOCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n\n# Directory to save logs and model checkpoints, if not provided\n# through the command line argument --logs\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n############################################################\n# Configurations\n############################################################\n\n\nclass BalloonConfig(Config):\n \"\"\"Configuration for training on the toy dataset.\n Derives from the base Config class and overrides some values.\n \"\"\"\n # Give the configuration a recognizable name\n NAME = \"people\"\n\n # We use a GPU with 12GB memory, which can fit two images.\n # Adjust down if you use a smaller GPU. 2\n IMAGES_PER_GPU = 1\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 1 # Background + balloon\n\n # Number of training steps per epoch 100\n STEPS_PER_EPOCH = 100\n\n # Skip detections with < 90% confidence\n #DETECTION_MIN_CONFIDENCE = 0.9\n\n #BACKBONE = \"resnet50\"\n\n #IMAGE_RESIZE_MODE = \"crop\"\n IMAGE_MIN_DIM = 448\n IMAGE_MAX_DIM = 640\n #TRAIN_ROIS_PER_IMAGE =150\n #MAX_GT_INSTANCES = 200\n #POST_NMS_ROIS_TRAINING = 2500\n #RPN_ANCHOR_RATIOS = [0.35, 1, 2]\n\n\n\n############################################################\n# Dataset\n############################################################\n\nclass BalloonDataset(utils.Dataset):\n\n def load_balloon(self, dataset_dir, subset):\n \"\"\"Load a subset of the Balloon dataset.\n dataset_dir: Root directory of the dataset.\n subset: Subset to load: train or val\n \"\"\"\n # Add classes. We have only one class to add.\n self.add_class(\"balloon\", 1, \"balloon\")\n\n # Train or validation dataset?\n assert subset in [\"train\", \"val\"]\n dataset_dir = os.path.join(dataset_dir, subset)\n\n # Load annotations\n # VGG Image Annotator (up to version 1.6) saves each image in the form:\n # { 'filename': '28503151_5b5b7ec140_b.jpg',\n # 'regions': {\n # '0': {\n # 'region_attributes': {},\n # 'shape_attributes': {\n # 'all_points_x': [...],\n # 'all_points_y': [...],\n # 'name': 'polygon'}},\n # ... more regions ...\n # },\n # 'size': 100202\n # }\n # We mostly care about the x and y coordinates of each region\n # Note: In VIA 2.0, regions was changed from a dict to a list.\n annotations = json.load(open(os.path.join(dataset_dir, \"via_region_data.json\")))\n annotations = list(annotations.values()) # don't need the dict keys\n\n # The VIA tool saves images in the JSON even if they don't have any\n # annotations. Skip unannotated images.\n annotations = [a for a in annotations if a['regions']]\n\n # Add images\n for a in annotations:\n # Get the x, y coordinaets of points of the polygons that make up\n # the outline of each object instance. These are stores in the\n # shape_attributes (see json format above)\n # The if condition is needed to support VIA versions 1.x and 2.x.\n if type(a['regions']) is dict:\n polygons = [r['shape_attributes'] for r in a['regions'].values()]\n else:\n polygons = [r['shape_attributes'] for r in a['regions']] \n\n # load_mask() needs the image size to convert polygons to masks.\n # Unfortunately, VIA doesn't include it in JSON, so we must read\n # the image. This is only managable since the dataset is tiny.\n image_path = os.path.join(dataset_dir, a['filename'])\n image = skimage.io.imread(image_path)\n height, width = image.shape[:2]\n\n self.add_image(\n \"balloon\",\n image_id=a['filename'], # use file name as a unique image id\n path=image_path,\n width=width, height=height,\n polygons=polygons)\n\n def load_mask(self, image_id):\n \"\"\"Generate instance masks for an image.\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n \"\"\"\n # If not a balloon dataset image, delegate to parent class.\n image_info = self.image_info[image_id]\n if image_info[\"source\"] != \"balloon\":\n return super(self.__class__, self).load_mask(image_id)\n\n # Convert polygons to a bitmap mask of shape\n # [height, width, instance_count]\n info = self.image_info[image_id]\n mask = np.zeros([info[\"height\"], info[\"width\"], len(info[\"polygons\"])],\n dtype=np.uint8)\n for i, p in enumerate(info[\"polygons\"]):\n # Get indexes of pixels inside the polygon and set them to 1\n rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])\n mask[rr, cc, i] = 1\n\n # Return mask, and array of class IDs of each instance. Since we have\n # one class ID only, we return an array of 1s\n return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)\n\n def image_reference(self, image_id):\n \"\"\"Return the path of the image.\"\"\"\n info = self.image_info[image_id]\n if info[\"source\"] == \"balloon\":\n return info[\"path\"]\n else:\n super(self.__class__, self).image_reference(image_id)\n\n\ndef train(model):\n \"\"\"Train the model.\"\"\"\n # Training dataset.\n dataset_train = BalloonDataset()\n dataset_train.load_balloon(args.dataset, \"train\")\n dataset_train.prepare()\n\n # Validation dataset\n dataset_val = BalloonDataset()\n dataset_val.load_balloon(args.dataset, \"val\")\n dataset_val.prepare()\n\n # *** This training schedule is an example. Update to your needs ***\n # Since we're using a very small dataset, and starting from\n # COCO trained weights, we don't need to train too long. Also,\n # no need to train all layers, just the heads should do it.\n print(\"Training network heads\")\n model.train(dataset_train, dataset_val,\n learning_rate=config.LEARNING_RATE,\n epochs=30,\n layers='heads')\n\n\"\"\"\ndef color_splash(image, mask):\n #Apply color splash effect.\n #image: RGB image [height, width, 3]\n #mask: instance segmentation mask [height, width, instance count]\n\n #Returns result image.\n \n # Make a grayscale copy of the image. The grayscale copy still\n # has 3 RGB channels, though.\n gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255\n # Copy color pixels from the original color image where mask is set\n if mask.shape[-1] > 0:\n # We're treating all instances as one, so collapse the mask into one layer\n mask = (np.sum(mask, -1, keepdims=True) >= 1)\n splash = np.where(mask, image, gray).astype(np.uint8)\n else:\n splash = gray.astype(np.uint8)\n return splash\n\"\"\"\n\"\"\"\n==================VISUALIZE==================\n\"\"\"\nrandom.seed(0)\nN=90\nbrightness = 1.0\nhsv = [(i / N, 1, brightness) for i in range(N)]\nrandom.shuffle(hsv)\n\ndef apply_mask(image, mask, color, alpha=0.5):\n \"\"\"Apply the given mask to the image.\n \"\"\"\n for c in range(3):\n image[:, :, c] = np.where(mask == 1,\n image[:, :, c] *\n (1 - alpha) + alpha * color[c] * 255,\n image[:, :, c])\n return image\n\ndef class_color(id,prob):\n _hsv = list(hsv[id])\n # _hsv[2]=random.uniform(0.8, 1)\n _hsv[2]=prob\n color = colorsys.hsv_to_rgb(*_hsv)\n return color\n\ndef random_colors(N, bright=True):\n \"\"\"\n Generate random colors.\n To get visually distinct colors, generate them in HSV space then\n convert to RGB.\n \"\"\"\n brightness = 1.0 if bright else 0.7\n hsv = [(i / N, 1, brightness) for i in range(N)]\n colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))\n random.shuffle(colors)\n return colors\n\n\ndef draw_instances(image, boxes, masks, class_ids, class_names,\n scores=None, title=\"\",\n figsize=(16, 16), ax=None):\n \"\"\"\n boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.\n masks: [num_instances, height, width]\n class_ids: [num_instances]\n class_names: list of class names of the dataset\n scores: (optional) confidence scores for each box\n figsize: (optional) the size of the image.\n \"\"\"\n # Number of instances\n N = boxes.shape[0]\n if not N:\n print(\"\\n*** No instances to display *** \\n\")\n else:\n assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]\n\n # if not ax:\n # _, ax = plt.subplots(1, figsize=figsize)\n\n # Generate random colors\n colors = random_colors(N)\n\n # Show area outside image boundaries.\n height, width = image.shape[:2]\n\n masked_image = image.copy()\n for i in range(N):\n class_id = class_ids[i]\n score = scores[i] if scores is not None else None\n # color = colors[i]\n #color = class_color(class_id,score*score*score*score)\n color = color = (255/255, 48/255, 48/255)\n # Bounding box\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in image cropping.\n continue\n y1, x1, y2, x2 = boxes[i]\n # p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n # alpha=0.7, linestyle=\"dashed\",\n # edgecolor=color, facecolor='none')\n\n cv2.rectangle(masked_image, (x1, y1),(x2, y2), [int(x*255) for x in (color)],2)#4\n\n # Label\n #label = class_names[class_id]\n label = \"smoking\"\n x = random.randint(x1, (x1 + x2) // 2)\n caption = \"%s %d%%\"%(label, int(score*100)) if score else label\n # ax.text(x1, y1 + 8, caption,\n # color='w', size=11, backgroundcolor=\"none\")\n\n yyy=y1 -16\n if yyy <0:\n yyy=0\n\n cv2.putText(masked_image, caption,\n (x1, yyy), cv2.FONT_HERSHEY_SIMPLEX, 0.8, #1.5\n [int(x*255) for x in (color)],2)#4\n # Mask\n mask = masks[:, :, i]\n masked_image = apply_mask(masked_image, mask, color)\n\n # Mask Polygon\n # Pad to ensure proper polygons for masks that touch image edges.\n padded_mask = np.zeros(\n (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)\n padded_mask[1:-1, 1:-1] = mask\n contours = find_contours(padded_mask, 0.5)#0.5\n for verts in contours:\n # Subtract the padding and flip (y, x) to (x, y)\n verts = np.fliplr(verts) - 1\n p = Polygon(verts, facecolor=\"none\", edgecolor=color)\n # ax.add_patch(p)\n pts = np.array(verts.tolist(), np.int32)\n pts = pts.reshape((-1,1,2))\n cv2.polylines(masked_image,[pts],True,[int(x*255) for x in (color)],2)#4\n return masked_image.astype(np.uint8)\n\n\n\ndef detect_and_color_splash(model, image_path=None, video_path=None):\n assert image_path or video_path\n\n show = np.zeros([2,2],dtype = int)\n class_names = ['BG', 'people']\n\n # Image or video?\n if image_path:\n # Run model detection and generate the color splash effect\n print(\"Running on {}\".format(args.image))\n # Read image\n image = skimage.io.imread(args.image)\n # Detect objects\n r = model.detect([image], verbose=1)[0]\n print(\"Number of people {}\".format(r['rois'].shape[0]))\n # Color splash\n #splash = color_splash(image, r['masks'])\n splash=draw_instances(image,r['rois'],r['masks'],r['class_ids'],BalloonConfig.NAME,r['scores'],BalloonConfig.NAME)\n # Save output\n file_name = \"splash_{:%Y%m%dT%H%M%S}.png\".format(datetime.datetime.now())\n skimage.io.imsave(file_name, splash)\n #不用渲染图片\n elif video_path:\n import cv2\n # Video capture\n vcapture = cv2.VideoCapture(video_path)\n width = int(vcapture.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vcapture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = vcapture.get(cv2.CAP_PROP_FPS)\n\n # Define codec and create video writer\n file_name = \"splash_{:%Y%m%dT%H%M%S}.avi\".format(datetime.datetime.now())\n vwriter = cv2.VideoWriter(file_name,\n cv2.VideoWriter_fourcc(*'MJPG'),\n fps, (width, height))\n\n count = 1\n success = True\n while success:\n #print(\"frame: \", count)\n # Read next image\n success, image = vcapture.read()\n if success:\n if count % 7500 == 0:\n # OpenCV returns images as BGR, convert to RGB\n image = image[..., ::-1]\n # Detect objects\n r = model.detect([image], verbose=0)[0]\n # Color splash\n num = r['rois'].shape[0]\n contn = count//7500\n if num <= 5:\n show = np.concatenate((show,[[contn,num+2]]),axis=0)\n elif num <= 10:\n show = np.concatenate((show,[[contn,num+4]]),axis=0)\n elif num <= 15:\n show = np.concatenate((show,[[contn,num+6]]),axis=0)\n elif num <= 20:\n show =np.concatenate((show,[[contn,num+10]]),axis=0)\n print(show)\n\n count += 1\n vwriter.release()\n # matplot(np.delete(show,[0,1],axis=0))\n # elif video_path:\n # import cv2\n # # Video capture\n # vcapture = cv2.VideoCapture(video_path)\n # width = int(vcapture.get(cv2.CAP_PROP_FRAME_WIDTH))\n # height = int(vcapture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n # fps = vcapture.get(cv2.CAP_PROP_FPS)\n\n # # Define codec and create video writer\n # file_name = \"splash_{:%Y%m%dT%H%M%S}.avi\".format(datetime.datetime.now())\n # vwriter = cv2.VideoWriter(file_name,\n # cv2.VideoWriter_fourcc(*'MJPG'),\n # fps, (width, height))\n\n # count = 1\n # success = True\n # while success:\n # #print(\"frame: \", count)\n # # Read next image\n # success, image = vcapture.read()\n # if success:\n # # OpenCV returns images as BGR, convert to RGB\n # image = image[..., ::-1]\n # # Detect objects\n # r = model.detect([image], verbose=0)[0]\n # # Color splash\n\n # if count % 1500 == 0:\n\t # num = r['rois'].shape[0]\n\t # contn = count//1500\n\t # if num <= 5:\n\t # \tshow = np.concatenate((show,[[contn,num+2]]),axis=0)\n\t # elif num <= 10:\n\t # \tshow = np.concatenate((show,[[contn,num+4]]),axis=0)\n\t # elif num <= 15:\n\t # \tshow = np.concatenate((show,[[contn,num+6]]),axis=0)\n\t # elif num <= 20:\n\t # \tshow =np.concatenate((show,[[contn,num+10]]),axis=0)\n\t # print(show)\n\n # splash = draw_instances(image,r['rois'],r['masks'],r['class_ids'],BalloonConfig.NAME,r['scores'],BalloonConfig.NAME)\n # # RGB -> BGR to save image to video\n # splash = splash[..., ::-1]\n # # Add image to video writer\n # vwriter.write(splash)\n # count += 1\n # vwriter.release()\n # matplot(np.delete(show,[0,1],axis=0))\n # print(\"Saved to \", file_name)\n\n\n# def matplot(show):\n# \tbarlist=plt.bar(show[:,0],show[:,1])\n\n# \tplt.xlim(0,show.shape[0]+1)\n# \tplt.ylim(0,40)\n\n# \tplt.xlabel(\"Time\")\n# \tplt.ylabel('Num of people')\n\n# \tplt.xticks(show[:,0])\n# \tplt.yticks([0,5,10,15,20,25,30,35,40])\n\n# \tfor x,y in zip(show[:,0],show[:,1]):\n# \t\tprint((x,y))\n# \t\tif y <= 10 :\n# \t\t\tbarlist[x-1].set_color('limegreen')\n# \t\telif y <=20 :\n# \t\t\tbarlist[x-1].set_color('dodgerblue')\n# \t\telif y <= 30 :\n# \t\t\tbarlist[x-1].set_color('orange')\n# \t\telse:\n# \t\t\tbarlist[x-1].set_color('m')\n\n# \t\tplt.text(x,y+0.5,'%.0f'%y,ha='center',va='bottom')\n\n# \tplt.savefig(\"plot.png\")\n# \tplt.show()\n\n\"\"\"\n==============PLOT=================\n\"\"\"\n\nimport matplotlib as mpl\n\nzhfont = mpl.font_manager.FontProperties(fname='/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc')\n\ndef matplot(show):\n fig,ax = plt.subplots()\n limegreen = np.zeros([2,2],dtype = int)\n dodgerblue = np.zeros([2,2],dtype = int)\n orange = np.zeros([2,2],dtype = int)\n m = np.zeros([2,2],dtype = int)\n for x,y in zip(show[:,0],show[:,1]):\n print((x,y))\n if y <= 10 :\n limegreen = np.concatenate((limegreen,[[x,y]]),axis = 0)\n elif y <=20 :\n dodgerblue = np.concatenate((dodgerblue,[[x,y]]),axis = 0)\n elif y <= 30 :\n orange = np.concatenate((orange,[[x,y]]),axis = 0)\n else :\n m = np.concatenate((m,[[x,y]]),axis = 0)\n limegreen = deletFT(limegreen)\n dodgerblue = deletFT(dodgerblue)\n orange = deletFT(orange)\n m = deletFT(m)\n limegreen1 = ax.bar(limegreen[:,0],limegreen[:,1],color='limegreen')\n dodgerblue1 = ax.bar(dodgerblue[:,0],dodgerblue[:,1],color='dodgerblue')\n orange1 = ax.bar(orange[:,0],orange[:,1],color='orange')\n m1 = ax.bar(m[:,0],m[:,1],color='m')\n ax.set_title('当前时段车厢内人数分布图',fontproperties=zhfont,size=\"20\")\n ax.set_xlim(0,show.shape[0]+1)\n ax.set_ylim(0,40)\n ax.set_ylabel('人数',fontproperties=zhfont,size=\"15\")\n ax.set_xlabel('2018-12-30',size=\"15\")\n ax.set_xticks([1,6,12,18,24,30,36])\n ax.set_xticklabels((r'$06:20$',r'$06:50$',r'$07:20$',r'$07:50$',r'$08:20$',r'$08:50$',r'$09:20$'))\n ax.set_yticks([0,5,10,15,20,25,30,35,40])\n leg = ax.legend((limegreen1[0],dodgerblue1[0],orange1[0],m1[0]),('少','正常','较多','爆满'))\n for text in leg.texts : text.set_font_properties(zhfont)\n\n def autolabel(rects):\n for rect in rects :\n height = rect.get_height()\n ax.text(rect.get_x()+rect.get_width()/2.0,1.01*height,'%d'%int(height),ha='center',va='bottom')\n\n autolabel(limegreen1)\n autolabel(dodgerblue1)\n autolabel(orange1)\n autolabel(m1)\n\n plt.savefig(\"plot.png\")\n plt.show()\n\ndef deletFT(abc):\n abc = np.delete(abc,[0,1],axis = 0)\n return abc\n\n############################################################\n# Training\n############################################################\n\nif __name__ == '__main__':\n import argparse\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n description='Train Mask R-CNN to detect balloons.')\n parser.add_argument(\"command\",\n metavar=\"<command>\",\n help=\"'train' or 'splash'\")\n parser.add_argument('--dataset', required=False,\n metavar=\"/path/to/balloon/dataset/\",\n help='Directory of the Balloon dataset')\n parser.add_argument('--weights', required=True,\n metavar=\"/path/to/weights.h5\",\n help=\"Path to weights .h5 file or 'coco'\")\n parser.add_argument('--logs', required=False,\n default=DEFAULT_LOGS_DIR,\n metavar=\"/path/to/logs/\",\n help='Logs and checkpoints directory (default=logs/)')\n parser.add_argument('--image', required=False,\n metavar=\"path or URL to image\",\n help='Image to apply the color splash effect on')\n parser.add_argument('--video', required=False,\n metavar=\"path or URL to video\",\n help='Video to apply the color splash effect on')\n args = parser.parse_args()\n\n # Validate arguments\n if args.command == \"train\":\n assert args.dataset, \"Argument --dataset is required for training\"\n elif args.command == \"splash\":\n assert args.image or args.video,\\\n \"Provide --image or --video to apply color splash\"\n\n print(\"Weights: \", args.weights)\n print(\"Dataset: \", args.dataset)\n print(\"Logs: \", args.logs)\n\n # Configurations\n if args.command == \"train\":\n config = BalloonConfig()\n else:\n class InferenceConfig(BalloonConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n config = InferenceConfig()\n config.display()\n\n # Create model\n if args.command == \"train\":\n model = modellib.MaskRCNN(mode=\"training\", config=config,\n model_dir=args.logs)\n else:\n model = modellib.MaskRCNN(mode=\"inference\", config=config,\n model_dir=args.logs)\n\n # Select weights file to load\n if args.weights.lower() == \"coco\":\n weights_path = COCO_WEIGHTS_PATH\n # Download weights file\n if not os.path.exists(weights_path):\n utils.download_trained_weights(weights_path)\n elif args.weights.lower() == \"last\":\n # Find last trained weights\n weights_path = model.find_last()\n elif args.weights.lower() == \"imagenet\":\n # Start from ImageNet trained weights\n weights_path = model.get_imagenet_weights()\n else:\n weights_path = args.weights\n\n # Load weights\n print(\"Loading weights \", weights_path)\n if args.weights.lower() == \"coco\":\n # Exclude the last layers because they require a matching\n # number of classes\n model.load_weights(weights_path, by_name=True, exclude=[\n \"mrcnn_class_logits\", \"mrcnn_bbox_fc\",\n \"mrcnn_bbox\", \"mrcnn_mask\"])\n else:\n model.load_weights(weights_path, by_name=True)\n\n # Train or evaluate\n if args.command == \"train\":\n train(model)\n elif args.command == \"splash\":\n detect_and_color_splash(model, image_path=args.image,\n video_path=args.video)\n else:\n print(\"'{}' is not recognized. \"\n \"Use 'train' or 'splash'\".format(args.command))\n","sub_path":"people/people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":23292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"598667698","text":"from typing import Union, Callable, Any\n\nimport numpy as np\nfrom casadi import MX, SX, vertcat\nfrom scipy.interpolate import interp1d\n\nfrom ..misc.enums import InterpolationType\nfrom ..misc.mapping import BiMapping\nfrom ..misc.options import UniquePerPhaseOptionList, OptionGeneric\n\n\nclass PathCondition(np.ndarray):\n \"\"\"\n A matrix for any component (rows) and time (columns) conditions\n\n Attributes\n ----------\n n_shooting: int\n Number of shooting points\n type: InterpolationType\n Type of interpolation\n t: list[float]\n Time vector\n extra_params: dict\n Any extra parameters that is associated to the path condition\n slice_list: slice\n Slice of the array\n custom_function: Callable\n Custom function to describe the path condition interpolation\n\n Methods\n -------\n __array_finalize__(self, obj: \"PathCondition\")\n Finalize the array. This is required since PathCondition inherits from np.ndarray\n __reduce__(self) -> tuple\n Adding some attributes to the reduced state\n __setstate__(self, state: tuple, *args, **kwargs)\n Adding some attributes to the expanded state\n check_and_adjust_dimensions(self, n_elements: int, n_shooting: int, element_name: str)\n Sanity check if the dimension of the matrix are sounds when compare to the number\n of required elements and time. If the function exit, then everything is okay\n evaluate_at(self, shooting_point: int)\n Evaluate the interpolation at a specific shooting point\n \"\"\"\n\n def __new__(\n cls,\n input_array: Union[np.ndarray, Callable],\n t: list = None,\n interpolation: InterpolationType = InterpolationType.CONSTANT,\n slice_list: Union[slice, list, tuple] = None,\n **extra_params,\n ):\n \"\"\"\n Parameters\n ----------\n input_array: Union[np.ndarray, Callable]\n The matrix of interpolation, rows are the components, columns are the time\n t: list[float]\n The time stamps\n interpolation: InterpolationType\n The type of interpolation. It determines how many timestamps are required\n slice_list: Union[slice, list, tuple]\n If the data should be sliced. It is more relevant for custom functions\n extra_params: dict\n Any parameters to pass to the path condition\n \"\"\"\n\n # Check and reinterpret input\n custom_function = None\n if interpolation == InterpolationType.CUSTOM:\n if not callable(input_array):\n raise TypeError(\"The input when using InterpolationType.CUSTOM should be a callable function\")\n custom_function = input_array\n input_array = np.array(())\n if not isinstance(input_array, (MX, SX)):\n input_array = np.asarray(input_array, dtype=float)\n\n if len(input_array.shape) == 0:\n input_array = input_array[np.newaxis, np.newaxis]\n\n if interpolation == InterpolationType.CONSTANT:\n if len(input_array.shape) == 1:\n input_array = input_array[:, np.newaxis]\n if input_array.shape[1] != 1:\n raise RuntimeError(\n f\"Invalid number of column for InterpolationType.CONSTANT \"\n f\"(ncols = {input_array.shape[1]}), the expected number of column is 1\"\n )\n\n elif interpolation == InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT:\n if len(input_array.shape) == 1:\n input_array = input_array[:, np.newaxis]\n if input_array.shape[1] != 1 and input_array.shape[1] != 3:\n raise RuntimeError(\n f\"Invalid number of column for InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT \"\n f\"(ncols = {input_array.shape[1]}), the expected number of column is 1 or 3\"\n )\n if input_array.shape[1] == 1:\n input_array = np.repeat(input_array, 3, axis=1)\n elif interpolation == InterpolationType.LINEAR:\n if input_array.shape[1] != 2:\n raise RuntimeError(\n f\"Invalid number of column for InterpolationType.LINEAR_CONTINUOUS \"\n f\"(ncols = {input_array.shape[1]}), the expected number of column is 2\"\n )\n elif interpolation == InterpolationType.EACH_FRAME:\n # This will be verified when the expected number of columns is set\n pass\n elif interpolation == InterpolationType.SPLINE:\n if input_array.shape[1] < 2:\n raise RuntimeError(\"Value for InterpolationType.SPLINE must have at least 2 columns\")\n if t is None:\n raise RuntimeError(\"Spline necessitate a time vector\")\n t = np.asarray(t)\n if input_array.shape[1] != t.shape[0]:\n raise RuntimeError(\"Spline necessitate a time vector which as the same length as column of data\")\n\n elif interpolation == InterpolationType.CUSTOM:\n # We have to assume dimensions are those the user wants\n pass\n else:\n raise RuntimeError(f\"InterpolationType is not implemented yet\")\n if not isinstance(input_array, (MX, SX)):\n obj = np.asarray(input_array).view(cls)\n else:\n obj = input_array\n\n # Additional information (do not forget to update __reduce__ and __setstate__)\n obj.n_shooting = None\n obj.type = interpolation\n obj.t = t\n obj.extra_params = extra_params\n obj.slice_list = slice_list\n if interpolation == InterpolationType.CUSTOM:\n obj.custom_function = custom_function\n\n return obj\n\n def __array_finalize__(self, obj):\n \"\"\"\n Finalize the array. This is required since PathCondition inherits from np.ndarray\n\n Parameters\n ----------\n obj: PathCondition\n The current object to finalize\n \"\"\"\n\n # see InfoArray.__array_finalize__ for comments\n if obj is None:\n return\n self.n_shooting = getattr(obj, \"n_shooting\", None)\n self.type = getattr(obj, \"type\", None)\n self.t = getattr(obj, \"t\", None)\n self.extra_params = getattr(obj, \"extra_params\", None)\n self.slice_list = getattr(obj, \"slice_list\", None)\n\n def __reduce__(self) -> tuple:\n \"\"\"\n Adding some attributes to the reduced state\n\n Returns\n -------\n The reduced state of the class\n \"\"\"\n\n pickled_state = super(PathCondition, self).__reduce__()\n new_state = pickled_state[2] + (self.n_shooting, self.type, self.t, self.extra_params, self.slice_list)\n return pickled_state[0], pickled_state[1], new_state\n\n def __setstate__(self, state: tuple, *args, **kwargs):\n \"\"\"\n Adding some attributes to the expanded state\n\n Parameters\n ----------\n state: tuple\n The state as described by __reduce__\n \"\"\"\n\n self.n_shooting = state[-5]\n self.type = state[-4]\n self.t = state[-3]\n self.extra_params = state[-2]\n self.slice_list = state[-1]\n # Call the parent's __setstate__ with the other tuple elements.\n super(PathCondition, self).__setstate__(state[0:-5], *args, **kwargs)\n\n def check_and_adjust_dimensions(self, n_elements: int, n_shooting: int, element_name: str):\n \"\"\"\n Sanity check if the dimension of the matrix are sounds when compare to the number\n of required elements and time. If the function exit, then everything is okay\n\n Parameters\n ----------\n n_elements: int\n The expected number of rows\n n_shooting: int\n The number of shooting points in the ocp\n element_name: str\n The human readable name of the data structure\n \"\"\"\n\n if (\n self.type == InterpolationType.CONSTANT\n or self.type == InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT\n or self.type == InterpolationType.LINEAR\n or self.type == InterpolationType.SPLINE\n or self.type == InterpolationType.CUSTOM\n ):\n self.n_shooting = n_shooting\n elif self.type == InterpolationType.EACH_FRAME:\n self.n_shooting = n_shooting + 1\n else:\n if self.n_shooting != n_shooting:\n raise RuntimeError(\n f\"Invalid number of shooting ({self.n_shooting}), the expected number is {n_shooting}\"\n )\n\n if self.type == InterpolationType.CUSTOM:\n slice_list = self.slice_list\n if slice_list is not None:\n val_size = self.custom_function(0, **self.extra_params)[\n slice_list.start : slice_list.stop : slice_list.step\n ].shape[0]\n else:\n val_size = self.custom_function(0, **self.extra_params).shape[0]\n else:\n val_size = self.shape[0]\n if val_size != n_elements:\n raise RuntimeError(f\"Invalid number of {element_name} ({val_size}), the expected size is {n_elements}\")\n\n if self.type == InterpolationType.EACH_FRAME:\n if self.shape[1] != self.n_shooting:\n raise RuntimeError(\n f\"Invalid number of column for InterpolationType.EACH_FRAME (ncols = {self.shape[1]}), \"\n f\"the expected number of column is {self.n_shooting}\"\n )\n\n def evaluate_at(self, shooting_point: int):\n \"\"\"\n Evaluate the interpolation at a specific shooting point\n\n Parameters\n ----------\n shooting_point: int\n The shooting point to evaluate the path condition at\n\n Returns\n -------\n The values of the components at a specific time index\n \"\"\"\n\n if self.n_shooting is None:\n raise RuntimeError(f\"check_and_adjust_dimensions must be called at least once before evaluating at\")\n\n if self.type == InterpolationType.CONSTANT:\n return self[:, 0]\n elif self.type == InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT:\n if shooting_point == 0:\n return self[:, 0]\n elif shooting_point == self.n_shooting:\n return self[:, 2]\n elif shooting_point > self.n_shooting:\n raise RuntimeError(\"shooting point too high\")\n else:\n return self[:, 1]\n elif self.type == InterpolationType.LINEAR:\n return self[:, 0] + (self[:, 1] - self[:, 0]) * shooting_point / self.n_shooting\n elif self.type == InterpolationType.EACH_FRAME:\n return self[:, shooting_point]\n elif self.type == InterpolationType.SPLINE:\n spline = interp1d(self.t, self)\n return spline(shooting_point / self.n_shooting * (self.t[-1] - self.t[0]))\n elif self.type == InterpolationType.CUSTOM:\n if self.slice_list is not None:\n slice_list = self.slice_list\n return self.custom_function(shooting_point, **self.extra_params)[\n slice_list.start : slice_list.stop : slice_list.step\n ]\n else:\n return self.custom_function(shooting_point, **self.extra_params)\n else:\n raise RuntimeError(f\"InterpolationType is not implemented yet\")\n\n\nclass Bounds(OptionGeneric):\n \"\"\"\n A placeholder for bounds constraints\n\n Attributes\n ----------\n n_shooting: int\n The number of shooting of the ocp\n min: PathCondition\n The minimal bound\n max: PathCondition\n The maximal bound\n type: InterpolationType\n The type of interpolation of the bound\n t: list[float]\n The time stamps\n extra_params: dict\n Any parameters to pass to the path condition\n\n Methods\n -------\n check_and_adjust_dimensions(self, n_elements: int, n_shooting: int)\n Sanity check if the dimension of the matrix are sounds when compare to the number\n of required elements and time. If the function exit, then everything is okay\n concatenate(self, other: \"Bounds\")\n Vertical concatenate of two Bounds\n __getitem__(self, slice_list: slice) -> \"Bounds\"\n Allows to get from square brackets\n __setitem__(self, slice: slice, value: Union[np.ndarray, list, float])\n Allows to set from square brackets\n __bool__(self) -> bool\n Get if the Bounds is empty\n shape(self) -> int\n Get the size of the Bounds\n \"\"\"\n\n def __init__(\n self,\n min_bound: Union[Callable, PathCondition, np.ndarray, list, tuple, float] = (),\n max_bound: Union[Callable, PathCondition, np.ndarray, list, tuple, float] = (),\n interpolation: InterpolationType = InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,\n slice_list: Union[slice, list, tuple] = None,\n **parameters: Any,\n ):\n \"\"\"\n Parameters\n ----------\n min_bound: Union[Callable, PathCondition, np.ndarray, list, tuple]\n The minimal bound\n max_bound: Union[Callable, PathCondition, np.ndarray, list, tuple]\n The maximal bound\n interpolation: InterpolationType\n The type of interpolation of the bound\n slice_list: Union[slice, list, tuple]\n Slice of the array\n parameters: dict\n Any extra parameters that is associated to the path condition\n \"\"\"\n if isinstance(min_bound, PathCondition):\n self.min = min_bound\n else:\n self.min = PathCondition(min_bound, interpolation=interpolation, slice_list=slice_list, **parameters)\n\n if isinstance(max_bound, PathCondition):\n self.max = max_bound\n else:\n self.max = PathCondition(max_bound, interpolation=interpolation, slice_list=slice_list, **parameters)\n\n super(Bounds, self).__init__(**parameters)\n self.type = interpolation\n self.t = None\n self.extra_params = self.min.extra_params\n self.n_shooting = self.min.n_shooting\n\n def check_and_adjust_dimensions(self, n_elements: int, n_shooting: int):\n \"\"\"\n Sanity check if the dimension of the matrix are sounds when compare to the number\n of required elements and time. If the function exit, then everything is okay\n\n Parameters\n ----------\n n_elements: int\n The expected number of rows\n n_shooting: int\n The number of shooting points in the ocp\n \"\"\"\n\n self.min.check_and_adjust_dimensions(n_elements, n_shooting, \"Bound min\")\n self.max.check_and_adjust_dimensions(n_elements, n_shooting, \"Bound max\")\n self.t = self.min.t\n self.n_shooting = self.min.n_shooting\n\n def concatenate(self, other: \"Bounds\"):\n \"\"\"\n Vertical concatenate of two Bounds\n\n Parameters\n ----------\n other: Bounds\n The Bounds to concatenate with\n \"\"\"\n\n if not isinstance(self.min, (MX, SX)) and not isinstance(other.min, (MX, SX)):\n self.min = PathCondition(np.concatenate((self.min, other.min)), interpolation=self.min.type)\n else:\n self.min = PathCondition(vertcat(self.min, other.min), interpolation=self.min.type)\n if not isinstance(self.max, (MX, SX)) and not isinstance(other.max, (MX, SX)):\n self.max = PathCondition(np.concatenate((self.max, other.max)), interpolation=self.max.type)\n else:\n self.max = PathCondition(vertcat(self.max, other.max), interpolation=self.max.type)\n\n self.type = self.min.type\n self.t = self.min.t\n self.extra_params = self.min.extra_params\n self.n_shooting = self.min.n_shooting\n\n def scale(self, scaling: Union[float, np.ndarray]):\n \"\"\"\n Scaling a Bound\n\n Parameters\n ----------\n scaling: float\n The scaling factor\n \"\"\"\n\n self.min /= scaling\n self.max /= scaling\n return\n\n def __getitem__(self, slice_list: Union[slice, list, tuple]) -> \"Bounds\":\n \"\"\"\n Allows to get from square brackets\n\n Parameters\n ----------\n slice_list: Union[slice, list, tuple]\n The slice to get\n\n Returns\n -------\n The bound sliced\n \"\"\"\n\n if isinstance(slice_list, slice):\n t = self.min.t\n param = self.extra_params\n interpolation = self.type\n if interpolation == InterpolationType.CUSTOM:\n min_bound = self.min.custom_function\n max_bound = self.max.custom_function\n else:\n min_bound = np.array(self.min[slice_list.start : slice_list.stop : slice_list.step])\n max_bound = np.array(self.max[slice_list.start : slice_list.stop : slice_list.step])\n bounds_sliced = Bounds(\n min_bound=min_bound,\n max_bound=max_bound,\n interpolation=interpolation,\n slice_list=slice_list,\n t=t,\n **param,\n )\n # TODO: Verify if it is ok that slice_list arg sent is used only if it is a custom type\n # (otherwise, slice_list is used before calling Bounds constructor)\n return bounds_sliced\n else:\n raise RuntimeError(\n \"Invalid input for slicing bounds. Please note that columns should not be specified. \"\n \"Therefore, it should look like [a:b] or [a:b:c] where a is the starting index, \"\n \"b is the stopping index and c is the step for slicing.\"\n )\n\n def __setitem__(self, _slice: Union[slice, list, tuple], value: Union[np.ndarray, list, float]):\n \"\"\"\n Allows to set from square brackets\n\n Parameters\n ----------\n _slice: Union[slice, list, tuple]\n The slice where to put the data\n value: Union[np.ndarray, float]\n The value to set\n \"\"\"\n\n self.min[_slice] = value\n self.max[_slice] = value\n\n def __bool__(self) -> bool:\n \"\"\"\n Get if the Bounds is empty\n\n Returns\n -------\n If the Bounds is empty\n \"\"\"\n\n return len(self.min) > 0\n\n @property\n def shape(self) -> int:\n \"\"\"\n Get the size of the Bounds\n\n Returns\n -------\n The size of the Bounds\n \"\"\"\n\n return self.min.shape\n\n\nclass BoundsList(UniquePerPhaseOptionList):\n \"\"\"\n A list of Bounds if more than one is required\n\n Methods\n -------\n add(self, min_bound: Union[PathCondition, np.ndarray, list, tuple] = None,\n max_bound: Union[PathCondition, np.ndarray, list, tuple] = None, bounds: Bounds = None, **extra_arguments)\n Add a new constraint to the list, either [min_bound AND max_bound] OR [bounds] should be defined\n __getitem__(self, item) -> Bounds\n Get the ith option of the list\n print(self)\n Print the BoundsList to the console\n \"\"\"\n\n def add(\n self,\n min_bound: Union[PathCondition, np.ndarray, list, tuple] = None,\n max_bound: Union[PathCondition, np.ndarray, list, tuple] = None,\n bounds: Bounds = None,\n **extra_arguments,\n ):\n \"\"\"\n Add a new bounds to the list, either [min_bound AND max_bound] OR [bounds] should be defined\n\n Parameters\n ----------\n min_bound: Union[PathCondition, np.ndarray, list, tuple]\n The minimum path condition. If min_bound if defined, then max_bound must be so and bound should be None\n max_bound: [PathCondition, np.ndarray, list, tuple]\n The maximum path condition. If max_bound if defined, then min_bound must be so and bound should be None\n bounds: Bounds\n Copy a Bounds. If bounds is defined, min_bound and max_bound should be None\n extra_arguments: dict\n Any parameters to pass to the Bounds\n \"\"\"\n\n if bounds and (min_bound or max_bound):\n RuntimeError(\"min_bound/max_bound and bounds cannot be set alongside\")\n if isinstance(bounds, Bounds):\n if bounds.phase == -1:\n bounds.phase = len(self.options) if self.options[0] else 0\n self.copy(bounds)\n else:\n super(BoundsList, self)._add(\n min_bound=min_bound, max_bound=max_bound, option_type=Bounds, **extra_arguments\n )\n\n def __getitem__(self, item) -> Bounds:\n \"\"\"\n Get the ith option of the list\n\n Parameters\n ----------\n item: int\n The index of the option to get\n\n Returns\n -------\n The ith option of the list\n \"\"\"\n\n return super(BoundsList, self).__getitem__(item)\n\n def print(self):\n \"\"\"\n Print the BoundsList to the console\n \"\"\"\n\n raise NotImplementedError(\"Printing of BoundsList is not ready yet\")\n\n\nclass QAndQDotBounds(Bounds):\n \"\"\"\n Specialized Bounds that reads a model to automatically extract q and qdot bounds\n \"\"\"\n\n def __init__(\n self,\n biorbd_model,\n q_mapping: BiMapping = None,\n qdot_mapping: BiMapping = None,\n ):\n \"\"\"\n Parameters\n ----------\n biorbd_model: biorbd.Model\n A reference to the model\n q_mapping: BiMapping\n The mapping of q\n qdot_mapping: BiMapping\n The mapping of qdot. If qdot_mapping is not provided, q_mapping is used\n \"\"\"\n if biorbd_model.nbQuat() > 0:\n if q_mapping and not qdot_mapping:\n raise RuntimeError(\n \"It is not possible to provide a q_mapping but not a qdot_mapping if the model have quaternion\"\n )\n elif qdot_mapping and not q_mapping:\n raise RuntimeError(\n \"It is not possible to provide a qdot_mapping but not a q_mapping if the model have quaternion\"\n )\n\n if not q_mapping:\n q_mapping = BiMapping(range(biorbd_model.nbQ()), range(biorbd_model.nbQ()))\n\n if not qdot_mapping:\n if biorbd_model.nbQuat() > 0:\n qdot_mapping = BiMapping(range(biorbd_model.nbQdot()), range(biorbd_model.nbQdot()))\n else:\n qdot_mapping = q_mapping\n\n q_ranges = []\n qdot_ranges = []\n for i in range(biorbd_model.nbSegment()):\n segment = biorbd_model.segment(i)\n q_ranges += [q_range for q_range in segment.QRanges()]\n qdot_ranges += [qdot_range for qdot_range in segment.QDotRanges()]\n\n x_min = [q_ranges[i].min() for i in q_mapping.to_first.map_idx] + [\n qdot_ranges[i].min() for i in qdot_mapping.to_first.map_idx\n ]\n x_max = [q_ranges[i].max() for i in q_mapping.to_first.map_idx] + [\n qdot_ranges[i].max() for i in qdot_mapping.to_first.map_idx\n ]\n\n super(QAndQDotBounds, self).__init__(min_bound=x_min, max_bound=x_max)\n\n\nclass InitialGuess(OptionGeneric):\n \"\"\"\n A placeholder for the initial guess\n\n Attributes\n ----------\n init: PathCondition\n The initial guess\n\n Methods\n -------\n check_and_adjust_dimensions(self, n_elements: int, n_shooting: int)\n Sanity check if the dimension of the matrix are sounds when compare to the number\n of required elements and time. If the function exit, then everything is okay\n concatenate(self, other: \"InitialGuess\")\n Vertical concatenate of two InitialGuess\n __bool__(self) -> bool\n Get if the initial guess is empty\n shape(self) -> int\n Get the size of the initial guess\n \"\"\"\n\n def __init__(\n self,\n initial_guess: Union[np.ndarray, list, tuple, float, Callable] = (),\n interpolation: InterpolationType = InterpolationType.CONSTANT,\n **parameters: Any,\n ):\n \"\"\"\n Parameters\n ----------\n initial_guess: Union[np.ndarray, list, tuple, float, Callable]\n The initial guess\n interpolation: InterpolationType\n The type of interpolation of the initial guess\n parameters: dict\n Any extra parameters that is associated to the path condition\n \"\"\"\n\n if isinstance(initial_guess, PathCondition):\n self.init = initial_guess\n else:\n self.init = PathCondition(initial_guess, interpolation=interpolation, **parameters)\n\n super(InitialGuess, self).__init__(**parameters)\n self.type = interpolation\n\n def check_and_adjust_dimensions(self, n_elements: int, n_shooting: int):\n \"\"\"\n Sanity check if the dimension of the matrix are sounds when compare to the number\n of required elements and time. If the function exit, then everything is okay\n\n Parameters\n ----------\n n_elements: int\n The expected number of rows\n n_shooting: int\n The number of shooting points in the ocp\n \"\"\"\n\n self.init.check_and_adjust_dimensions(n_elements, n_shooting, \"InitialGuess\")\n\n def concatenate(self, other: \"InitialGuess\"):\n \"\"\"\n Vertical concatenate of two Bounds\n\n Parameters\n ----------\n other: InitialGuess\n The InitialGuess to concatenate with\n \"\"\"\n\n self.init = PathCondition(\n np.concatenate((self.init, other.init)),\n interpolation=self.init.type,\n )\n\n def scale(self, scaling: float):\n \"\"\"\n Scaling an InitialGuess\n\n Parameters\n ----------\n scaling: float\n The scaling factor\n \"\"\"\n self.init /= scaling\n return\n\n def __bool__(self) -> bool:\n \"\"\"\n Get if the InitialGuess is empty\n\n Returns\n -------\n If the InitialGuess is empty\n \"\"\"\n\n return len(self.init) > 0\n\n @property\n def shape(self) -> int:\n \"\"\"\n Get the size of the InitialGuess\n\n Returns\n -------\n The size of the InitialGuess\n \"\"\"\n\n return self.init.shape\n\n\nclass InitialGuessList(UniquePerPhaseOptionList):\n \"\"\"\n A list of InitialGuess if more than one is required\n\n Methods\n -------\n add(self, initial_guess: Union[PathCondition, np.ndarray, list, tuple], **extra_arguments)\n Add a new initial guess to the list\n print(self)\n Print the InitialGuessList to the console\n \"\"\"\n\n def add(self, initial_guess: Union[InitialGuess, np.ndarray, list, tuple], **extra_arguments: Any):\n \"\"\"\n Add a new initial guess to the list\n\n Parameters\n ----------\n initial_guess: Union[InitialGuess, np.ndarray, list, tuple]\n The initial guess to add\n extra_arguments: dict\n Any parameters to pass to the Bounds\n \"\"\"\n\n if isinstance(initial_guess, InitialGuess):\n self.copy(initial_guess)\n else:\n super(InitialGuessList, self)._add(initial_guess=initial_guess, option_type=InitialGuess, **extra_arguments)\n\n def print(self):\n \"\"\"\n Print the InitialGuessList to the console\n \"\"\"\n raise NotImplementedError(\"Printing of InitialGuessList is not ready yet\")\n","sub_path":"bioptim/limits/path_conditions.py","file_name":"path_conditions.py","file_ext":"py","file_size_in_byte":27490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"15157680","text":"from Interp import LOLCodeInterpreter\r\nfrom Parser import parser\r\nimport argparse\r\n\r\nif __name__ == \"__main__\":\r\n arg_parser = argparse.ArgumentParser(description='LolCode interpretator')\r\n arg_parser.add_argument('-f', nargs=1, help='input filename')\r\n args = arg_parser.parse_args()\r\n filename = args.f[0]\r\n with open(filename, 'r') as f:\r\n data = f.read()\r\n if data:\r\n try:\r\n tree = parser.parse(data)\r\n interpret = LOLCodeInterpreter(tree)\r\n interpret.execute_program()\r\n except Exception as e:\r\n print(e)","sub_path":"LolCode.py","file_name":"LolCode.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164268168","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom django.conf import settings\nfrom django import setup\nfrom django.test.runner import DiscoverRunner\n\n\nif __name__ == \"__main__\":\n settings.configure(\n **{\n \"DATABASES\": {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": \"\",\n \"USER\": \"\",\n \"PASSWORD\": \"\",\n }\n },\n \"INSTALLED_APPS\": (\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"access\",\n ),\n }\n )\n setup()\n failures = DiscoverRunner(verbosity=1).run_tests([\"access\"])\n if failures:\n sys.exit(failures)\n","sub_path":"runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291365525","text":"# Copyright (C) 2020 Wissen MX\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom odoo import fields, models, api\nfrom odoo.osv import expression\n\n\nclass AccountPayment(models.Model):\n _inherit = 'account.payment'\n \n w_tasa_id = fields.Many2one('res.currency.rate', string='Fecha de Tasa')\n w_tasa = fields.Float(related = 'w_tasa_id.rate', readonly=False, string='Tasa')\n \n def rateant(self):\n temporal = self.env['rates.temp']\n CurrencyRate = self.env['res.currency.rate']\n temporal_object = temporal.search([('w_tasa_id', '=', self.w_tasa_id.id)], limit=1, order='create_date')\n currency_object = CurrencyRate.search([('id', '=', self.w_tasa_id.id)])\n currency_object.rate = temporal_object.w_tasanterior\n temporal_object.unlink()\n return True\n \n @api.model\n def create(self, values):\n CurrencyRate = self.env['res.currency.rate']\n temporal = self.env['rates.temp']\n currency_object = CurrencyRate.search([('id', '=', values['w_tasa_id'])])\n tasaant = currency_object.rate\n temporal.create({'w_tasa_id': currency_object.id, 'w_tasanterior': tasaant, 'w_name': currency_object.name, 'w_company_id': currency_object.company_id})\n res = super(AccountPayment, self).create(values)\n return res\n \n","sub_path":"rate/models/rate.py","file_name":"rate.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245806446","text":"#Simulate a game of Hangman.\nimport random\ntextFileLines = open(\"Resources/hangmanwords.txt\").readlines()\nrandomLine = random.choice(textFileLines)\nhangmanWords = randomLine.split()\ncurrentWord = random.choice(hangmanWords).lower()\ngameFinished = False\nlettersGuessed = []\nwrongGuesses = 0\nuserDisplayLine = []\ncorrectGuesses = 0\n\nprint(\"You're playing hangman! If you make 10 incorrect guesses, you lose.\")\nfor i in range(0, len(currentWord)):\n userDisplayLine .append(\"_\")\nwhile gameFinished is False:\n print(\" \".join(userDisplayLine))\n guessedLetter = input(\"Guess a letter --> \").lower()\n\n if guessedLetter in lettersGuessed:\n print(\"You've already guessed '\", guessedLetter,\"'\")\n elif len(guessedLetter) > 1 or guessedLetter.isalpha() is False:\n print(\"Invalid input. Please enter a single letter as a guess.\")\n else:\n if guessedLetter in currentWord:\n for i in range(0, len(currentWord)):\n if currentWord[i] == guessedLetter:\n userDisplayLine[i] = guessedLetter\n correctGuesses += 1\n lettersGuessed.append(guessedLetter)\n print(\"Guessed Letters: \", lettersGuessed)\n else:\n wrongGuesses += 1\n print(guessedLetter, \"is not in the word. Incorrect guesses: \", wrongGuesses)\n lettersGuessed.append(guessedLetter)\n print(\"Guessed Letters: \", lettersGuessed)\n if(wrongGuesses == 10):\n print(\"You have lost the game. The word was\", currentWord)\n gameFinished = True\n if(correctGuesses == len(currentWord)):\n print(\"You've won! The word was\", currentWord)\n gameFinished = True","sub_path":"Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"324468690","text":"import socket\nimport struct\nimport subprocess as sp\nfrom threading import Thread\n\n\nhosts = {} # {ip: hostname}\nmulticast_group = '224.3.29.71'\nserver_address = ('', 10000)\n\n# Create the socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n# Bind to the server address\nsock.bind(server_address)\n# Tell the operating system to add the socket to the multicast group\n# on all interfaces.\ngroup = socket.inet_aton(multicast_group)\nmreq = struct.pack('4sL', group, socket.INADDR_ANY)\nsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n\n\ndef ip_address():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n return s.getsockname()[0]\n\n\ndef send_message(msg):\n _multicast_group = ('224.3.29.71', 10000)\n try:\n if msg == '.../...':\n # Send data to the multicast group\n # print('sending \"%s\"' % message())\n sock.sendto(str.encode('.../...' + message()), _multicast_group)\n print('\\nHello message sent')\n else:\n sock.sendto(str.encode(msg), _multicast_group)\n\n except Exception as e:\n print(e)\n\n\ndef message():\n global hostname\n cmd = ['cat /etc/hostname']\n hostname = str(sp.check_output(cmd, shell=True), 'utf-8')[0:-1]\n return hostname\n\n\ndef receive_message():\n while True:\n data, address = sock.recvfrom(1024)\n\n if data.decode()[:7] == '.../...':\n # print('received %s bytes from %s' % (len(data), address))\n hosts[address[0]] = data.decode()[7:]\n if len(hosts) == mec:\n print('MEC Details: ', hosts)\n else:\n if address[0] != ip_address():\n print(data.decode())\n\n\ndef messaging_nodes():\n global h1\n\n while True:\n\n try:\n msg = input()\n if (msg == '') or (msg == ' '):\n print('\\n')\n else:\n # print('{}: {}'.format(hostname, msg_))\n send_message(msg)\n\n except Exception as e:\n print('Programme Terminated')\n\n\ndef main():\n global mec\n global h1\n\n try:\n mec = int(input('Number of Nodes: ').strip())\n print('\\nCompiling All Neighbours Details')\n h1 = Thread(target=receive_message)\n h1.daemon = True\n h1.start()\n if input('Send Hello Message (Y/N): ').strip().lower() == 'y':\n send_message('.../...')\n messaging_nodes()\n\n except KeyboardInterrupt:\n print('\\nProgramme Terminated')\n exit(0)\n\n\nmain()\n\n\n\n\n","sub_path":"3send_receive.py","file_name":"3send_receive.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11024947","text":"# This is an interface for interacting directly with the program host\nfrom multiprocessing.connection import Connection, Pipe\n\nfrom Config import cfg_transaction\nfrom ModuleMessage import ModuleMessage\n\n\nclass CFGT:\n def __init__(self):\n pass\n\n CFG_GET = \"cfg_get\"\n CFG_SET = \"cfg_set\"\n\n\ndef get_config_value(conn: Connection = None, key=None, prgh_queue=None):\n h, c = Pipe(duplex=True)\n cfg_msg = cfg_transaction(key, is_set_var=False, reply=c)\n\n config_message = ModuleMessage(\"PRGH\", CFGT.CFG_GET, cfg_msg)\n if conn is not None:\n conn.send(config_message)\n elif prgh_queue is not None:\n prgh_queue.put(config_message)\n else:\n raise Exception(\"get_config_value() was called without a pipe or queue\")\n\n msg = h.recv()\n h.close()\n return msg\n\n\ndef get_state_value(conn: Connection = None, key=None, prgh_queue=None):\n h, c = Pipe(duplex=True)\n\n state_message = ModuleMessage(\"PRGH\", \"get_state_data\", (key, c))\n if conn is not None:\n conn.send(state_message)\n elif prgh_queue is not None:\n prgh_queue.put(state_message)\n else:\n raise Exception(\"get_state_value() was called without a pipe or queue\")\n\n msg = h.recv()\n h.close()\n return msg\n\n\ndef set_state_value(conn: Connection, key, value):\n state_message = ModuleMessage(\"PRGH\", \"set_state_data\", (key, value))\n conn.send(state_message)\n","sub_path":"ProgramHostInterface.py","file_name":"ProgramHostInterface.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"576902658","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom itertools import combinations\n\n# Complete the icecreamParlor function below.\ndef icecreamParlor(m, arr):\n for pair in combinations(arr, 2):\n if sum(pair) == m:\n first_icecream_idx = arr.index(pair[0]) + 1\n return [first_icecream_idx, arr.index(pair[1], first_icecream_idx) + 1]\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n t = int(input())\n\n for t_itr in range(t):\n m = int(input())\n\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n result = icecreamParlor(m, arr)\n\n fptr.write(' '.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","sub_path":"icecream_pool.py","file_name":"icecream_pool.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2701663","text":"from PySFML import sf\nfrom Punk import *\nimport math\n\n#Reference to colour\nColor = sf.Color\n\nclass Rectangle:\n def __init__(self, x, y, width, height):\n self.x = x; self.y = y;\n self.width = width; self.height = height;\n\nclass Graphic(object):\n def __init__(self):\n # if the graphic should render\n self.visible = True\n\n # offset\n self.x = 0\n self.y = 0\n\n # If the graphic should render at its position relative to its parent Entity's position.\n self.relative = True\n\n #Scrollfactor\n self.scrollX = 1\n self.scrollY = 1\n\n #Transformation point\n self._originY = 0\n self._originY = 0\n\n # Graphic information\n self._assign = None # private\n self._scroll = True # private\n self._point = Point() # private\n self._alpha = 1.0 # private\n\n def render(self, App, point=Point(), camera=Punk.camera):\n \"\"\"Render the image to App\"\"\"\n #offsetx = int(self.x - self.originX - camera.x * self.scrollX)\n #offsety = int(self.y - self.originY - camera.y * self.scrollY)\n offsetx = int(self.x - camera.x * self.scrollX)\n offsety = int(self.y - camera.y * self.scrollY)\n if self.relative: offsetx += point.x; offsety += point.y\n self.SetPosition(offsetx, offsety)\n\n if self.visible: App.Draw(self)\n\n def _set_assign(self, value):\n self._assign = value\n assign = property(lambda self: self._assign, _set_assign)\n \n def set_alpha(self, value):\n if value > 1: value = 1\n if value < 0: value = 0\n self._alpha = value\n self.SetColor(sf.Color(255, 255, 255, int(value*255)))\n alpha = property(lambda self: self._alpha, set_alpha)\n\n def set_angle(self, value): self.SetRotation(value)\n angle = property(lambda self: self.GetRotation(), set_angle)\n\n def origin(self, x, y):\n self._originX = x\n self._originY = y;\n self.SetCenter(self._originX, self._originY) \n originX = property(lambda self: self.GetCenter()[0], lambda self, value: self.origin(value, self._originY))\n originY = property(lambda self: self.GetCenter()[1], lambda self, value: self.origin(self._originX, value))\n\n width = property(lambda self: self.GetImage().GetWidth())\n height = property(lambda self: self.GetImage().GetHeight())\n\n\nclass Image(Graphic, sf.Sprite):\n def __init__(self, loc, rect=None):\n \"\"\"Create new Image\n Args:\n loc: location of image\"\"\"\n Graphic.__init__(self)\n if type(loc) == str: self.img = GetImage(loc)\n elif type(loc) == sf.Image: self.img = loc\n else: raise TypeError(\"Please pass the path to an image or a sf.Image instance\")\n sf.Sprite.__init__(self, self.img)\n\n if rect:\n self.SetSubRect(sf.IntRect(rect.x, rect.y, rect.x+rect.width, rect.y+rect.height))\n\n #None of \\/THESE\\/ do anything right now. Will be added later\n\n # Scale of the image, affects both x and y scale.\n self.scale = 1\n\n # X scale of the image.\n self.scaleX = 1\n\n # Y scale of the image.\n self.scaleY = 1\n \n\n\nclass Spritemap(Image):\n def __init__(self, loc, frameWidth=0, frameHeight=0, callback=None):\n Graphic.__init__(self)\n\n self.complete = True\n self.callback = None\n self.rate = 1\n\n self._rect = Rectangle(0, 0, frameWidth, frameHeight)\n\n Image.__init__(self, loc, self._rect)\n\n self._width = self.GetImage().GetWidth()\n self._height = self.GetImage().GetHeight()\n if not frameWidth: self._rect.width = self._width\n if not frameHeight: self._rect.height = self._height\n self._columns = self._width / self._rect.width\n self._rows = self._height / self._rect.height\n self._frameCount = self._columns * self._rows\n self.callback = callback\n \n self._timer = 0\n self._anims = {}\n self._anim = None\n\n self._frame = 0\n self._index = 0\n\n def render(self, App, point=Point(), camera=Punk.camera):\n if self._anim and not self.complete:\n self._timer += (self._anim[\"frameRate\"] * Punk.elapsed) * self.rate\n if self._timer >= 1:\n while self._timer >= 1:\n self._timer -= 1\n self._index += 1\n if self._index == len(self._anim[\"frames\"]):\n if self._anim[\"loop\"]:\n self._index = 0\n if self.callback: self.callback()\n else:\n self._index = len(self._anim[\"frames\"])-1\n self.complete = True\n if self.callback: self.callback()\n break\n if self._anim: self._frame = self._anim[\"frames\"][self._index]\n self._rect.x = int((self._frame % self._columns) * self._rect.width)\n self._rect.y = int(math.ceil(self._frame / self._columns) * self._rect.height)\n self.SetSubRect(sf.IntRect(self._rect.x, self._rect.y, self._rect.x+self._rect.width, self._rect.y+self._rect.height))\n\n Image.render(self, App, point, camera)\n \n def add(self, name, frames, frameRate=0, loop=True):\n try: dummy = self._anims[name]\n except KeyError:\n self._anims[name] = {\"name\":name, \"frames\":frames, \"frameRate\":frameRate, \"loop\":loop}\n return\n raise TypeError(\"Cannot have multiple animations with the same name\")\n \n def play(self, name=\"\", reset=False, frame=0):\n if not reset and self._anim and self._anim[\"name\"] == name: return self._anim\n try: self._anim = self._anims[name]\n except TypeError: self._anim = None\n if not self._anim:\n self._frame = self._index = 0\n self.complete = True\n return None\n self._index = 0\n self._timer = 0\n self._frame = int(self._anim[\"frames\"][frame % len(self._anim[\"frames\"])])\n self.complete = False\n return self._anim\n \n def getFrame(self, column=0, row=0):\n return (row % self._rows) * self._columns + (column % self._columns)\n \n def setFrame(self, colum=0, row=0):\n self._anim = None\n frame = (row % _rows) * _columns + (column % _columns)\n if self._frame == frame: return\n self._frame = frame\n self._timer = 0\n\n def randFrame(self):\n self._frame = math.randint(self._frameCount)\n \n def setAnimFrame(self, name, index):\n frames = self._anims[name][\"frames\"]\n index %= len(frames)\n if index < 0: index += len(frames)\n self._frame = frames[index]\n\n def set_frame(self, value):\n self._anim = False\n value %= self._frameCount\n if value < 0: value += self._frameCount\n if self._frame == value: return\n self._frame = value\n self._timer = 0\n frame = property(lambda self: self._frame, set_frame)\n\n def set_index(self, value):\n if not self._anim: return\n value %= len(self._anim[\"frames\"])\n if self._index == value: return;\n self._index = value\n self._frame = self._anim[\"frames\"][self._index]\n self._timer = 0\n index = property(lambda self: self._index if self._anim else 0, set_index)\n\n frameCount = property(lambda self: self._frameCount)\n columns = property(lambda self: self._columns)\n rows = property(lambda self: self._rows)\n currentAnim = property(lambda self: self._anim[\"name\"] if self._anim else \"\")\n\nclass Tilemap(Graphic, sf.Sprite):\n def __init__(self, loc, width, height, tileWidth, tileHeight):\n Graphic.__init__(self)\n\n if type(loc) == str: self.img = GetImage(loc)\n elif type(loc) == sf.Image: self.img = loc\n else: raise TypeError(\"Please pass the path to an image or a sf.Image instance\")\n sf.Sprite.__init__(self, self.img)\n\n self._width = width\n self._height = height\n self._columns = int(math.ceil(width / tileWidth))\n self._rows = int(math.ceil(height / tileHeight))\n self._tileCols = self.GetImage().GetWidth() / tileWidth\n self._tileRows = self.GetImage().GetHeight() / tileHeight\n self._tile = Rectangle(0, 0, tileWidth, tileHeight)\n\n #-1 == do not draw\n self._map = [[-1 for j in range(self._rows)] for i in range(self._columns)]\n \n def setTile(self, column, row, index):\n self._map[column][row] = index\n \n def clearTile(self, column, row):\n self.setTile(column, row, -1)\n \n def getTile(self, column, row):\n return self._map[column][row]\n \n def setRect(self, column, row, width=1, height=1, index=0):\n for cl in range(column, column+width):\n for rw in range(row, row+height):\n self._map[cl][rw] = index\n \n def clearRect(self, column, row, width=1, height=1):\n self.setRect(column, row, height, width, -1)\n\n def render(self, App, point=Point(), camera=Punk.camera):\n if not self.visible: return\n for col in range(len(self._map)):\n for row in range(len(self._map[col])):\n tile = self._map[col][row]\n if not tile == -1:\n self._tile.x = int((tile % self._tileCols) * self._tile.width)\n self._tile.y = int(math.ceil(tile / self._tileCols) * self._tile.height)\n #print self._tile.x, self._tile.y\n self.SetSubRect(sf.IntRect(self._tile.x, self._tile.y, self._tile.x+self._tile.width, self._tile.y+self._tile.height))\n\n offsetx = int(self.x + col*self._tile.width - self.originX - camera.x * self.scrollX)\n offsety = int(self.y + row*self._tile.height - self.originY - camera.y * self.scrollY)\n if self.relative: offsetx += point.x; offsety += point.y\n self.SetPosition(offsetx, offsety)\n\n App.Draw(self)\n\nclass Shape(Graphic, sf.Shape):\n def __init__(self):\n \"\"\"Create a shape\"\"\"\n Graphic.__init__(self)\n sf.Shape.__init__(self)\n \n def createRect(self, width, height, colour):\n \"\"\"Predefined rectangle shape\"\"\"\n self.AddPoint(0, 0, colour)\n self.AddPoint(width, 0, colour)\n self.AddPoint(width, height, colour)\n self.AddPoint(0, height, colour)\n\nclass Text(Graphic, sf.String):\n def __init__(self, loc, text=\"\", size=16):\n \"\"\"Create text graphic\n Args:\n loc: location of font\n text: text to display\n size: font size\"\"\"\n Graphic.__init__(self)\n\n self.fnt = GetFont(loc, size)\n\n sf.String.__init__(self)\n self.SetText(text)\n self.SetFont(self.fnt)\n self.SetSize(size)\n \n def set_color(self, value):\n self.SetColor(sf.Color(value[0], value[1], value[2]))\n def get_color(self):\n \"\"\"Get/Set the color of the text\"\"\"\n clr = self.GetColor()\n return (clr.r, clr.g, clr.b)\n color = property(get_color, set_color)\n\n def set_text(self, value): self.SetText(value)\n text = property(lambda self: self.GetText(), set_text)\n\n def set_size(self, value): self.SetSize(value)\n size = property(lambda self: self.GetSize(), set_size)\n\n width = property(lambda self: self.GetCharacterPos(len(self.GetText())-1)[0])\n height = property(lambda self: self.GetSize())\n\nclass Graphiclist(object):\n def __init__(self, *args):\n \"\"\"List of graphics to render\"\"\"\n self.list = args\n \n def add(self, toAdd):\n self.list.append(toAdd)\n def remove(self, toRem):\n self.list.remove(toRem)\n \n def render(self, App, point=Point(), camera=Punk.camera):\n for obj in self.list:\n obj.render(App, point, camera)\n\n#Caches\nimageCache = {}\ndef GetImage(loc):\n try: #Will only run if already loaded\n return imageCache[loc]\n except KeyError:\n Image = sf.Image()\n Image.SetSmooth(False)\n if not Image.LoadFromFile(loc):\n return None\n imageCache[loc] = Image\n return Image\n\nfontCache = {}\ndef GetFont(loc, size):\n try:\n fnt = fontCache[loc]\n old_size = fnt.GetCharacterSize()\n if size < old_size:\n return fnt\n except KeyError: pass\n Font = sf.Font()\n if not Font.LoadFromFile(loc, size):\n return None\n fontCache[loc] = Font\n return Font\n","sub_path":"Game/pypunk/Graphics.py","file_name":"Graphics.py","file_ext":"py","file_size_in_byte":12528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50389121","text":"class Solution(object):\n\tdef findKthLargest(self, nums, k):\n\t\t\"\"\"\n\t\t:type nums: List[int]\n\t\t:type k: int\n\t\t:rtype: int\n\t\t\"\"\"\n\t\tlength = len(nums)\n\t\tstart, end = 0, len(nums) - 1\n\t\twhile(start < end):\n\t\t\tpivot, pivotIndex = self.partion(nums, start, end)\n\t\t\tif(k <= pivotIndex):\n\t\t\t\tend = pivotIndex - 1\n\t\t\telse:\n\t\t\t\tstart = pivotIndex + 1\n\t\t\tprint(nums, start, end, pivot, pivotIndex)\n\t\treturn nums[k - 1]\n\n\tdef partion(self, nums, start, end):\n\t\timport random\n\t\tpivotIndex = random.randint(start, end)\n\t\tpivot = nums[pivotIndex]\n\t\t\n\t\tself.swap(nums, end, pivotIndex)\n\t\ti = j = start\n\t\twhile(j < end):\n\t\t\tif(nums[j] >= pivot):\n\t\t\t\ttmp = nums[j]\n\t\t\t\tnums[j] = nums[i]\n\t\t\t\tnums[i] = tmp\n\t\t\t\ti += 1\n\t\t\tj += 1\n\t\tself.swap(nums, end, i)\n\t\treturn pivot, i\n\n\tdef swap(self, nums, i, j):\n\t\ttmp = nums[i]\n\t\tnums[i] = nums[j]\n\t\tnums[j] = tmp\n\nif(__name__ == '__main__'):\n\ts = Solution()\n\tnums = [3,2,1,5,6,4]\n\tk = 2\n\tprint(s.findKthLargest(nums, k))","sub_path":"LeetCode/215M_Kth_Largest_Element_in_an_Array.py","file_name":"215M_Kth_Largest_Element_in_an_Array.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"45671835","text":"import json\nimport requests\nimport random\nimport logging\n\nimport consul\n\nfrom ServiceDiscovery.config import config as _config\n\nconfig = _config()\n\nlog = logging.getLogger(__name__)\n\n\nclass ServiceDiscovery(object):\n \"\"\"Main entry point for ServiceDiscovery\"\"\"\n\n def __init__(self, endpoint=None):\n if endpoint is None:\n endpoint = config.get('ServiceDiscovery', 'sd')\n self.consul = consul.Client(endpoint=endpoint)\n self.services = {}\n\n def _refresh(self):\n log.info(\"Refreshing Service definitions\")\n self.services = {\n k: self.consul.info(k)\n for k in self.consul.list().keys()\n }\n\n def register(self, service, datacenter=None, check=None, tags=None):\n log.debug(\"About to register service: %s\", service)\n Node = service.node\n if check is None:\n log.debug('setting default check for %s based on TCP %s:%s ',\n service.name, service.addr, service.port)\n check = {\n # 'ServiceID': service.id,\n 'Node': Node,\n 'Name': \"{} on {}:{}\".format(\n service.name, service.addr, service.port),\n 'Tcp': \"{}:{}\".format(service.addr, service.port),\n 'Interval': '30s',\n 'Timeout': '2s',\n # 'Status': 'passing'\n }\n else:\n log.debug('setting custom check for %s: %s', service.name, check)\n\n if tags is None:\n tags = [service.id, 'v1']\n\n # Address = service.addr\n serviceRepr = service.consulRepr()\n serviceRepr['Tags'] = tags\n \n r = self.consul.register(\n id=service.id,\n address=service.addr,\n port=service.port,\n name=service.name,\n check=check)\n\n log.debug(\"Register Response: %s\", r)\n \n def unregister(self, service):\n log.debug(\"About to unregister service: %s\", service)\n self.consul.deregister(id=service.id)\n\n def getServices(self, key):\n \"\"\"get all services of type `key`\"\"\"\n if key not in self.services:\n self._refresh()\n if key not in self.services:\n return []\n \n services = self.services[key]\n log.debug(\"%s\", services)\n return [\n \"https://{}:{}\".format(\n x['ServiceAddress'],\n x['ServicePort'])\n for x in services\n ]\n\n def getService(self, key):\n \"\"\"get a random service of type `key`\"\"\"\n services = self.getServices(key)\n if len(services) == 0:\n raise Exception('No Services found with key=\"%s\"' % key)\n return random.choice(services)\n\n def call(self, key, path, ck_health=True, **kwargs):\n base_url = self.getService(key)\n retries = 10\n while retries:\n if ck_health:\n res = requests.get(base_url + \"/health\", **kwargs)\n if res.status_code != 200:\n # handle it\n self._refresh()\n services = self._services[key]\n \n retries -= 1\n \n \n url = \"\".join(base_url, path)\n res = requests.get(url, **kwargs)\n return res.json()\n \n\nclass Service(object):\n def __init__(self, name, addr, port, node=None):\n self.name = name\n self.addr = addr\n if node is None:\n node = addr.split('.')[0]\n self.node = node\n self.port = port\n self.id = \"{}-{}-{}\".format(self.name, self.node, self.port)\n\n def to_json(self):\n \"JSON repr of this Service\"\n return json.dumps(self.to_dict())\n\n def to_dict(self):\n \"\"\"Dict repr of this Service\"\"\"\n d = {k: v for k, v in self.__dict__.iteritems() if k != \"sd\"}\n return d\n\n def __repr__(self):\n return \"<Service id:%s, name:%s, addr:%s, port:%s>\" % \\\n (self.id, self.name, self.addr, self.port)\n\n def consulRepr(self):\n return {\n 'ID': self.id,\n 'Node': self.node,\n 'Service': self.name,\n 'Address': self.addr,\n 'Port': int(self.port)\n }\n","sub_path":"ServiceDiscovery/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"43353948","text":"#Import necessary libraries\nimport json, requests, sys\n\n#Define universal constants\nBREACHES_URL = \"https://haveibeenpwned.com/api/v2/breaches\"\n\ndef breach_get(url):\n\t\"\"\"Makes a get request from the haveibeenpwned API. Returns the \n\tresponse code\"\"\"\n\tbreach_response = requests.get(BREACHES_URL)\n\treturn breach_response\n\t\ndef make_breach_dict(code):\n\t\"\"\"Uses status code from breach_get to determine API call's success.\n\tIf successful, creates a python dictionary from the returned JSON\"\"\"\n\tif (int(code.status_code)==200):\n\t\tbreach_dict = json.loads(code.text)\n\t\treturn breach_dict\n\telse:\n\t\tprint(\"Request to the API failed\")\n\t\tsys.exit()\n\t\t\ndef limit_breach_dict(dictionary):\n\t\"\"\"Limits the full breach dictionary to only the necessary information\n\tfor determining the average breach size. Creates a dictionary of \n\tkey-value pairs for the breach name and size.\"\"\"\n\tbreach_limited = {}\n\tfor breach in dictionary:\n\t\tbreach_limited[breach['Name']] = breach['PwnCount']\t\n\treturn breach_limited\n\t\ndef average_size(dictionary):\n\t\"\"\"Calculates the average size of a breach based on PwnCount\"\"\"\n\tcount = 0\n\ttotal = 0\n\tfor breach in dictionary:\n\t\tcount += 1\n\t\ttotal = total + dictionary[breach]\n\taverage = total / count\n\treturn average\n\t\ndef breach_max(dictionary):\n\t\"\"\"Returns the largest breach in the dictionary\"\"\"\n\tfor breach in dictionary:\n\t\tif dictionary[breach] == max(dictionary.values()):\n\t\t\treturn breach\n\t\t\t\ndef breach_min(dictionary):\n\t\"\"\"Returns the smallest breach in the dictionary\"\"\"\n\tfor breach in dictionary:\n\t\tif dictionary[breach] == min(dictionary.values()):\n\t\t\treturn breach\n\t\ndef breach_file(dictionary, average):\n\t\"\"\"Creates a file with a list of all breaches in the system, as well\n\tas the largest and smallest breaches and the average size of a breach\"\"\"\n\twith open('breaches.txt', 'a') as b:\n\t\tfor breach in dictionary:\n\t\t\tb.write(\"%s: %d\\n\" % (breach, dictionary[breach]))\n\t\tb.write(\"\\n\\n\\n\")\n\t\tb.write(\"Largest breach - %s: %d\\n\" % (breach_max(dictionary), max(dictionary.values())))\n\t\tb.write(\"Smallest breach - %s: %d\\n\" % (breach_min(dictionary), min(dictionary.values())))\n\t\tb.write(\"Average breach size - %f\" % average)\n\t\t\ndef print_breach():\n\t\"\"\"Prints the contents of the breach file to the console for quick\n\treview\"\"\"\n\twith open('breaches.txt', 'r') as b:\n\t\tfor line in b:\n\t\t\tprint(line)\n\t\ndef main():\n\t\"\"\"Calls each function in order to call the api,create the breach \n\tfile and print it to the console\"\"\"\n\t\n\t#Call breach_get to make a call to the API to return status code\n\tcode = breach_get(BREACHES_URL)\n\t\n\t#Pass status code to make_breach_dict\n\tbreach_dict = make_breach_dict(code)\n\tfor line in breach_dict:\n\t\tprint(line)\n\t\n\t#Limit breach_dict to only relevant information\n\tbreach_limited = limit_breach_dict(breach_dict)\n\t\n\t#Find average size of breaches\n\taverage = average_size(breach_limited)\n\n\t#Write a file with all breaches, largest and smallest breaches, and average\n\tbreach_file(breach_limited, average)\n\t\n\t#Print contents of breaches.txt to screen\n\t#print_breach()\n\t\nmain()\n","sub_path":"week8api/week8api.py","file_name":"week8api.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"374249912","text":"#################### syllogism production model ###################\n\n# this is the simplest type of act-r model\n# it uses only the production system and one buffer\n# the buffer represents the focus of thought\n# we call it the focus buffer but it is often called the goal buffer\n# productions fire if they match the focus buffer\n# each production changes the contents of focus buffer so a different production will fire on the next cycle\n\n\nimport ccm \nlog=ccm.log() \n\nfrom ccm.lib.actr import * \n\n#####\n# Python ACT-R requires an environment\n# but in this case we will not be using anything in the environment\n# so we 'pass' on putting things in there\n\nclass MyEnvironment(ccm.Model):\n pass\n\n#####\n# create an act-r agent\n\nclass MyAgent(ACTR):\n \n focus=Buffer()\n DMbuffer=Buffer() # create a buffer for the declarative memory (henceforth DM)\n\n DM=Memory(DMbuffer) # create DM and connect it to its buffer \n\n focus.set('goal:syllogism step:conclusion')\n \n DM.add('premise:one subject:socrates isa:man')\n DM.add('premise:two subject:man isa:mortal')\n\n def conclusion(focus='goal:syllogism step:conclusion'):\n DM.add('conclusion:one subject:socrates isa:mortal')\n DM.request('conclusion:one subject:?subject isa:isa?')\n focus.set('goal:syllogism step:declare_conclusion')\n\n def declare_conclusion(focus='goal:syllogism step:declare_conclusion'):\n print(subject, isa)\n\ntim=MyAgent() # name the agent\nsubway=MyEnvironment() # name the environment\nsubway.agent=tim # put the agent in the environment\nccm.log_everything(subway) # print out what happens in the environment\n\nsubway.run() # run the environment\nccm.finished() # stop the environment\n","sub_path":"syllogism.py","file_name":"syllogism.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"169746826","text":"#!/usr/bin/env python\n\nfrom flask import Flask, request, jsonify\nimport os\nimport urlparse\nimport psycopg2\n\nimport urlparse\nimport psycopg2\n\napp = Flask(__name__, static_url_path='')\napp.config['DEBUG'] = True\n\n# GET request this for the national data and stuff\n# return json if possible\n\nSTATES = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']\nCANDIDATES = ['biden', 'clinton', 'omalley', 'sanders', 'warren', 'bush', 'carson', 'christie', 'cruz', 'huckabee', 'paul', 'perry', 'rubio', 'walker', 'santorum']\n\ndef getConnection():\n urlparse.uses_netloc.append(\"postgres\")\n url = urlparse.urlparse(os.environ[\"DATABASE_URL\"])\n return psycopg2.connect(database=url.path[1:],user=url.username,password=url.password,host=url.hostname,port=url.port)\n\n@app.route('/random')\ndef fillRandom():\n conn = getConnection()\n cursor = conn.cursor()\n for c in CANDIDATES:\n for s in STATES:\n cursor.execute(\"INSERT INTO tweets (candidate, state, pos, neg, neu, color) VALUES (%s,%s,%s,%s,%s,0)\", (c, s, random() * 1000, random() * 1000, random() * 1000))\n conn.commit()\n conn.close()\n return 'Test data generated!'\n\n@app.route('/testdb')\ndef testDatabase():\n try:\n conn = getConnection()\n if conn != None:\n conn.close()\n return \"<pre>Database connected successfully!</pre>\"\n return \"<pre>Failed to connect to database!</pre>\"\n except Exception as e:\n return \"<pre>\" + str(e) + \"</pre>\"\n\nfrom random import random\n\n@app.route('/nation')\ndef getNation():\n p = request.args.get('p')\n conn = getConnection()\n cursor = conn.cursor()\n cursor.execute(\"SELECT state, pos, neg, neu FROM tweets WHERE candidate = %s\", [p])\n rs = cursor.fetchall()\n conn.close()\n db = dict()\n for i in rs:\n db[i[0]] = [i[1], i[2], i[3]]\n for j in STATES:\n if not j in db:\n db[j] = [0, 0, 0]\n assert len(db) >= 50\n return jsonify(**db)\n\n@app.route('/')\ndef root():\n return app.send_static_file('index.html')\n\n\nimport sys\n\nif __name__ == '__main__':\n # probably should use gunicorn or something\n app.run(host='0.0.0.0', port=int(sys.argv[1]))\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"530958617","text":"import re\r\n\r\n#open the file to be written from, for reading\r\nemailDoc = open(r'')\r\nemailDocContents = emailDoc.read()\r\n\r\n#create a regex object for the email address\r\nemailRegexObj = re.compile(r'[a-zA-Z0-9._]+@[a-zA-Z0-9]+\\.[a-z]+')\r\nmatchObj = emailRegexObj.findall(emailDocContents)\r\n\r\n#append all the email address in the match object to a list\r\nemailList = []\r\nfor items in matchObj:\r\n emailList.append(items)\r\n\r\n#write the email addresses to the desired file\r\n\r\n#open the destination file for writing\r\ndestinationEmailFile = open(r'', 'w')\r\nfor items in emailList:\r\n\tdestinationEmailFile.write(items + '\\n')\r\n\r\n#close all open files\r\nemailDoc.close()\r\ndestinationEmailFile.close()\r\n\r\n#report success\r\nprint(\"copy has been concluded\") \r\n\r\n#separate the addresses by domain\r\nsepAdd = open(r'')\r\nsepAddContent = sepAdd.readlines()\r\n\r\ngmailAdd = open(r'', 'w')\r\nyahooAdd = open(r'', 'w')\r\notherAdd = open(r'', 'w')\r\n\r\nfor i in range(len(sepAddContent)):\r\n if \"gmail\" in sepAddContent[i]:\r\n gmailAdd.write(sepAddContent[i])\r\n elif \"yahoo\" in sepAddContent[i]:\r\n yahooAdd.write(sepAddContent[i])\r\n else:\r\n otherAdd.write(sepAddContent[i])\r\n \r\n \r\n\r\ngmailAdd.close()\r\notherAdd.close()\r\nyahooAdd.close() \r\nsepAdd.close()\r\n\r\nprint(\"all operation complete\")\r\n \r\n \r\n\r\n\r\n","sub_path":"emailRegex.py","file_name":"emailRegex.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116746368","text":"import asyncio\nimport aiohttp\n\nPOP20_CC = ('CN IN US ID BR PK NG BD RU JP MX PH VN ET EG DE IR TR CD FR').split()\nBASE_URL = 'http://flupy.org/data/flags'\nDEST_DIR = './downloads/'\n\ndef save_flag(img,filename):\n path=os.path.join(DEST_DIR,filename)\n with open(path,'wb') as fp:\n fp.write(img)\n\ndef get_flag(cc):\n url='{}/{cc}/{cc}.gif'.format(BASE_URL,cc=cc.lower())\n resp=requests.get(url)\n return resp.content\n\n\n@asyncio.coroutine\ndef get_flag(cc):\n url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())\n resp = yield from aiohttp.request('GET', url)\n image = yield from resp.read()\n return image\n\n@asyncio.coroutine\ndef download_one(cc):\n image = yield from get_flag(cc)\n show(cc)\n save_flag(image, cc.lower() + '.gif')\n return cc\n\ndef download_many(cc_list):\n loop = asyncio.get_event_loop()\n to_do = [download_one(cc) for cc in sorted(cc_list)]\n wait_coro = asyncio.wait(to_do)\n res, _ = loop.run_until_complete(wait_coro)\n loop.close()\n return len(res)\n\n\ndef main(download_many):\n t0=time.time()\n count=download_many(POP20_CC)\n elapsed=time.time()-t0\n print('\\n{} flags downloaded in {:.2f}s'.format(count,elapsed))\n\nif __name__ == '__main__':\n main(download_many)\n","sub_path":"fluent-python/asyncio/async-download.py","file_name":"async-download.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177941942","text":"#!/usr/bin/python\n# Software License Agreement (BSD License)\n#\n# Copyright (c) 2013, Juergen Sturm, TUM\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of TUM nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# Requirements: \n# sudo apt-get install python-argparse\n\n\"\"\"\nThe Kinect provides the color and depth images in an un-synchronized way. This means that the set of time stamps from the color images do not intersect with those of the depth images. Therefore, we need some way of associating color images to depth images.\n\nFor this purpose, you can use the ''associate.py'' script. It reads the time stamps from the rgb.txt file and the depth.txt file, and joins them by finding the best matches.\n\"\"\"\n\nimport argparse\nimport sys\nimport os\nimport numpy as np\nfrom plotly import tools\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\ndef read_file_list(filename):\n \"\"\"\n Reads a Pose from a text file. \n \n File format:\n The file format is \"stamp x y yaw where stamp denotes the time stamp\n \n \"\"\"\n file = open(filename)\n data = file.read()\n lines = data.replace(\"\\t\",\" \").split(\"\\n\") \n list = [[v.strip() for v in line.split(\" \") if v.strip()!=\"\"] for line in lines if len(line)>0 and line[0]!=\"#\"]\n\n #list = [(float(l[0]),l[1:]) for l in list if len(l)>1]\n #list = [(float(l[i]) for i in l ) for l in list if len(l)>1]\n list = [[float(l[0]),float(l[1]), float(l[2]), float(l[3])] for l in list if len(l)>1]\n return list\n\nif __name__ == '__main__':\n \n # parse command line\n parser = argparse.ArgumentParser(description='''\n This script extracts a trajectory from a txt file and plots it \n ''')\n parser.add_argument('odom_file', help='odom text file (format: AMCL Odometry data)')\n #parser.add_argument('second_file', help='second text file (format: Global Plan data)')\n args = parser.parse_args()\n\n tools.set_credentials_file(username='ajithkrishnanbm', api_key='MCCZv2hEgYCcbPL9gQ92')\n\n odom_list = read_file_list(args.odom_file)\n pose_list_x = []\n pose_list_y = []\n yaw_list = []\n time_list = []\n\n for pose in odom_list:\n time = pose[0]\n pose_x = pose[1]\n pose_y = pose[1]\n yaw = pose[2]\n\n pose_list_x.append(pose_x)\n pose_list_y.append(pose_y)\n yaw_list.append(yaw)\n time_list.append(time)\n \n trace_x = go.Scatter(x=time_list, y=pose_list_x, name='x')\n trace_y = go.Scatter(x=time_list, y=pose_list_y, name='y')\n trace_yaw = go.Scatter(x=time_list, y=yaw_list, name='yaw')\n\n #fig = tools.make_subplots(rows=3, cols=1, specs=[[{}], [{}], [{}]], shared_xaxes=True, shared_yaxes=True)\n\n #fig.append_trace(trace_x, 3, 1)\n #fig.append_trace(trace_y, 2, 1)\n #fig.append_trace(trace_yaw, 1, 1)\n\n #fig['layout'].update(height=600, width=600, title='AGV odometry')\n #py.plot(fig, filename='odom_plotly')\n\n data = [trace_x, trace_y, trace_yaw]\n layout = go.Layout(\n title='AGV odometry',\n xaxis=dict(title='Timestamp'),\n yaxis=dict(title='Odometry'),\n legend=dict(traceorder='reversed'),\n )\n\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename='AGV Odomentry - stacked')\n\n \n \n\n\n","sub_path":"position_controller/scripts/plot_plotly.py","file_name":"plot_plotly.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"412897222","text":"import sublime\nimport sublime_plugin\nimport sys\nimport os\nimport re\nimport subprocess\n\nsettings = sublime.load_settings('Corona.sublime-settings')\n\nclass Pref:\n def load(self):\n Pref.path_corona_simulator = settings.get('path_corona_simulator', \"/Applications/CoronaSDK/simulator\")\n Pref.skin = settings.get('skin', \"iPhone4\")\n\nPref().load()\n\nsettings.add_on_change('path_corona_simulator', lambda:Pref().load())\nsettings.add_on_change('skin', lambda:Pref().load())\n\nclass CoronaCommand(sublime_plugin.WindowCommand):\n def run(self, skin=None):\n \n if skin:\n skin = skin[0]\n else:\n skin = Pref.skin\n \n path_project = os.path.dirname(self.window.active_view().file_name())\n path_package = sublime.packages_path()\n path_coronascpt = re.compile(' ').sub('\\ ', path_package) + '/Corona/corona.scpt'\n\n proces = subprocess.Popen('osascript -s s '+path_coronascpt+' '+Pref.path_corona_simulator+' '+path_project+' '+skin, shell=True)\n\n proces.wait()","sub_path":"Corona/corona.py","file_name":"corona.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"439371945","text":"print('b.')\n'''\nVerilen iki listeden ilk listenin tüm elemanlarının tam bölebildiği bir sayıların, ikinci listenin tüm\nelemanlarını tam bölebildiği durumların sayısını tespit eden bir fonksiyon yazınız.\nBu tür sayılara iki liste arası sayılar diyeceğiz. Bu tür sayıların sayısını tespit etmeniz\ngerekmektedir.\nÖrnek:\nİki liste verildiğini düşünelim:\na = [2, 6]\nb = [24, 36]\nBu durumda iki liste arası sayılar 6 ve 12’dir.\nİlk değer (6) için:\n6 % 2 = 0\n6 % 6 = 0\n24 % 6 = 0\n36 % 6 = 0\nİkinci değer (12) için:\n12 % 2 = 0\n12 % 6 = 0\n24 % 12 = 0\n36 % 12 = 0\nFonksiyon Tanımı\ngetTotalX fonksiyonunu tamamlayarak iki liste arası sayıların miktarını verecek şekle getiriniz.\ngetTotalX fonksiyonu iki parametre almaktadır:\na: integerlardan oluşan bir liste\nb: integerlardan oluşan bir liste\nInput Formatı\nİlk input satırı boşluklarla birbirinden ayrılmış iki integerdan (m ve n) oluşmalıdır. Bu integerlar a\nve b listelerinin eleman sayılarını belirleyecektir.\nİkinci input satırı birbirinden boşlukla ayrılmış, birbirinden farklı ve a listesinin elemanlarını ( a\n[ i ] ) oluşturan n tane integerdan oluşmalıdır. Koşul: 0 <= i <=n.\nÜçüncü input satırı birbirinden boşlukla ayrılmış, birbirinden farklı ve b listesinin elemanlarını\n( b[ j ] ) oluşturan m tane integerdan oluşmalıdır. Koşul: 0 <= j <=m.\nKısıtlamalar:\n1 <= n,m <=10\n1 <a [i] <100\n1 <= b[j] <=100\nOutput Formatı:\na ve b listelerinin arasında olan (yukarıda belirtilen koşulları sağlayan) sayıların miktarını output\nolarak vermeniz gerekmektedir.\nÖrnek Input:\n2 3\n2 4\n16 32 96\nÖrnek Output:\n3\nAçıklama:\n2 ve 4 (a listesinin elemanları) sayıları 4, 8, 12 ve 16 sayılarına tam bölünmektedir.\n4, 8 ve 16 sayıları 16, 32, 96 sayılarına (b listesinin elemanları) tam olarak bölünmektedir.\n4, 8 ve 16 sayıları a listesinin elemanları tarafından tam bölünebilen ve b listesinin elemanlarını\ntam bölebilen sayılar olduğundan cevap 3 olacaktır.\n'''\ndef getTotalX():\n first_multiple_input = input('aralarinda bosluk birakarak birinci ve '\n 'ikinci listenin elaman sayilarini giriniz:').split() #split ile bosluklardan ayirdik\n n = int(first_multiple_input[0])\n m = int(first_multiple_input[1])\n birinci_liste = list(map(int, input('birinci listenin elamanlarini aralarinda boslik birakarak giriniz :').split()))\n ikinci_liste = list(map(int, input('ikinci listenin elamanlarini aralarinda boslik birakarak giriniz :').split()))\n b = []\n a = []\n # ilk listenin max elamani ile ikinci listenin min elamani arasindaki sayilari sayilari bulduk\n # range ile buldugumuz elamanlari birinci listenin elamanlarinin ikisinede bolunenleri ayikladik\n for i in range(max(birinci_liste), min(ikinci_liste) + 1):\n for j in birinci_liste:\n if i % j != 0:\n break\n else:\n a.append(i)\n #ikinci listenin elamanlarinin hepsini bolenlerini bulduk\n for j in a:\n for i in ikinci_liste:\n if i % j != 0:\n break\n else:\n b.append(j)\n # birinci listeye bolunen ikinci lisyeyi bolen elamanlarin sayisi\n print(f'birinci listeye bolunen,ikinci lisyeyi bolen elamanlarin sayisi:{len(b)}')\ngetTotalX()\n","sub_path":"2.odev.py","file_name":"2.odev.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"175545041","text":"import os\nimport unittest\n\nfrom mock import Mock\n\nfrom conans.client.cache.cache import ClientCache\nfrom conans.client.graph.graph import RECIPE_CONSUMER, RECIPE_INCACHE\nfrom conans.client.graph.graph_manager import GraphManager\nfrom conans.client.graph.proxy import ConanProxy\nfrom conans.client.graph.python_requires import ConanPythonRequire\nfrom conans.client.graph.range_resolver import RangeResolver\nfrom conans.client.installer import BinaryInstaller\nfrom conans.client.loader import ConanFileLoader\nfrom conans.client.recorder.action_recorder import ActionRecorder\nfrom conans.model.graph_info import GraphInfo\nfrom conans.model.manifest import FileTreeManifest\nfrom conans.model.options import OptionsValues\nfrom conans.model.profile import Profile\nfrom conans.model.ref import ConanFileReference\nfrom conans.test.unittests.model.transitive_reqs_test import MockSearchRemote\nfrom conans.test.utils.conanfile import TestConanFile\nfrom conans.test.utils.test_files import temp_folder\nfrom conans.test.utils.tools import TestBufferConanOutput\nfrom conans.util.files import save\nfrom conans.errors import ConanException\nfrom parameterized import parameterized\n\n\nclass GraphManagerTest(unittest.TestCase):\n\n def setUp(self):\n self.output = TestBufferConanOutput()\n cache_folder = temp_folder()\n cache = ClientCache(cache_folder, os.path.join(cache_folder, \".conan\"), self.output)\n self.cache = cache\n self.remote_search = MockSearchRemote()\n remote_manager = None\n self.resolver = RangeResolver(cache, self.remote_search)\n proxy = ConanProxy(cache, self.output, remote_manager)\n self.loader = ConanFileLoader(None, self.output, ConanPythonRequire(None, None))\n self.manager = GraphManager(self.output, cache, remote_manager, self.loader, proxy,\n self.resolver)\n hook_manager = Mock()\n recorder = Mock()\n self.binary_installer = BinaryInstaller(cache, self.output, remote_manager, recorder,\n hook_manager)\n\n def _cache_recipe(self, reference, test_conanfile, revision=None):\n if isinstance(test_conanfile, TestConanFile):\n test_conanfile.info = True\n ref = ConanFileReference.loads(reference)\n save(self.cache.conanfile(ref), str(test_conanfile))\n with self.cache.package_layout(ref).update_metadata() as metadata:\n metadata.recipe.revision = revision or \"123\"\n manifest = FileTreeManifest.create(self.cache.export(ref))\n manifest.save(self.cache.export(ref))\n\n def build_graph(self, content, profile_build_requires=None, ref=None):\n path = temp_folder()\n path = os.path.join(path, \"conanfile.py\")\n save(path, str(content))\n self.loader.cached_conanfiles = {}\n\n profile = Profile()\n if profile_build_requires:\n profile.build_requires = profile_build_requires\n profile.process_settings(self.cache)\n update = check_updates = False\n recorder = ActionRecorder()\n remote_name = None\n build_mode = []\n ref = ref or ConanFileReference(None, None, None, None, validate=False)\n options = OptionsValues()\n graph_info = GraphInfo(profile, options, root_ref=ref)\n deps_graph, _ = self.manager.load_graph(path, None, graph_info,\n build_mode, check_updates, update,\n remote_name, recorder)\n self.binary_installer.install(deps_graph, False, graph_info)\n return deps_graph\n\n def _check_node(self, node, ref, deps, build_deps, dependents, closure, public_deps):\n conanfile = node.conanfile\n ref = ConanFileReference.loads(str(ref))\n self.assertEqual(node.ref.full_repr(), ref.full_repr())\n self.assertEqual(conanfile.name, ref.name)\n self.assertEqual(len(node.dependencies), len(deps) + len(build_deps))\n self.assertEqual(len(node.dependants), len(dependents))\n\n public_deps = {n.name: n for n in public_deps}\n self.assertEqual(node.public_deps, public_deps)\n\n # The recipe requires is resolved to the reference WITH revision!\n self.assertEqual(len(deps), len(conanfile.requires))\n for dep in deps:\n self.assertEqual(conanfile.requires[dep.name].ref,\n dep.ref)\n\n self.assertEqual(closure, node.public_closure)\n libs = []\n envs = []\n for n in closure:\n libs.append(\"mylib%s%slib\" % (n.ref.name, n.ref.version))\n envs.append(\"myenv%s%senv\" % (n.ref.name, n.ref.version))\n self.assertEqual(conanfile.deps_cpp_info.libs, libs)\n env = {\"MYENV\": envs} if envs else {}\n self.assertEqual(conanfile.deps_env_info.vars, env)\n\n\nclass TransitiveGraphTest(GraphManagerTest):\n def test_basic(self):\n # say/0.1\n deps_graph = self.build_graph(TestConanFile(\"Say\", \"0.1\"))\n self.assertEqual(1, len(deps_graph.nodes))\n node = deps_graph.root\n self.assertEqual(node.conanfile.name, \"Say\")\n self.assertEqual(len(node.dependencies), 0)\n self.assertEqual(len(node.dependants), 0)\n\n def test_transitive(self):\n # app -> libb0.1\n libb_ref = \"libb/0.1@user/testing\"\n self._cache_recipe(libb_ref, TestConanFile(\"libb\", \"0.1\"))\n deps_graph = self.build_graph(TestConanFile(\"app\", \"0.1\",\n requires=[libb_ref]))\n self.assertEqual(2, len(deps_graph.nodes))\n app = deps_graph.root\n self.assertEqual(app.conanfile.name, \"app\")\n self.assertEqual(len(app.dependencies), 1)\n self.assertEqual(len(app.dependants), 0)\n self.assertEqual(app.recipe, RECIPE_CONSUMER)\n\n libb = app.dependencies[0].dst\n self.assertEqual(libb.conanfile.name, \"libb\")\n self.assertEqual(len(libb.dependencies), 0)\n self.assertEqual(len(libb.dependants), 1)\n self.assertEqual(libb.inverse_neighbors(), [app])\n self.assertEqual(libb.ancestors, set([app.ref.name]))\n self.assertEqual(libb.recipe, RECIPE_INCACHE)\n\n self.assertEqual(app.public_closure, [libb])\n self.assertEqual(libb.public_closure, [])\n self.assertEqual(app.public_deps, {\"app\": app, \"libb\": libb})\n self.assertEqual(libb.public_deps, app.public_deps)\n\n def test_transitive_two_levels(self):\n # app -> libb0.1 -> liba0.1\n liba_ref = \"liba/0.1@user/testing\"\n libb_ref = \"libb/0.1@user/testing\"\n self._cache_recipe(liba_ref, TestConanFile(\"liba\", \"0.1\"))\n self._cache_recipe(libb_ref, TestConanFile(\"libb\", \"0.1\", requires=[liba_ref]))\n deps_graph = self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[libb_ref]))\n\n self.assertEqual(3, len(deps_graph.nodes))\n app = deps_graph.root\n libb = app.dependencies[0].dst\n liba = libb.dependencies[0].dst\n\n # No Revision??? Because of consumer?\n self._check_node(app, \"app/0.1@None/None\", deps=[libb], build_deps=[], dependents=[],\n closure=[libb, liba], public_deps=[app, libb, liba])\n self._check_node(libb, \"libb/0.1@user/testing#123\", deps=[liba], build_deps=[],\n dependents=[app], closure=[liba], public_deps=[app, libb, liba])\n self._check_node(liba, \"liba/0.1@user/testing#123\", deps=[], build_deps=[],\n dependents=[libb], closure=[], public_deps=[app, libb, liba])\n\n def test_diamond(self):\n # app -> libb0.1 -> liba0.1\n # \\-> libc0.1 ->/\n liba_ref = \"liba/0.1@user/testing\"\n libb_ref = \"libb/0.1@user/testing\"\n libc_ref = \"libc/0.1@user/testing\"\n self._cache_recipe(liba_ref, TestConanFile(\"liba\", \"0.1\"))\n self._cache_recipe(libb_ref, TestConanFile(\"libb\", \"0.1\", requires=[liba_ref]))\n self._cache_recipe(libc_ref, TestConanFile(\"libc\", \"0.1\", requires=[liba_ref]))\n deps_graph = self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[libb_ref, libc_ref]))\n\n self.assertEqual(4, len(deps_graph.nodes))\n app = deps_graph.root\n libb = app.dependencies[0].dst\n libc = app.dependencies[1].dst\n liba = libb.dependencies[0].dst\n\n # No Revision??? Because of consumer?\n self._check_node(app, \"app/0.1@None/None\", deps=[libb, libc], build_deps=[], dependents=[],\n closure=[libb, libc, liba], public_deps=[app, libb, libc, liba])\n self._check_node(libb, \"libb/0.1@user/testing#123\", deps=[liba], build_deps=[],\n dependents=[app], closure=[liba], public_deps=[app, libb, libc, liba])\n self._check_node(libb, \"libb/0.1@user/testing#123\", deps=[liba], build_deps=[],\n dependents=[app], closure=[liba], public_deps=[app, libb, libc, liba])\n self._check_node(liba, \"liba/0.1@user/testing#123\", deps=[], build_deps=[],\n dependents=[libb, libc], closure=[], public_deps=[app, libb, libc, liba])\n\n def test_diamond_conflict(self):\n # app -> libb0.1 -> liba0.1\n # \\-> libc0.1 -> liba0.2\n liba_ref = \"liba/0.1@user/testing\"\n liba_ref2 = \"liba/0.2@user/testing\"\n libb_ref = \"libb/0.1@user/testing\"\n libc_ref = \"libc/0.1@user/testing\"\n self._cache_recipe(liba_ref, TestConanFile(\"liba\", \"0.1\"))\n self._cache_recipe(liba_ref2, TestConanFile(\"liba\", \"0.2\"))\n self._cache_recipe(libb_ref, TestConanFile(\"libb\", \"0.1\", requires=[liba_ref]))\n self._cache_recipe(libc_ref, TestConanFile(\"libc\", \"0.1\", requires=[liba_ref2]))\n with self.assertRaisesRegexp(ConanException, \"Requirement liba/0.2@user/testing conflicts\"):\n self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[libb_ref, libc_ref]))\n\n def test_loop(self):\n # app -> libc0.1 -> libb0.1 -> liba0.1 ->|\n # \\<-------------------------|\n liba_ref = \"liba/0.1@user/testing\"\n libb_ref = \"libb/0.1@user/testing\"\n libc_ref = \"libc/0.1@user/testing\"\n self._cache_recipe(liba_ref, TestConanFile(\"liba\", \"0.1\", requires=[libc_ref]))\n self._cache_recipe(libb_ref, TestConanFile(\"libb\", \"0.1\", requires=[liba_ref]))\n self._cache_recipe(libc_ref, TestConanFile(\"libc\", \"0.1\", requires=[libb_ref]))\n with self.assertRaisesRegexp(ConanException, \"Loop detected: 'liba/0.1@user/testing' \"\n \"requires 'libc/0.1@user/testing'\"):\n self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[libc_ref]))\n\n @parameterized.expand([(\"recipe\", ), (\"profile\", )])\n def test_basic_build_require(self, build_require):\n # app -(br)-> tool0.1\n self._cache_recipe(\"tool/0.1@user/testing\", TestConanFile(\"tool\", \"0.1\"))\n if build_require == \"recipe\":\n deps_graph = self.build_graph(TestConanFile(\"app\", \"0.1\",\n build_requires=[\"tool/0.1@user/testing\"]))\n else:\n profile_build_requires = {\"*\": [ConanFileReference.loads(\"tool/0.1@user/testing\")]}\n deps_graph = self.build_graph(TestConanFile(\"app\", \"0.1\"),\n profile_build_requires=profile_build_requires)\n\n # Build requires always apply to the consumer\n self.assertEqual(2, len(deps_graph.nodes))\n app = deps_graph.root\n tool = app.dependencies[0].dst\n\n self._check_node(app, \"app/0.1@None/None\", deps=[], build_deps=[tool], dependents=[],\n closure=[tool], public_deps=[app])\n self._check_node(tool, \"tool/0.1@user/testing#123\", deps=[], build_deps=[],\n dependents=[app], closure=[], public_deps=[tool, app])\n\n def test_transitive_build_require_recipe(self):\n # app -> lib -(br)-> tool\n self._cache_recipe(\"tool/0.1@user/testing\", TestConanFile(\"tool\", \"0.1\"))\n self._cache_recipe(\"lib/0.1@user/testing\",\n TestConanFile(\"lib\", \"0.1\",\n build_requires=[\"tool/0.1@user/testing\"]))\n deps_graph = self.build_graph(TestConanFile(\"app\", \"0.1\",\n requires=[\"lib/0.1@user/testing\"]))\n\n self.assertEqual(3, len(deps_graph.nodes))\n app = deps_graph.root\n lib = app.dependencies[0].dst\n tool = lib.dependencies[0].dst\n\n self._check_node(app, \"app/0.1@None/None\", deps=[lib], build_deps=[], dependents=[],\n closure=[lib], public_deps=[app, lib])\n\n self._check_node(lib, \"lib/0.1@user/testing#123\", deps=[], build_deps=[tool],\n dependents=[app], closure=[tool], public_deps=[app, lib])\n\n self._check_node(tool, \"tool/0.1@user/testing#123\", deps=[], build_deps=[],\n dependents=[lib], closure=[], public_deps=[tool, lib])\n\n def test_loop_build_require(self):\n # app -> lib -(br)-> tool ->|\n # \\<---------------|\n lib_ref = \"lib/0.1@user/testing\"\n self._cache_recipe(\"tool/0.1@user/testing\", TestConanFile(\"tool\", \"0.1\", requires=[lib_ref]))\n self._cache_recipe(lib_ref,\n TestConanFile(\"lib\", \"0.1\",\n build_requires=[\"tool/0.1@user/testing\"]))\n with self.assertRaisesRegexp(ConanException, \"Loop detected: 'tool/0.1@user/testing' \"\n \"requires 'lib/0.1@user/testing'\"):\n self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[\"lib/0.1@user/testing\"]))\n\n def test_transitive_build_require_recipe_profile(self):\n # app -> lib -(br)-> gtest -(br)-> mingw\n # profile \\---(br)-> mingw\n # app -(br)-> mingw\n self._cache_recipe(\"mingw/0.1@user/testing\", TestConanFile(\"mingw\", \"0.1\"))\n self._cache_recipe(\"gtest/0.1@user/testing\", TestConanFile(\"gtest\", \"0.1\"))\n self._cache_recipe(\"lib/0.1@user/testing\",\n TestConanFile(\"lib\", \"0.1\",\n build_requires=[\"gtest/0.1@user/testing\"]))\n profile_build_requires = {\"*\": [ConanFileReference.loads(\"mingw/0.1@user/testing\")]}\n deps_graph = self.build_graph(TestConanFile(\"app\", \"0.1\",\n requires=[\"lib/0.1@user/testing\"]),\n profile_build_requires=profile_build_requires)\n\n self.assertEqual(6, len(deps_graph.nodes))\n app = deps_graph.root\n lib = app.dependencies[0].dst\n gtest = lib.dependencies[0].dst\n mingw_gtest = gtest.dependencies[0].dst\n mingw_lib = lib.dependencies[1].dst\n mingw_app = app.dependencies[1].dst\n\n self._check_node(app, \"app/0.1@None/None\", deps=[lib], build_deps=[mingw_app], dependents=[],\n closure=[mingw_app, lib], public_deps=[app, lib])\n\n self._check_node(lib, \"lib/0.1@user/testing#123\", deps=[], build_deps=[mingw_lib, gtest],\n dependents=[lib], closure=[mingw_lib, gtest], public_deps=[app, lib])\n self._check_node(gtest, \"gtest/0.1@user/testing#123\", deps=[], build_deps=[mingw_gtest],\n dependents=[lib], closure=[mingw_gtest], public_deps=[gtest, lib])\n # MinGW leaf nodes\n self._check_node(mingw_gtest, \"mingw/0.1@user/testing#123\", deps=[], build_deps=[],\n dependents=[gtest], closure=[], public_deps=[mingw_gtest, gtest])\n self._check_node(mingw_lib, \"mingw/0.1@user/testing#123\", deps=[], build_deps=[],\n dependents=[lib], closure=[], public_deps=[mingw_lib, gtest, lib])\n self._check_node(mingw_app, \"mingw/0.1@user/testing#123\", deps=[], build_deps=[],\n dependents=[app], closure=[], public_deps=[mingw_app, lib, app])\n\n def test_conflict_transitive_build_requires(self):\n zlib_ref = \"zlib/0.1@user/testing\"\n zlib_ref2 = \"zlib/0.2@user/testing\"\n self._cache_recipe(zlib_ref, TestConanFile(\"zlib\", \"0.1\"))\n self._cache_recipe(zlib_ref2, TestConanFile(\"zlib\", \"0.2\"))\n\n self._cache_recipe(\"gtest/0.1@user/testing\", TestConanFile(\"gtest\", \"0.1\",\n requires=[zlib_ref2]))\n self._cache_recipe(\"lib/0.1@user/testing\",\n TestConanFile(\"lib\", \"0.1\", requires=[zlib_ref],\n build_requires=[\"gtest/0.1@user/testing\"]))\n\n with self.assertRaisesRegexp(ConanException, \"Requirement zlib/0.2@user/testing conflicts\"):\n self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[\"lib/0.1@user/testing\"]))\n\n def test_not_conflict_transitive_build_requires(self):\n # Same as above, but gtest->(build_require)->zlib2\n zlib_ref = \"zlib/0.1@user/testing\"\n zlib_ref2 = \"zlib/0.2@user/testing\"\n self._cache_recipe(zlib_ref, TestConanFile(\"zlib\", \"0.1\"))\n self._cache_recipe(zlib_ref2, TestConanFile(\"zlib\", \"0.2\"))\n\n self._cache_recipe(\"gtest/0.1@user/testing\", TestConanFile(\"gtest\", \"0.1\",\n build_requires=[zlib_ref2]))\n self._cache_recipe(\"lib/0.1@user/testing\",\n TestConanFile(\"lib\", \"0.1\", requires=[zlib_ref],\n build_requires=[\"gtest/0.1@user/testing\"]))\n\n graph = self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[\"lib/0.1@user/testing\"]))\n\n self.assertEqual(5, len(graph.nodes))\n app = graph.root\n lib = app.dependencies[0].dst\n zlib = lib.dependencies[0].dst\n gtest = lib.dependencies[1].dst\n zlib2 = gtest.dependencies[0].dst\n self._check_node(app, \"app/0.1@None/None\", deps=[lib], build_deps=[], dependents=[],\n closure=[lib, zlib], public_deps=[app, lib, zlib])\n\n self._check_node(lib, \"lib/0.1@user/testing#123\", deps=[zlib], build_deps=[gtest],\n dependents=[app], closure=[gtest, zlib], public_deps=[app, lib, zlib])\n\n self._check_node(gtest, \"gtest/0.1@user/testing#123\", deps=[], build_deps=[zlib2],\n dependents=[lib], closure=[zlib2], public_deps=[gtest, lib, zlib])\n\n def test_diamond_no_option_conflict_build_requires(self):\n # Same as above, but gtest->(build_require)->zlib2\n zlib_ref = \"zlib/0.1@user/testing\"\n self._cache_recipe(zlib_ref, TestConanFile(\"zlib\", \"0.1\",\n options='{\"shared\": [True, False]}',\n default_options='shared=False'))\n\n self._cache_recipe(\"gtest/0.1@user/testing\",\n TestConanFile(\"gtest\", \"0.1\", requires=[zlib_ref],\n default_options='zlib:shared=True'))\n self._cache_recipe(\"lib/0.1@user/testing\",\n TestConanFile(\"lib\", \"0.1\", requires=[zlib_ref],\n build_requires=[\"gtest/0.1@user/testing\"]))\n\n graph = self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[\"lib/0.1@user/testing\"]))\n\n self.assertEqual(4, len(graph.nodes))\n app = graph.root\n lib = app.dependencies[0].dst\n zlib = lib.dependencies[0].dst\n self.assertFalse(bool(zlib.conanfile.options.shared))\n gtest = lib.dependencies[1].dst\n zlib2 = gtest.dependencies[0].dst\n self.assertIs(zlib, zlib2)\n self._check_node(app, \"app/0.1@None/None\", deps=[lib], build_deps=[], dependents=[],\n closure=[lib, zlib], public_deps=[app, lib, zlib])\n\n self._check_node(lib, \"lib/0.1@user/testing#123\", deps=[zlib], build_deps=[gtest],\n dependents=[app], closure=[gtest, zlib], public_deps=[app, lib, zlib])\n\n self._check_node(gtest, \"gtest/0.1@user/testing#123\", deps=[zlib2], build_deps=[],\n dependents=[lib], closure=[zlib2], public_deps=[gtest, lib, zlib])\n\n def test_diamond_option_conflict_build_requires(self):\n # Same as above, but gtest->(build_require)->zlib2\n zlib_ref = \"zlib/0.1@user/testing\"\n self._cache_recipe(zlib_ref, TestConanFile(\"zlib\", \"0.1\",\n options='{\"shared\": [True, False]}',\n default_options='shared=False'))\n configure = \"\"\"\n def configure(self):\n self.options[\"zlib\"].shared=True\n \"\"\"\n gtest = str(TestConanFile(\"gtest\", \"0.1\", requires=[zlib_ref])) + configure\n self._cache_recipe(\"gtest/0.1@user/testing\", gtest)\n self._cache_recipe(\"lib/0.1@user/testing\",\n TestConanFile(\"lib\", \"0.1\", requires=[zlib_ref],\n build_requires=[\"gtest/0.1@user/testing\"]))\n\n with self.assertRaisesRegexp(ConanException,\n \"tried to change zlib/0.1@user/testing option shared to True\"):\n self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[\"lib/0.1@user/testing\"]))\n\n def test_conflict_private(self):\n liba_ref = \"liba/0.1@user/testing\"\n liba_ref2 = \"liba/0.2@user/testing\"\n libb_ref = \"libb/0.1@user/testing\"\n libc_ref = \"libc/0.1@user/testing\"\n self._cache_recipe(liba_ref, TestConanFile(\"liba\", \"0.1\"))\n self._cache_recipe(liba_ref2, TestConanFile(\"liba\", \"0.2\"))\n self._cache_recipe(libb_ref, TestConanFile(\"libb\", \"0.1\", requires=[liba_ref]))\n self._cache_recipe(libc_ref, TestConanFile(\"libc\", \"0.1\", requires=[liba_ref2]))\n with self.assertRaisesRegexp(ConanException, \"Requirement liba/0.2@user/testing conflicts\"):\n self.build_graph(TestConanFile(\"app\", \"0.1\", private_requires=[libb_ref, libc_ref]))\n\n def test_loop_private(self):\n # app -> lib -(private)-> tool ->|\n # \\<-----(private)------|\n lib_ref = \"lib/0.1@user/testing\"\n self._cache_recipe(\"tool/0.1@user/testing\", TestConanFile(\"tool\", \"0.1\",\n private_requires=[lib_ref]))\n self._cache_recipe(lib_ref,\n TestConanFile(\"lib\", \"0.1\",\n private_requires=[\"tool/0.1@user/testing\"]))\n with self.assertRaisesRegexp(ConanException, \"Loop detected: 'tool/0.1@user/testing' \"\n \"requires 'lib/0.1@user/testing'\"):\n self.build_graph(TestConanFile(\"app\", \"0.1\", requires=[lib_ref]))\n\n def test_build_require_private(self):\n # app -> lib -(br)-> tool -(private)-> zlib\n zlib_ref = \"zlib/0.1@user/testing\"\n self._cache_recipe(zlib_ref, TestConanFile(\"zlib\", \"0.1\"))\n self._cache_recipe(\"tool/0.1@user/testing\", TestConanFile(\"tool\", \"0.1\",\n private_requires=[zlib_ref]))\n self._cache_recipe(\"lib/0.1@user/testing\",\n TestConanFile(\"lib\", \"0.1\",\n build_requires=[\"tool/0.1@user/testing\"]))\n deps_graph = self.build_graph(TestConanFile(\"app\", \"0.1\",\n requires=[\"lib/0.1@user/testing\"]))\n\n self.assertEqual(4, len(deps_graph.nodes))\n app = deps_graph.root\n lib = app.dependencies[0].dst\n tool = lib.dependencies[0].dst\n zlib = tool.dependencies[0].dst\n\n self._check_node(app, \"app/0.1@None/None\", deps=[lib], build_deps=[], dependents=[],\n closure=[lib], public_deps=[app, lib])\n\n self._check_node(lib, \"lib/0.1@user/testing#123\", deps=[], build_deps=[tool],\n dependents=[app], closure=[tool], public_deps=[app, lib])\n\n self._check_node(tool, \"tool/0.1@user/testing#123\", deps=[zlib], build_deps=[],\n dependents=[lib], closure=[zlib], public_deps=[tool, lib])\n\n self._check_node(zlib, \"zlib/0.1@user/testing#123\", deps=[], build_deps=[],\n dependents=[tool], closure=[], public_deps=[zlib])\n","sub_path":"conans/test/functional/graph/graph_manager_test.py","file_name":"graph_manager_test.py","file_ext":"py","file_size_in_byte":24474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"386998281","text":"\"\"\"\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\n http://www.apache.org/licenses/LICENSE-2.0\n\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\nCopyright: (c) 2020, Deutsches Zentrum fuer Luft- und Raumfahrt e.V.\nContact: jasper.bussemaker@dlr.de\n\"\"\"\n\nimport pytest\nimport timeit\nfrom open_turb_arch.architecting.problem import *\nfrom open_turb_arch.architecting.metrics import *\nfrom open_turb_arch.architecting.opt_defs import *\nfrom open_turb_arch.architecting.turbofan import *\nfrom open_turb_arch.evaluation.analysis.balancer import *\nfrom open_turb_arch.evaluation.architecture.flow import *\nfrom open_turb_arch.evaluation.architecture.turbomachinery import *\n\n\n@pytest.fixture\ndef gearbox_problem():\n return AnalysisProblem(DesignCondition(\n mach=1e-6, alt=0,\n thrust=20017, # 4500 lbf\n turbine_in_temp=1314, # 2857 degR\n balancer=DesignBalancer(init_turbine_pr=8.36),\n ))\n\n\ndef _get_problem(gearbox_problem, fan_choice, gearbox_choice):\n return ArchitectingProblem(\n analysis_problem=gearbox_problem, choices=[fan_choice, gearbox_choice],\n objectives=[TSFCMetric()], constraints=[TSFCMetric()], metrics=[TSFCMetric()],\n )\n\n\ndef test_des_vars(gearbox_problem):\n problem = _get_problem(gearbox_problem, FanChoice(), GearboxChoice())\n assert len(problem.opt_des_vars) == 5\n assert len(problem.free_opt_des_vars) == 5\n assert isinstance(problem.opt_des_vars[3], DiscreteDesignVariable)\n assert isinstance(problem.opt_des_vars[4], ContinuousDesignVariable)\n\n\ndef test_modify_architecture(gearbox_problem):\n problem = _get_problem(gearbox_problem, FanChoice(), GearboxChoice())\n\n architecture, dv = problem.generate_architecture([0, 5., 1.5, 0, 3.])\n assert len(architecture.get_elements_by_type(Gearbox)) == 0\n assert len(architecture.get_elements_by_type(Shaft)) == 1\n\n architecture, dv = problem.generate_architecture([0, 5., 1.5, 1, 3.])\n assert len(architecture.get_elements_by_type(Gearbox)) == 0\n assert len(architecture.get_elements_by_type(Shaft)) == 1\n\n architecture, dv = problem.generate_architecture([1, 5., 1.5, 0, 3.])\n assert len(architecture.get_elements_by_type(Gearbox)) == 0\n assert len(architecture.get_elements_by_type(Shaft)) == 1\n\n architecture, dv = problem.generate_architecture([1, 5., 1.5, 1, 3.])\n assert len(architecture.get_elements_by_type(Gearbox)) == 1\n assert len(architecture.get_elements_by_type(Shaft)) == 2\n\n\n# def test_evaluate_architecture(gearbox_problem):\n# problem = _get_problem(gearbox_problem, FanChoice(), GearboxChoice())\n# problem.print_results = True\n#\n# start = timeit.default_timer()\n# dv_imputed, obj, con, met = problem.evaluate([0, 5., 1.5, 0, 3.]) # No fan & no gearbox\n# assert obj == [pytest.approx(26.5737, abs=5e-1)]\n# assert con == [pytest.approx(26.5737, abs=5e-1)]\n# assert met == [pytest.approx(26.5737, abs=5e-1)]\n# time = timeit.default_timer()-start\n#\n# start_cached = timeit.default_timer()\n# dv_imputed2, obj, con, met = problem.evaluate([0, 5., 1.5, 0, 3.]) # With no fan & no gearbox (cached)\n# assert dv_imputed2 == dv_imputed\n# assert obj == [pytest.approx(26.5737, abs=5e-1)]\n# assert con == [pytest.approx(26.5737, abs=5e-1)]\n# assert met == [pytest.approx(26.5737, abs=5e-1)]\n# time_cached = timeit.default_timer()-start_cached\n# assert time_cached < time*.01\n#\n# dv_imputed, obj, con, met = problem.evaluate([0, 5., 1.5, 1, 3.]) # With no fan but gearbox (should not have effect)\n# assert obj == [pytest.approx(26.5737, abs=5e-1)]\n# assert con == [pytest.approx(26.5737, abs=5e-1)]\n# assert met == [pytest.approx(26.5737, abs=5e-1)]\n#\n# dv_imputed, obj, con, met = problem.evaluate([1, 5., 1.5, 0, 3.]) # With fan but no gearbox\n# assert obj == [pytest.approx(11.8247, abs=5e-1)]\n# assert con == [pytest.approx(11.8247, abs=5e-1)]\n# assert met == [pytest.approx(11.8247, abs=5e-1)]\n#\n# dv_imputed, obj, con, met = problem.evaluate([1, 5., 1.5, 1, 3.]) # With fan and gearbox\n# assert obj == [pytest.approx(11.8247, abs=5e-1)]\n# assert con == [pytest.approx(11.8247, abs=5e-1)]\n# assert met == [pytest.approx(11.8247, abs=5e-1)]\n","sub_path":"open_turb_arch/tests/architecting/test_gearbox_choice.py","file_name":"test_gearbox_choice.py","file_ext":"py","file_size_in_byte":4620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13352151","text":"#find years to save to buy house with raise\n#we are given .07 semi annual raise roi .04, dwon payment .25, cost of house is 1M,\n#we have 36 months to save (3 years)\n#use bisectional search to solve for portion of slary to save\n\n\nannual_salary = float(input(\"Salary?\"))\ntotal_cost = float(1000000)\nportion_down_payment = total_cost * .25\nsemi_annual_raise = float(0.07)\nmonths_saved = 36\ncurrent_savings = 0\n\n#\nepsilon = 100 # want to be within 100 dollars\nsave = 1\nmin_savings = 0\nmax_savings = save\nnum_guesses = 1\n\nguess = ( max_savings + min_savings ) / 2\n\n#let check if savings is possible on your salary\nfor i in range(1, months_saved + 1):\n annual_salary_mod = annual_salary\n monthly_saving = (annual_salary_mod / 12) * max_savings\n current_savings = current_savings * (1 + .04 / 12)\n current_savings += monthly_saving\n if i % 6 == 0:\n annual_salary_mod = annual_salary_mod * (1 + semi_annual_raise)\nif current_savings < portion_down_payment:\n print(\"It is not possible to pay the down payment in three years.\")\n quit()\nelse:\n\n #while approaching a smaller epsilon via if, else adjusting min and max targets if the basis of bisection method\n while abs(current_savings - portion_down_payment) >= epsilon:\n #calculate savings after 36 months where guess is portion saved\n #we need to reset annual salary for each iteration of final current_savings\n current_savings = 0\n annual_salary_mod = annual_salary\n for i in range(1, months_saved + 1):\n monthly_saving = (annual_salary_mod / 12) * guess\n current_savings = current_savings * (1 + .04 / 12)\n current_savings += monthly_saving\n if i % 6 == 0:\n annual_salary_mod = annual_salary_mod * (1 + semi_annual_raise)\n\n if current_savings < portion_down_payment:\n min_savings = guess\n else:\n max_savings = guess\n guess = (max_savings + min_savings) / 2\n num_guesses += 1\n\n print(guess)\n print(num_guesses)\n","sub_path":"contents/assignments/ps1c.py","file_name":"ps1c.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"150146172","text":"import logging\nimport formencode\nfrom formencode.validators import PlainText, Int, URL, String\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\nfrom pylons.decorators import validate\n\nfrom springgrid.lib.base import BaseController, render, Session\nfrom springgrid.model.meta import Engine\nfrom springgrid.model import roles\n\nlog = logging.getLogger(__name__)\n\n\nclass EngineForm(formencode.Schema):\n allow_extra_fields = True\n filter_extra_fields = True\n engineName = String(not_empty=True)\n engineUrl = URL(check_exists=True)\n engineArchiveChecksum = PlainText(not_empty=True)\n\n\nclass EngineController(BaseController):\n\n @validate(schema=EngineForm(), form='list', post_only=True, on_get=False)\n def add(self):\n if not roles.isInRole(roles.modadmin):\n c.message = \"You must be logged in as a modadmin. Sorry, temporary\"\n return render('genericmessage.html')\n\n enginename = self.form_result[\"engineName\"]\n enginearchivechecksum = self.form_result[\"engineArchiveChecksum\"]\n engineurl = self.form_result[\"engineUrl\"]\n\n engine = Engine(enginename)\n engine.engine_url = engineurl\n engine.engine_archivechecksum = enginearchivechecksum\n Session.add(engine)\n Session.commit()\n\n c.message = \"Added ok\"\n return render('genericmessage.html')\n\n def view(self, id):\n engine = Session.query(Engine).filter(Engine.engine_id == id).first()\n if engine == None:\n c.message = \"No such engine\"\n return render('genericmessage.html')\n\n showForm = roles.isInRole(roles.modadmin)\n\n c.showForm = showForm\n c.engine = engine\n return render('viewengine.html')\n\n @validate(schema=EngineForm(), form='view', post_only=True, on_get=False)\n def update(self, id):\n if not roles.isInRole(roles.modadmin):\n c.message = \"You must be logged in as a modadmin\"\n return render('genericmessage.html')\n\n engineName = self.form_result['engineName']\n engineArchiveChecksum = self.form_result[\"engineArchiveChecksum\"]\n engineUrl = self.form_result[\"engineUrl\"]\n\n engine = Session.query(Engine).filter(Engine.engine_id == id).first()\n if engine == None:\n c.message = \"No such engine\"\n return render('genericmessage.html')\n\n engine.engine_name = engineName\n engine.engine_url = engineUrl\n engine.engine_archivechecksum = engineArchiveChecksum\n Session.commit()\n\n c.message = \"Updated ok\"\n return render('genericmessage.html')\n\n def remove(self, id):\n if not roles.isInRole(roles.modadmin):\n c.message = \"You must be logged in as a modadmin, temporary!\"\n return render('genericmessage.html')\n\n engine = Session.query(Engine).filter(Engine.engine_id == id).first()\n if engine == None:\n c.message = \"No such engine\"\n return render('genericmessage.html')\n\n Session.delete(engine)\n Session.commit()\n\n c.message = \"Deleted ok\"\n return render('genericmessage.html')\n\n def list(self):\n engines = Session.query(Engine)\n showForm = roles.isInRole(roles.modadmin)\n\n c.showForm = showForm\n c.engines = engines\n return render('viewengines.html')\n","sub_path":"webserver/website/springgrid/controllers/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"310649396","text":"#\n# hello-python version 1.0.\n#\n# Copyright (c) 2020 Oracle, Inc. All rights reserved.\n# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.\n#\n\nimport io\nimport json\nimport pickle\nimport os\n\nfrom fdk import response\n\n\ndef handler(ctx, data: io.BytesIO=None):\n print(\"Entering Python Hello World handler\", flush=True)\n name = [3,2,0,0,1,1,2,2,1,2,5,2,0,0,1,3,2,5,4,4,3,2]\n global age,education,primarySourceOfIncome,jobType,retire,pension,secondarySourceOfIncome,investmentHorizon,understandingOfMarket,married,noOfDependent,annualIncome,spouseWorking,familyAnnualIncome,rent,rentCost,liabilities,investmentObjective,balanceFromInvestment,investmentApproach,nonPerformingPortfolio,insured \n\n try:\n body = json.loads(data.getvalue())\n age = body.get(\"age\")\n education = body.get(\"education\")\n jobType = body.get(\"jobType\")\n pension = body.get(\"pension\")\n primarySourceOfIncome = body.get(\"primarySourceOfIncome\")\n retired = body.get(\"retired\")\n secondarySourceOfIncome = body.get(\"secondarySourceOfIncome\")\n investmentHorizon = body.get(\"investmentHorizon\")\n understandingOfMarket = body.get(\"understandingOfMarket\")\n married = body.get(\"married\")\n spouseWorking = body.get(\"spouseWorking\")\n familyAnnualIncome = body.get(\"familyAnnualIncome\")\n noOfDependent = body.get(\"noOfDependent\")\n rent = body.get(\"rent\")\n rentCost = body.get(\"rentCost\")\n liabilities = body.get(\"liabilities\")\n investmentObjective = body.get(\"investmentObjective\")\n investmentApproach = body.get(\"investmentApproach\")\n nonPerformingPortfolio = body.get(\"nonPerformingPortfolio\")\n insured = body.get(\"insured\")\n annualIncome = body.get(\"annualIncome\")\n balanceFromInvestment = body.get(\"balanceFromInvestment\")\n except (Exception, ValueError) as ex:\n print(str(ex), flush=True)\n \n \n if age == '<25':\n ageML = 4\n elif age == '>=25<40':\n ageML = 3\n elif age == '>=40<58':\n ageML = 2\n elif age == '>=58':\n ageML = 1\n else:\n ageML = 0\n\n if education == 'Graduate':\n educationML = 2\n elif education == 'Under-Graduate':\n educationML = 1\n elif education == 'Post-Graduate':\n educationML = 3\n else:\n educationML = 0\n\n if jobType == 'Permanent':\n jobTypeML = 2\n elif jobType == 'Temporary':\n jobTypeML = 1\n else:\n jobTypeML = 0\n\n if pension == 'Yes':\n pensionML = 2\n elif pension == 'No':\n pensionML = 1\n else:\n pensionML = 0\n\n if primarySourceOfIncome == 'Salaried':\n primarySourceOfIncomeML = 3\n elif primarySourceOfIncome == 'Pension':\n primarySourceOfIncomeML = 1\n elif primarySourceOfIncome == 'Business':\n primarySourceOfIncomeML = 2\n else:\n primarySourceOfIncomeML = 0\n\n if retired == 'Yes':\n retiredML = 1\n elif retired == 'No':\n retiredML = 2\n else:\n retiredML = 0\n\n if secondarySourceOfIncome == 'Rental':\n secondarySourceOfIncomeML = 3\n elif secondarySourceOfIncome == 'Private Channel':\n secondarySourceOfIncomeML = 2\n elif secondarySourceOfIncome == 'Freelancer':\n secondarySourceOfIncomeML = 1\n elif secondarySourceOfIncome == 'Trainer':\n secondarySourceOfIncomeML = 5\n elif secondarySourceOfIncome == 'Stock Broker':\n secondarySourceOfIncomeML = 7\n elif secondarySourceOfIncome == 'Home Based Business':\n secondarySourceOfIncomeML = 6\n else:\n secondarySourceOfIncomeML = 0\n\n if investmentHorizon == 'Less than a year':\n investmentHorizonML = 1\n elif investmentHorizon == 'upto 2 year':\n investmentHorizonML = 2\n elif investmentHorizon == '2-5 year':\n investmentHorizonML = 3\n elif investmentHorizon == '5-10 years':\n investmentHorizonML = 4\n elif investmentHorizon == 'more than 10 years':\n investmentHorizonML = 5\n else:\n investmentHorizonML = 0\n\n if understandingOfMarket == 'No Idea':\n understandingOfMarketML = 1\n elif understandingOfMarket == 'Basic':\n understandingOfMarketML = 2\n elif understandingOfMarket == 'Moderate':\n understandingOfMarketML = 3\n elif understandingOfMarket == 'Experianced':\n understandingOfMarketML = 4\n else:\n understandingOfMarketML = 0\n\n if married == 'Yes':\n marriedML = 1\n elif married == 'No':\n marriedML = 2\n else:\n marriedML = 0\n\n if spouseWorking == 'Yes':\n spouseWorkingML = 2\n elif spouseWorking == 'No':\n spouseWorkingML = 1\n else:\n spouseWorkingML = 0\n\n if familyAnnualIncome == 'Less than $30000':\n familyAnnualIncomeML = 1\n elif familyAnnualIncome == '$30000 to $80000':\n familyAnnualIncomeML = 2\n elif familyAnnualIncome == '$80000 to $150000':\n familyAnnualIncomeML = 3\n elif familyAnnualIncome == '$150000 to $250000':\n familyAnnualIncomeML = 4\n elif familyAnnualIncome == '>$250000':\n familyAnnualIncomeML = 5\n else:\n familyAnnualIncomeML = 0\n\n if noOfDependent == '0':\n noOfDependentML = 5\n elif noOfDependent == '1':\n noOfDependentML = 4\n elif noOfDependent == '2':\n noOfDependentML = 3\n elif noOfDependent == '<3':\n noOfDependentML = 2\n else:\n noOfDependentML = 0\n\n if rent == 'Own':\n rentML = 2\n elif rent == 'Rental':\n rentML = 1\n else:\n rentML = 0\n\n if rentCost == '<$1000':\n rentCostML = 4\n elif rentCost == '>$1000<$2000':\n rentCostML = 3\n elif rentCost == '>$2000<$3500':\n rentCostML = 2\n elif rentCost == '>$3500':\n rentCostML = 1\n else:\n rentCostML = 0\n\n if liabilities == 'Auto':\n liabilitiesML = 4\n elif liabilities == 'Education Loan':\n liabilitiesML = 3\n elif liabilities == 'Home Loan':\n liabilitiesML = 2\n elif liabilities == 'Personal Loan':\n liabilitiesML = 1\n else:\n liabilitiesML = 0\n\n if investmentObjective == 'Children Education':\n investmentObjectiveML = 5\n elif investmentObjective == 'Savings':\n investmentObjectiveML = 3\n elif investmentObjective == 'Retirement Planning':\n investmentObjectiveML = 5\n elif investmentObjective == 'Kid Wedding':\n investmentObjectiveML = 5\n elif investmentObjective == 'Holidays':\n investmentObjectiveML = 2\n else:\n investmentObjectiveML = 0\n \n if investmentApproach == 'Sell all the investments and saved the remaining money':\n investmentApproachML = 1\n elif investmentApproach == 'Sell portion of your portfolio which is still in profit to recover the losses':\n investmentApproachML = 2\n elif investmentApproach == 'Hold you portfolio and wait to recover':\n investmentApproachML = 3\n elif investmentApproach == 'Buy more to lower your average of investments':\n investmentApproachML = 4\n else:\n investmentApproachML = 0\n \n if nonPerformingPortfolio == 'upto 3 months':\n nonPerformingPortfolioML = 1\n elif nonPerformingPortfolio == 'upto 6 month':\n nonPerformingPortfolioML = 2\n elif nonPerformingPortfolio == 'upto 1 year':\n nonPerformingPortfolioML = 3\n elif nonPerformingPortfolio == 'more than a year':\n nonPerformingPortfolioML = 4\n else:\n nonPerformingPortfolioML = 0\n\n if insured == 'Yes':\n insuredML = 2\n elif insured == 'No':\n insuredML = 1\n else:\n insuredML = 0\n\n if annualIncome == 'Less than $30000':\n annualIncomeML = 1\n elif annualIncome == '$30000 to $80000':\n annualIncomeML = 2\n elif annualIncome == '$80000 to $150000':\n annualIncomeML = 3\n elif annualIncome == '$150000 to $250000':\n annualIncomeML = 4\n elif annualIncome == '>$250000':\n annualIncomeML = 5\n else:\n annualIncomeML = 0\n\n if balanceFromInvestment == 'Preferably guaranteed returns before tax savings':\n balanceFromInvestmentML = 1\n elif balanceFromInvestment == 'Stable reliable returns minimal tax savings':\n balanceFromInvestmentML = 2\n elif balanceFromInvestment == 'Some variability in returns some tax savings':\n balanceFromInvestmentML = 3\n elif balanceFromInvestment == 'Moderate variability in returns reasonable tax savings':\n balanceFromInvestmentML = 4\n elif balanceFromInvestment == 'Unstable but potentially higher returns maximize tax savings':\n balanceFromInvestmentML = 5\n else:\n balanceFromInvestmentML = 0\n\n\n testing = [[ageML,educationML,primarySourceOfIncomeML,jobTypeML,retiredML,pensionML,\n secondarySourceOfIncomeML,investmentHorizonML,understandingOfMarketML,\n marriedML,noOfDependentML,annualIncomeML,spouseWorkingML,familyAnnualIncomeML,\n rentML,rentCostML,liabilitiesML,investmentObjectiveML,balanceFromInvestmentML,investmentApproachML,\n nonPerformingPortfolioML,insuredML]]\n\n print(\"Vale of value = \", testing, flush=True)\n print(\"Exiting Python Hello World handler\", flush=True)\n filename = 'finalized_model.sav'\n \n model_dir = os.path.dirname(os.path.realpath(__file__))\n contents = os.listdir(model_dir)\n if filename in contents:\n with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), filename), \"rb\") as file:\n loaded_model = pickle.load(file)\n result = loaded_model.predict(testing)\n else:\n raise Exception('{0} is not found in model directory {1}'.format(filename, model_dir))\n\n return response.Response(\n ctx, response_data=json.dumps(\n {\"message\": \"Your risk appetite is {0} percent\".format(result)}),\n headers={\"Content-Type\": \"application/json\"}\n )\n","sub_path":"python_risk/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":9756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"15744925","text":"#Codechef may long challenge problem 2\n#Isolation centers\nfrom collections import Counter\nfor _ in range(int(input())):\n N,Q = map(int,input().split())\n s = input()\n counter = Counter (s)\n for i in range(Q):\n c = int(input())\n count = 0 \n for v in counter.values():\n if v>c :\n count += v-c\n print(count) \n ","sub_path":"isolation_center.py","file_name":"isolation_center.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266254963","text":"#Experiment\nfrom comet_ml import Experiment\nfrom datetime import datetime\nfrom DeepTreeAttention.trees import AttentionModel\nfrom DeepTreeAttention.utils import metrics, resample, start_cluster\nfrom DeepTreeAttention.models.layers import WeightedSum\nfrom DeepTreeAttention.visualization import visualize\n\nimport tensorflow as tf\nfrom tensorflow.keras import metrics as keras_metrics\nfrom tensorflow.keras.models import load_model\nfrom random import randint\nfrom time import sleep\nfrom distributed import wait\n\nimport glob\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef find_shapefiles(dirname):\n files = glob.glob(os.path.join(dirname,\"*.shp\"))\n return files\n\ndef predict(dirname, savedir, generate=True, cpus=2, parallel=True, height=40, width=40, channels=3):\n \"\"\"Create a wrapper dask cluster and run list of shapefiles in parallel (optional)\n Args:\n dirname: directory of DeepForest predicted shapefiles to run\n savedir: directory to write processed shapefiles\n generate: Do tfrecords need to be generated/overwritten or use existing records?\n cpus: Number of dask cpus to run\n \"\"\"\n shapefiles = find_shapefiles(dirname=dirname)\n \n if parallel:\n client = start_cluster.start(cpus=cpus)\n futures = client.map(_predict_,shapefiles, create_records=generate, savedir=savedir, height=height, width=width, channels=channels)\n wait(futures)\n \n for future in futures:\n print(future.result())\n else:\n for shapefile in shapefiles:\n _predict_(shapefile, model_path, savedir=savedir, create_records=generate)\n \nif __name__ == \"__main__\":\n experiment = Experiment(project_name=\"neontrees\", workspace=\"bw4sz\")\n experiment.add_tag(\"Train\")\n \n #Create output folder\n #Sleep for a moment to allow queries to build up in SLURM queue\n sleep(randint(0,10))\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n save_dir = \"{}/{}\".format(\"/orange/idtrees-collab/DeepTreeAttention/snapshots/\",timestamp)\n os.mkdir(save_dir)\n \n experiment.log_parameter(\"timestamp\",timestamp)\n \n #Create a class and run\n model = AttentionModel(config=\"/home/b.weinstein/DeepTreeAttention/conf/tree_config.yml\")\n model.create()\n \n #Log config\n experiment.log_parameters(model.config[\"train\"])\n experiment.log_parameters(model.config[\"evaluation\"]) \n experiment.log_parameters(model.config[\"predict\"])\n experiment.log_parameters(model.config[\"train\"][\"ensemble\"])\n \n ##Train\n #Train see config.yml for tfrecords path with weighted classes in cross entropy\n model.read_data()\n class_weight = model.calc_class_weight()\n \n #Load from file and compile or train new models\n if model.config[\"train\"][\"checkpoint_dir\"] is not None:\n dirname = model.config[\"train\"][\"checkpoint_dir\"] \n if model.config[\"train\"][\"gpus\"] > 1:\n with model.strategy.scope(): \n print(\"Running in parallel on {} GPUs\".format(model.strategy.num_replicas_in_sync))\n model.RGB_model = load_model(\"{}/RGB_model.h5\".format(dirname), custom_objects={\"WeightedSum\": WeightedSum}, compile=False)\n model.HSI_model = load_model(\"{}/HSI_model.h5\".format(dirname), custom_objects={\"WeightedSum\": WeightedSum}, compile=False) \n model.metadata_model = load_model(\"{}/metadata_model.h5\".format(dirname), compile=False) \n else:\n model.RGB_model = load_model(\"{}/RGB_model.h5\".format(dirname), custom_objects={\"WeightedSum\": WeightedSum})\n model.HSI_model = load_model(\"{}/HSI_model.h5\".format(dirname), custom_objects={\"WeightedSum\": WeightedSum}) \n model.metadata_model = load_model(\"{}/metadata_model.h5\".format(dirname), compile=False) \n \n else:\n if model.config[\"train\"][\"pretrain\"]:\n #metadata network\n with experiment.context_manager(\"metadata\"):\n print(\"Train metadata\")\n model.read_data(mode=\"metadata\")\n model.train(submodel=\"metadata\", experiment=experiment, class_weight=class_weight)\n model.metadata_model.save(\"{}/metadata_model.h5\".format(save_dir))\n \n ##Train subnetworks\n experiment.log_parameter(\"Train subnetworks\", True)\n with experiment.context_manager(\"RGB_spatial_subnetwork\"):\n print(\"Train RGB spatial subnetwork\")\n model.read_data(mode=\"RGB_submodel\")\n model.train(submodel=\"spatial\", sensor=\"RGB\", class_weight=[class_weight, class_weight, class_weight], experiment=experiment)\n \n with experiment.context_manager(\"RGB_spectral_subnetwork\"):\n print(\"Train RGB spectral subnetwork\") \n model.read_data(mode=\"RGB_submodel\") \n model.train(submodel=\"spectral\", sensor=\"RGB\", class_weight=[class_weight, class_weight, class_weight], experiment=experiment)\n \n #Train full RGB model\n with experiment.context_manager(\"RGB_model\"):\n experiment.log_parameter(\"Class Weighted\", True)\n model.read_data(mode=\"RGB_train\")\n model.train(class_weight=class_weight, sensor=\"RGB\", experiment=experiment)\n model.RGB_model.save(\"{}/RGB_model.h5\".format(save_dir))\n \n #Get Alpha score for the weighted spectral/spatial average. Higher alpha favors spatial network.\n if model.config[\"train\"][\"RGB\"][\"weighted_sum\"]:\n estimate_a = model.RGB_model.get_layer(\"weighted_sum\").get_weights()\n experiment.log_metric(name=\"spatial-spectral weight\", value=estimate_a[0][0])\n \n ##Train subnetwork\n experiment.log_parameter(\"Train subnetworks\", True)\n with experiment.context_manager(\"HSI_spatial_subnetwork\"):\n print(\"Train HSI spatial subnetwork\")\n model.read_data(mode=\"HSI_submodel\")\n model.train(submodel=\"spatial\", sensor=\"hyperspectral\",class_weight=[class_weight, class_weight, class_weight], experiment=experiment)\n \n with experiment.context_manager(\"HSI_spectral_subnetwork\"):\n print(\"Train HSI spectral subnetwork\") \n model.read_data(mode=\"HSI_submodel\") \n model.train(submodel=\"spectral\", sensor=\"hyperspectral\", class_weight=[class_weight, class_weight, class_weight], experiment=experiment)\n \n #Train full model\n with experiment.context_manager(\"HSI_model\"):\n experiment.log_parameter(\"Class Weighted\", True)\n model.read_data(mode=\"HSI_train\")\n model.train(class_weight=class_weight, sensor=\"hyperspectral\", experiment=experiment)\n model.HSI_model.save(\"{}/HSI_model.h5\".format(save_dir))\n \n #Get Alpha score for the weighted spectral/spatial average. Higher alpha favors spatial network.\n if model.config[\"train\"][\"HSI\"][\"weighted_sum\"]:\n estimate_a = model.HSI_model.get_layer(\"weighted_sum\").get_weights()\n experiment.log_metric(name=\"spatial-spectral weight\", value=estimate_a[0][0])\n \n ##Ensemble\n with experiment.context_manager(\"ensemble\"): \n print(\"Train Ensemble\")\n model.ensemble(freeze=model.config[\"train\"][\"ensemble\"][\"freeze\"], experiment=experiment, class_weight=class_weight)\n #HSI_weight, RGB_weight, metadata_weight = model.ensemble_model.get_layer(\"ensemble_weight\").get_weights()\n \n #experiment.log_metric(name=\"ensemble HSI weight\", value=HSI_weight[0])\n #experiment.log_metric(name=\"ensemble RGB weight\", value=RGB_weight[0])\n #experiment.log_metric(name=\"ensemble metadata weight\", value=metadata_weight[0])\n \n #Save model and figure\n tf.keras.utils.plot_model(model.ensemble_model, to_file=\"{}/Ensemble.png\".format(save_dir))\n experiment.log_figure(\"{}/Ensemble.png\".format(save_dir))\n model.ensemble_model.save(\"{}/Ensemble.h5\".format(save_dir))\n \n #save predictions\n \n","sub_path":"experiments/Trees/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":8340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"74222246","text":"#!/user/bin/env python3\n# -*- coding: utf-8 -*-\nimport re\n\n\nclass ValidationOperator(object):\n # 获取当前时间\n @staticmethod\n def email_chk(ori_str):\n if type(ori_str) is not str:\n raise ValueError('only str can be handler')\n mat = r'^[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+){0,4}@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+){0,4}$'\n return re.match(mat, ori_str) is not None\n","sub_path":"python/python36/util/ValidationUtil.py","file_name":"ValidationUtil.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"137125377","text":"import requests\nfrom bs4 import BeautifulSoup as BS\nfrom multiprocessing import Pool\n\n\n# Получаем все страницы с товаром\ndef get_all_collections():\n links = []\n link = \"https://www.rusplitka.ru/catalog/\"\n\n for i in range(1, 438): # Первая цифра, начало, вторая количество страниц + 1\n new_link = link + 'page-' + str(i) + '/'\n i += 1\n if i <= 40:\n links.append(new_link)\n return links\n\n\n# Сохраняем все ссылки на страницы в список, и записываем его в текстовый файл\npages_list = get_all_collections()\nwith open(\"pages_list.txt\", 'w') as file:\n for line in pages_list:\n file.write(line + '\\n')\n file.close()\n\n\n# Получаем ссылки на все товары\ndef get_catalog():\n cat_links = []\n\n for page in pages_list:\n response = requests.get(page)\n html_ = response.text\n soup = BS(html_, \"html.parser\")\n catalog = soup.find_all('a', class_='title')\n print(f\"Распарсил {page}, перехожу к следующей странице.\")\n\n for link in catalog:\n a = link.get('href')\n cat_links.append(a)\n return cat_links\n\n\ncatalog_list = get_catalog()\n\n#Сохраняем ссылки на товары в файл\nwith open(\"catalog_list.txt\", 'w') as file:\n for line in catalog_list:\n file.write(f\"https://www.rusplitka.ru{line}\\n\")\n file.close()\n\n","sub_path":"asd.py","file_name":"asd.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"532118052","text":"from collections import namedtuple\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport pdb\nimport pickle\n#from parse_path import constituency_path\nimport math\nfrom util import *\nfrom torch.nn import utils as nn_utils\nimport torch.nn.init as init\ndef init_ortho(module):\n for weight_ in module.parameters():\n if len(weight_.size()) == 2:\n init.orthogonal_(weight_)\n\nclass MLSTM(nn.Module):\n def __init__(self, config):\n super(MLSTM, self).__init__()\n self.config = config\n #The concatenated word embedding and target embedding as input\n self.rnn = nn.LSTM(config.embed_dim , int(config.l_hidden_size / 2), batch_first=True, num_layers = int(config.l_num_layers / 2),\n bidirectional=True, dropout=config.l_dropout)\n init_ortho(self.rnn)\n\n # batch_size * sent_l * dim\n def forward(self, feats, seq_lengths=None):\n '''\n Args:\n feats: batch_size, max_len, emb_dim\n seq_lengths: batch_size\n '''\n #FIXIT: doesn't have batch\n #Sort the lengths\n # seq_lengths, perm_idx = seq_lengths.sort(0, descending=True)\n # feats = feats[perm_idx]\n #feats = feats.unsqueeze(0)\n pack = nn_utils.rnn.pack_padded_sequence(feats, \n seq_lengths, batch_first=True)\n \n \n #assert self.batch_size == batch_size\n lstm_out, _ = self.rnn(pack)\n #lstm_out, (hid_states, cell_states) = self.rnn(feats)\n\n #Unpack the tensor, get the output for varied-size sentences\n unpacked, _ = nn_utils.rnn.pad_packed_sequence(lstm_out, batch_first=True)\n\n #FIXIT: for batch\n #lstm_out = lstm_out.squeeze(0)\n # batch * sent_l * 2 * hidden_states \n return unpacked\n\n# consits of three components\nclass depTSA(nn.Module):\n def __init__(self, config):\n super(depTSA, self).__init__()\n self.config = config\n\n self.lstm = MLSTM(config)\n self.target2vec = nn.Linear(config.embed_dim, config.l_hidden_size)\n self.vec2label = nn.Linear(config.embed_dim, 3)\n self.concatvec_linear = nn.Linear(2*config.l_hidden_size, 1)\n\n self.cri = nn.CrossEntropyLoss()\n self.dropout = nn.Dropout(config.dropout)\n #Modified by Richard Sun\n #If we use Elmo, don't load GloVec\n #self.cat_layer.load_vector()\n\n def compute_score(self, sent, weights, lens):\n '''\n inputs are list of list for the convenince of top CRF\n Args:\n sent: a list of sentences, batch_size*max_len*(2*emb_dim)\n weights: batch_size*max_len\n label: a list labels\n '''\n\n #Get the target embedding\n #batch_size, sent_len, dim = sent.size()\n weights = weights.unsqueeze(1)#batch_size*1*max_len\n\n sents_vec = torch.bmm(weights, sent).squeeze(1)#Batch_size*hidden_dim\n \n #Dropout\n if self.training:\n sents_vec = self.dropout(sents_vec)\n\n output = self.vec2label(sents_vec)#Bach_size*label_size\n\n scores = F.log_softmax(output, dim=1)#Batch_size*label_size\n return scores, weights\n\n \n def forward(self, sent, weights, label, lens):\n #Sent emb_dim + 50\n \n sent = F.dropout(sent, p=0.2, training=self.training)\n scores, _ = self.compute_score(sent, weights, lens)\n loss = nn.NLLLoss()\n #cls_loss = -1 * torch.log(scores[label])\n cls_loss = loss(scores, label)\n\n #print('Transition', pena)\n return cls_loss \n\n def predict(self, sent, weights, sent_len):\n #sent = self.cat_layer(sent, mask)\n scores, attentions = self.compute_score(sent, weights, sent_len)\n _, pred_label = scores.max(1)#Find the max label in the 2nd dimension\n \n #Modified by Richard Sun\n return pred_label, attentions\n\n","sub_path":"backup/backup_models/model_parse_elmo.py","file_name":"model_parse_elmo.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"619054181","text":"import json\nimport boto3\nimport unidecode\n\ndef normalizeWords(word):\n return unidecode.unidecode(word.lower().replace(' ', ''))\n\ndef getMatchingFood(fullname, foods):\n good = []\n fullname = normalizeWords(fullname)\n\n for cat in foods:\n good_cat = []\n for cat_name, food_list in cat.items():\n for food in food_list:\n f = normalizeWords(food)\n rotten = False\n stripped_name = fullname\n for letter in f:\n if letter in stripped_name:\n stripped_name = stripped_name.replace(letter, '', 1)\n else:\n rotten = True\n break\n \n if not rotten:\n good_cat.append(food)\n if len(good_cat) > 0:\n good.append({cat_name: good_cat})\n\n return good\n \ndef lambda_handler(event, context):\n fullname = event['fullname']\n language = event['language']\n \n tablename = 'food_' + language\n \n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table(tablename)\n \n all_cat = table.scan()\n print(json.dumps(all_cat))\n \n everyfood = []\n for cat_list in all_cat['Items']:\n cat_food = cat_list['words']\n everyfood.append({cat_list['category']: cat_food})\n\n matching = getMatchingFood(fullname, everyfood)\n \n return {\n 'statusCode': 200,\n 'body': matching\n }\n","sub_path":"lambda/scrabble/food_retrieval.py","file_name":"food_retrieval.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"537029379","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data;\n\n# import tflearn.datasets.mnist as lmnist\n# lmnist.load_data(one_hot=True)\n\nmnist = input_data.read_data_sets('mnist/', one_hot= True);\nprint(mnist.train.num_examples);\nprint(mnist.test.num_examples);\n\ntrainimg = mnist.train.images;\ntrainlabel = mnist.train.images;\ntestimg = mnist.test.images;\ntestlabel = mnist.test.labels;\n\nprint( type(trainimg));\nprint(trainimg.shape,);\nprint(trainlabel.shape,);\nprint(testimg.shape,);\nprint(testlabel.shape,);\n\nnsample = 5;\nrandidx = np.random.randint(trainimg.shape[0], size = nsample )\n\n\nfor i in randidx:\n print(i)\n curr_img = np.reshape(trainimg[i, :], (28, 28))\n curr_label = np.argmax(trainlabel[i, :])\n plt.matshow(curr_img, cmap=plt.get_cmap('gray_r'))\n plt.title(\"\" + str(i) + \"th Training Data\" + \"label is\" + str(curr_label))\n print(\"\" + str(i) + \"th Training Data\" + \"label is\" + str(curr_label))\n plt.show()\n\n\n\n","sub_path":"cifardata/tf3.py","file_name":"tf3.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"185978337","text":"# Definition for a binary tree node.\n# 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 countNodes(self, root: TreeNode) -> int:\n arr = self.prePrint(root)\n return len(arr)\n\n # 函数功能:二叉树的前序遍历\n def prePrint(self, root):\n if root == None:\n return []\n arr = []\n arr.append(root.val)\n\n leftArr = self.prePrint(root.left)\n if len(leftArr) > 0:\n for node in leftArr:\n arr.append(node)\n rightArr = self.prePrint(root.right)\n if len(rightArr) > 0:\n for node in rightArr:\n arr.append(node)\n return arr","sub_path":"chap9-树/222. 完全二叉树的节点个数/countNodes.py","file_name":"countNodes.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"56084626","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Notes\n\nengine = create_engine('sqlite:///notes.db')\n\nBase.metadata.bind = create_engine\nDBSession = sessionmaker(bind = engine)\nsession = DBSession()\n\nnew_query = Notes(text = \"Why are people always staring at me on the bus, I mean it's ridiculous. I'm just eating my pringles!\")\nsession.add(new_query)\nsession.commit()\nsession.query(Notes).all()\n","sub_path":"create_note.py","file_name":"create_note.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"123922500","text":"# http://stuvel.eu/media/flickrapi-docs/documentation/2-calling.html\n# flickr\nflickr_key = u'AAAAAA'\nflickr_secret = u'BBBBBB'\n\nflickr_id = {}\nflickr_id['cmrhipstamatic'] = u'119090494@N05'\nflickr_id['cmreverything'] = u'123590461@N07'\nflickr_id['cmrcuba'] = u'67073011@N07'\n\n# twitter\nconsumer_key = 'CCCCCCC'\nconsumer_secret = 'DDDDDDDD'\n","sub_path":"attic/bot/apikeys.example.py","file_name":"apikeys.example.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"635815572","text":"#!/usr/bin/python\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\"\"\"quite a complicated demo showing many features of pi3d as well as\ncommunication between players using httpRequest (see rpi_json.sql and\nrpi_json.php) json serialisation and threading.\n\"\"\"\n\n\"\"\"\nSpace Pi-Rates mainscreen\noriginally Dogfight.py from pi3d_demos - https://github.com/pi3d/pi3d_demos\n\n\"\"\"\n\n\nimport sys\nimport time, math, glob, random, threading, json\n\nimport uuid\nMYID=uuid.uuid4()\nrefid=MYID.hex ##Unique ship ID (removes dashes) (send to comms for debugging/noise info?)\n\nimport pi3d\n\nif sys.version_info[0] == 3:\n from urllib import request as urllib_request\n from urllib import parse as urllib_parse\nelse:\n import urllib\n urllib_request = urllib\n urllib_parse = urllib\n\ninstdisplay=False #display instruments/icon on screen\n\naudio=True #turn on sound\n\nscreenoverride=True\n\nif screenoverride==True:\n #screenwidth=640\n #screenheight=480\n screenwidth=800\n screenheight=600\nelse:\n screenwidth=0\n screenheight=0\n \n\n\nif audio==True:\n import pygame\n pygame.init()\n bgnoise = pygame.mixer.Sound('assets/sounds/brownnoise.ogg')\n beamsound = pygame.mixer.Sound('assets/sounds/slimeball.wav')\n clock = pygame.time.Clock()\n bgnoise.play()\n #beamsound.play()\n\n\n#display, camera, shader\n#DISPLAY = pi3d.Display.create(x=100, y=100, frames_per_second=30) ##Use for debugging (not fullscreen)\n#DISPLAY = pi3d.Display.create(x=0, y=0, frames_per_second=30) #default screen for Pi\n#DISPLAY = pi3d.Display.create(0, 0, 640,480,32, frames_per_second=30,window_title='Space Pi-rates',mouse=False) ## For testing on desktop (set to 640x480)\nDISPLAY = pi3d.Display.create(0, 0, screenwidth,screenheight,32, frames_per_second=30,window_title='Space Pi-rates',mouse=False) ## For testing on desktop (set to 640x480)\n\n#a default camera is created automatically but we might need a 2nd 2D camera\n#for displaying the instruments etc. Also, because the landscape is large\n#we need to set the far plane to 10,000\nCAMERA = pi3d.Camera(lens=(1.0, 10000.0, 55.0, 1.33)) #4:3 res\n#CAMERA = pi3d.Camera(lens=(1.0, 10000.0, 55.0, 1.77)) #16:9 res\n#CAMERA = pi3d.Camera(lens=(1.0, 10000.0, 55.0, 2.0))\nCAMERA2D = pi3d.Camera(is_3d=False)\n\nprint(\"\"\"===================================\n== W increase power, S reduce power\n== V view mode, C control mode\n== B brakes\n== X jumps to location of 1st enemy in list\n== P Fires beams\n== Q to turn left, E to turn right\n== I to climb, K to desend\n== 1 Toggle Instruments\n================================\"\"\")\n\nSHADER = pi3d.Shader(\"uv_bump\") #for objects to look 3D\nFLATSH = pi3d.Shader(\"uv_flat\") #for 'unlit' objects like the background\n\nGRAVITY = 0.00001 # 9.8 #m/s**2\nLD = 10 #10 #lift/drag ratio\nDAMPING = 0.95 #reduce roll and pitch rate each update_variables\nBOOSTER = 1.5 #extra manoevreability boost to defy 1st Low of Thermodynamics.\n\n#--Weapons\n\n#load bullet images\nBULLET_TEX = [] #list to hold Texture refs\niFiles = glob.glob(sys.path[0] + \"/assets/textures/starship/bullet??.png\") \niFiles.sort() # order is vital to animation!\nfor f in iFiles:\n BULLET_TEX.append(pi3d.Texture(f))\n \n#load torp1 images - Not yet used\nTORP1_TEX = [] #list to hold Texture refs\niFiles = glob.glob(sys.path[0] + \"/assets/textures/starship/torp1/torp??.png\") \niFiles.sort() # order is vital to animation!\nfor f in iFiles:\n TORP1_TEX.append(pi3d.Texture(f))\n \n#load torp2 images - Not yet used\nTORP2_TEX = [] #list to hold Texture refs\niFiles = glob.glob(sys.path[0] + \"/assets/textures/starship/torp2/torp??.png\") \niFiles.sort() # order is vital to animation!\nfor f in iFiles:\n TORP2_TEX.append(pi3d.Texture(f))\n\n#-- Move to config file?\nDAMAGE_FACTOR = 50 #dived by distance of shoot() \nTORP1_DAMAGE_FACTOR = 100 #dived by distance of shoot()\nTORP2_DAMAGE_FACTOR = 130 #dived by distance of shoot()\n\nNR_TM = 1.0 #check much less frequently until something comes back\nFA_TM = 5.0\nNR_DIST = 250 ## Near Distance?\nFA_DIST = 1900 ## Firing distance? - Far Distance?\nP_FACTOR = 0.001\nI_FACTOR = 0.00001\n\n#define Aeroplane class\nclass Aeroplane(object):\n def __init__(self, model, recalc_time, refid):\n self.refid = refid\n self.recalc_time = recalc_time #in theory use different values for enemy\n self.x, self.y, self. z = 0.0, 0.0, 0.0\n self.x_perr, self.y_perr, self.z_perr = 0.0, 0.0, 0.0\n self.x_ierr, self.y_ierr, self.z_ierr = 0.0, 0.0, 0.0\n self.d_err = 0.0\n self.v_speed, self.h_speed = 0.0, 0.0\n self.rollrate, self.pitchrate, self.yaw = 0.0, 0.0, 0.0\n self.direction, self.roll, self.pitch = 0.0, 0.0, 0.0\n self.max_roll, self.max_pitch = 65, 30 #limit rotations\n self.ailerons, self.elevator = 0.0, 0.0\n self.max_ailerons, self.max_elevator = 10.0, 10.0 #limit conrol surface movement\n self.VNE = 120 #max speed (Velocity Not to be Exceeded)\n self.mass = 300\n self.a_factor, self.e_factor = 10, 10\n self.roll_inrta, self.pitch_inrta = 100, 100\n self.max_power = 2000 #force units of thrust really\n self.lift_factor = 20.0 #randomly adjusted to give required performance!\n self.power_setting = 0.0\n self.throttle_step = 20\n self.last_time = time.time()\n self.last_pos_time = self.last_time\n self.del_time = None #difference in pi time for other aero c.f. main one\n self.rtime = 60\n self.nearest = None\n self.other_damage = 0.0 #done to nearest others since last json_load\n self.damage = 0.0 #done to this aeroplane by others\n #create the actual model\n self.model = pi3d.Model(file_string=model, camera=CAMERA)\n self.model.set_shader(SHADER)\n #create the bullets\n plane = pi3d.Plane(h=25, w=1)\n self.bullets = pi3d.MergeShape(camera=CAMERA)\n #the merge method does rotations 1st Z, 2nd X, 3rd Y for some reason\n #for multi axis rotations you need to figure it out by rotating a\n #sheet of paper in the air in front of you (angles counter clockwise)!\n \n\n \"\"\" ##Old beams/bullets\n self.bullets.merge([[plane, -2.0, 0.5, 8.0, 90,0,0, 1,1,1],\n [plane, -2.0, 0.5, 8.0, 0,90,90, 1,1,1],\n [plane, 2.0, 0.5, 8.0, 90,0,0, 1,1,1],\n [plane, 2.0, 0.5, 8.0, 0,90,90, 1,1,1]])\n \"\"\"\n self.bullets.merge([[plane, 0.0, 0.5, 8.0, 90,0,0, 1,1,1]]) ## fixed single beam - probably needs to be configured for each ship\n self.num_b = len(BULLET_TEX)\n self.seq_b = self.num_b\n self.bullets.set_draw_details(FLATSH, [BULLET_TEX[0]])\n\n def set_ailerons(self, dx):\n self.ailerons = dx\n if abs(self.ailerons) > self.max_ailerons:\n self.ailerons = math.copysign(self.max_ailerons, self.ailerons)\n\n def set_elevator(self, dy):\n self.elevator = dy\n if abs(self.elevator) > self.max_elevator:\n self.elevator = math.copysign(self.max_elevator, self.elevator)\n\n def set_power(self, incr):\n self.power_setting += incr * self.throttle_step\n if self.power_setting < 0:\n self.power_setting = 0\n elif self.power_setting > self.max_power:\n self.power_setting = self.max_power\n print(\"power at \" + str(self.power_setting))\n\n def shoot(self, target):\n #only shoot if animation seq. ended\n beamsound.play()\n if self.seq_b < self.num_b:\n return 0.0\n #animate bullets\n self.seq_b = 0\n #check for hit\n #components of direction vector\n diag_xz = math.cos(math.radians(self.pitch))\n drn_x = diag_xz * math.sin(math.radians(self.direction))\n drn_y = math.sin(math.radians(self.pitch))\n drn_z = diag_xz * math.cos(math.radians(self.direction))\n #this will already be a unit vector\n #vector from target to aeroplane\n a_x = target[0] - self.x\n a_y = target[1] - self.y\n a_z = target[2] - self.z\n #dot product\n dot_p = drn_x * a_x + drn_y * a_y + drn_z * a_z\n dx = a_x - dot_p * drn_x\n dy = a_y - dot_p * drn_y\n dz = a_z - dot_p * drn_z\n distance = math.sqrt(dx**2 + dy**2 + dz**2)\n print(\"distance={0:.2f}\".format(distance))\n print(\"Damage: %s\" % (DAMAGE_FACTOR))\n return DAMAGE_FACTOR / distance if distance > 0.0 else 2.0 * DAMAGE_FACTOR\n\n def home(self, target):\n #turn towards target location, mainly for AI control of enemy aircraft\n dir_t = math.degrees(math.atan2((target[0] - self.x), (target[2] - self.z)))\n #make sure the direction is alway a value between +/- 180 degrees\n #roll so bank is half direction, \n self.roll = -((dir_t - self.direction + 180) % 360 - 180) / 2\n #find angle between self and target\n pch_t = math.degrees(math.atan2((target[1] - self.y),\n math.sqrt((target[2] - self.z)**2 + (target[0] - self.x)**2)))\n self.pitch = pch_t\n return True\n\n def update_variables(self):\n #time\n tm = time.time()\n dt = tm - self.last_time\n if dt < self.recalc_time: # don't need to do all this physics every loop\n return\n self.last_time = tm\n #force from ailerons and elevators to get rotational accelerations\n spsq = self.v_speed**2 + self.h_speed**2 #speed squared\n a_force = self.a_factor * self.ailerons * spsq #ailerons force (moment really)\n roll_acc = a_force / self.roll_inrta #good old Newton\n e_force = self.e_factor * self.elevator * spsq #elevator\n pitch_acc = e_force / self.pitch_inrta\n #velocities and positions\n if abs(self.roll) > self.max_roll: #make it easier to do flight control\n self.roll = math.copysign(self.max_roll, self.roll)\n self.rollrate = 0.0\n if abs(self.pitch) > self.max_pitch:\n self.pitch = math.copysign(self.max_pitch, self.pitch)\n self.pitchrate = 0.0\n self.roll += self.rollrate * dt #update roll position\n self.pitch += self.pitchrate * dt #update roll rate\n self.rollrate += roll_acc * dt\n self.rollrate *= DAMPING # to stop going out of contol while looking around!\n self.pitchrate += pitch_acc * dt\n self.pitchrate *= DAMPING\n #angle of attack\n aofa = math.atan2(self.v_speed, self.h_speed)\n aofa = math.radians(self.pitch) - aofa # approximation to sin difference\n lift = self.lift_factor * spsq * aofa\n drag = lift / LD \n #if spsq < 100: #stall! ####DONT STALL!!\n # lift *= 0.9\n # drag *= 1.3\n\n cos_pitch = math.cos(math.radians(self.pitch))\n sin_pitch = math.sin(math.radians(self.pitch))\n cos_roll = math.cos(math.radians(self.roll))\n sin_roll = math.sin(math.radians(self.roll)) \n ### start looking here for turning....\n h_force = (self.power_setting - drag) * cos_pitch - lift * sin_pitch\n v_force = lift * cos_pitch * cos_roll - self.mass #* GRAVITY # No/very low gravity\n h_acc = h_force / self.mass\n v_acc = v_force / self.mass\n self.h_speed += h_acc * dt\n if self.h_speed > self.VNE:\n self.h_speed = self.VNE\n elif self.h_speed < 0: \n self.h_speed = 0\n self.v_speed += v_acc * dt\n if abs(self.v_speed) > self.VNE:\n self.v_speed = math.copysign(self.VNE, self.v_speed)\n turn_force = -lift * sin_roll * 1.5\n radius = self.mass * spsq / turn_force if turn_force != 0.0 else 0.0\n self.yaw = math.sqrt(spsq) / radius if radius != 0.0 else 0.0\n\n def update_position(self, height):\n #time\n tm = time.time()\n dt = tm - self.last_pos_time\n self.last_pos_time = tm\n self.x += (self.h_speed * math.sin(math.radians(self.direction)) * dt -\n self.x_perr * P_FACTOR - self.x_ierr * I_FACTOR)\n self.y += self.v_speed * dt - self.y_perr * P_FACTOR - self.y_ierr * I_FACTOR\n if self.y < (height + 3):\n self.y = height + 3\n self.v_speed = 0\n self.pitch = 2.5\n #self.roll = 0\n self.z += (self.h_speed * math.cos(math.radians(self.direction)) * dt -\n self.z_perr * P_FACTOR - self.z_ierr * I_FACTOR)\n\n self.direction += math.degrees(self.yaw) * dt - self.d_err * P_FACTOR\n\n ## debug/details\n print(\"X: %s |Y: %s |dir: %s|v speed: %s|h speed: %s\" % (str(self.x), str(self.y), str(self.direction), str(self.v_speed), str(self.h_speed) ))\n ## report to server str(self.direction) to send to helm\n\n #set values of model\n sin_d = math.sin(math.radians(self.direction))\n cos_d = math.cos(math.radians(self.direction))\n sin_r = math.sin(math.radians(self.roll))\n cos_r = math.cos(math.radians(self.roll))\n sin_p = math.sin(math.radians(self.pitch))\n cos_p = math.cos(math.radians(self.pitch))\n absroll = math.degrees(math.asin(sin_r * cos_d + cos_r * sin_p * sin_d))\n abspitch = math.degrees(math.asin(sin_r * sin_d - cos_r * sin_p * cos_d))\n self.model.position(self.x, self.y, self.z)\n self.model.rotateToX(abspitch)\n self.model.rotateToY(self.direction)\n self.model.rotateToZ(absroll)\n #set values for bullets\n if self.seq_b < self.num_b:\n self.bullets.position(self.x, self.y, self.z)\n self.bullets.rotateToX(abspitch)\n self.bullets.rotateToY(self.direction)\n self.bullets.rotateToZ(absroll)\n #set values for camera\n \n return (self.x - 10.0 * sin_d, self.y + 4, self.z - 10.0 * cos_d, self.direction)\n\n def draw(self):\n self.model.draw() ###make this toggled for inside/outside view?\n #draw the bullet sequence if not finished\n if self.seq_b < self.num_b:\n self.bullets.buf[0].textures[0] = BULLET_TEX[self.seq_b]\n self.bullets.draw()\n self.seq_b += 1\n\n#define Instruments class\nclass Instruments(object):\n def __init__(self):\n wd = DISPLAY.width\n #print(str(wd))\n ht = DISPLAY.height\n #print(str(ht))\n \n asi_tex = pi3d.Texture(\"assets/textures/airspeed_indicator.png\") ### Update these with more sci-fi looking images\n alt_tex = pi3d.Texture(\"assets/textures/altimeter.png\")\n #rad_tex = pi3d.Texture(\"assets/textures/radar.png\") ## Use for Sensors\n rad_tex = pi3d.Texture(\"assets/textures/sensors.png\") ## New Sensors\n dot_tex = pi3d.Texture(\"assets/textures/radar_dot.png\") ##Use for sensors\n ndl_tex = pi3d.Texture(\"assets/textures/instrument_needle.png\")\n sprlogo_tex = pi3d.Texture(\"assets/textures/spr_logo.png\") ##Logo\n\n self.asi = pi3d.ImageSprite(asi_tex, FLATSH, camera=CAMERA2D,\n w=128, h=128, x=-128, y=-ht/2+64, z=2)\n self.alt = pi3d.ImageSprite(alt_tex, FLATSH, camera=CAMERA2D,\n w=128, h=128, x=0, y=-ht/2+64, z=2)\n\n #self.rad = pi3d.ImageSprite(rad_tex, FLATSH, camera=CAMERA2D,\n #w=128, h=128, x=128, y=-ht/2+64, z=2)\n self.rad = pi3d.ImageSprite(rad_tex, FLATSH, camera=CAMERA2D,\n w=screenwidth, h=screenheight, x=0, y=-0, z=2) #New sensors screen\n\n self.dot = pi3d.ImageSprite(dot_tex, FLATSH, camera=CAMERA2D,\n w=16, h=16, z=1)\n\n self.ndl1 = pi3d.ImageSprite(ndl_tex, FLATSH, camera=CAMERA2D,\n w=128, h=128, x=-128, y=-ht/2+64, z=1)\n self.ndl2 = pi3d.ImageSprite(ndl_tex, FLATSH, camera=CAMERA2D,\n w=128, h=128, x=0, y=-ht/2+64, z=1)\n self.ndl3 = pi3d.ImageSprite(ndl_tex, FLATSH, camera=CAMERA2D,\n w=128, h=128, x=128, y=-ht/2+64, z=1)\n \n \n self.spr = pi3d.ImageSprite(sprlogo_tex, FLATSH, camera=CAMERA2D,\n w=49, h=64, x=-wd/2+25, y=-ht/2+32, z=2) ##Logo\n print(wd)\n self.dot_list = []\n self.update_time = 0.0\n def draw(self):\n \n #self.asi.draw()\n #self.alt.draw()\n self.rad.draw()\n self.spr.draw() ## Logo\n \"\"\"\n for i in self.dot_list:\n self.dot.position(i[1] + 128, i[2] + self.rad.y(), 1)\n self.dot.draw()\n self.ndl1.draw()\n self.ndl2.draw()\n self.ndl3.draw()\n \"\"\"\n\n def update(self, ae, others):\n \n self.ndl1.rotateToZ(-360*ae.h_speed/140)\n self.ndl2.rotateToZ(-360*ae.y/3000)\n self.ndl3.rotateToZ(-ae.direction)\n \n self.dot_list = []\n for i in others:\n if i == \"start\":\n continue\n o = others[i]\n dx = (o.x - ae.x) / 50\n dy = (o.z - ae.z) / 50\n d = math.hypot(dx, dy)\n if d > 40:\n dx *= 40 / d\n dy *= 40 / d\n self.dot_list.append([o.refid, dx, dy])\n self.update_time = ae.last_pos_time\n\n''' ## Commenting out\ndef json_load(ae, others): ### Replace this with UDP networking\n \"\"\"httprequest other players. Sends own data and gets back array of all\n other players within sight. This function runs in a background thread\n \"\"\"\n #TODO pass nearest, nearest.hp and own hp merge in some way\n tm_now = time.time()\n jstring = json.dumps([ae.refid, ae.last_time, ae.x, ae.y, ae.z,\n ae.h_speed, ae.v_speed, ae.pitch, ae.direction, ae.roll,\n ae.pitchrate, ae.yaw, ae.rollrate, ae.power_setting, ae.damage], separators=(',',':'))\n if ae.nearest:\n n_id = ae.nearest.refid\n n_damage = ae.nearest.other_damage\n ae.nearest.other_damage = 0.0\n else:\n n_id = \"\"\n n_damage = 0.0\n params = urllib_parse.urlencode({\"id\":ae.refid, \"tm\":tm_now, \"x\":ae.x, \"z\":ae.z,\n \"json\":jstring, \"nearest\":n_id, \"damage\":n_damage})\n others[\"start\"] = tm_now #used for polling freqency\n #urlstring = \"http://www.eldwick.org.uk/sharecalc/rpi_json.php?{0}\".format(params)\n urlstring = \"http://localhost/rpi_json.php?{0}\".format(params)\n try:\n r = urllib_request.urlopen(urlstring)\n if r.getcode() == 200: #good response\n jstring = r.read().decode(\"utf-8\")\n #print \"jstring: %s\" % (jstring)\n if len(jstring) > 50: #error messages are shorter than this\n olist = json.loads(jstring)\n #smooth time offset value\n ae.del_time = ae.del_time * 0.9 + olist[0] * 0.1 if ae.del_time else olist[0]\n #own damage is cumulative and not reset on server until dead!\n ae.damage = olist[1]\n #if ae.damage > 2.0 * DAMAGE_FACTOR: #explode return to GO etc\n #print(ae.damage)\n olist = olist[2:]\n \"\"\"\n synchronisation system: sends time.time() which is used to calculate\n an offset on the server and which is inserted as the second term \n in the json string. When the list of other players comes back from\n the server it is preceded by the same offset time inserted in this json.\n This is used to adjust the last_time for all\n the other avatars.\n \"\"\"\n nearest = None\n ae.rtime = 60\n for o in olist: ## AI should go somewhere in here on the server....\n if not(o[0] in others):\n others[o[0]] = Aeroplane(\"assets/models/cigar1.obj\", 0.9, o[0])\n oa = others[o[0]] #oa is other aeroplane, ae is this one!\n oa.refif = o[0]\n #exponential smooth time offset values\n oa.del_time = oa.del_time * 0.9 + o[1] * 0.1 if oa.del_time else o[1]\n oa.last_time = o[2] + oa.del_time - ae.del_time # o[1] inserted by server code\n dt = tm_now - oa.last_time\n if oa.x == 0.0:\n oa.x, oa.y, oa.z = o[3], o[4], o[5]\n nx = o[3] + o[6] * math.sin(math.radians(o[9])) * dt\n ny = o[4] + o[7] * dt\n nz = o[5] + o[6] * math.cos(math.radians(o[9])) * dt\n distance = math.hypot(nx - ae.x, nz - ae.z)\n if not nearest or distance < nearest:\n nearest = distance\n ae.nearest = oa\n oa.x_perr, oa.y_perr, oa.z_perr = oa.x - nx, oa.y - ny, oa.z - nz\n oa.x_ierr += oa.x_perr\n oa.y_ierr += oa.y_perr\n oa.z_ierr += oa.z_perr\n oa.d_err = ((oa.direction - (o[9] + o[12] * dt) + 180) % 360 - 180) / 2\n oa.h_speed = o[6]\n oa.v_speed = o[7]\n oa.pitch = o[8]\n oa.roll = o[10]\n oa.pitchrate = o[11]\n oa.yaw = o[12]\n oa.rollrate = o[13]\n oa.power_setting = o[14]\n oa.damage = o[15]\n\n if nearest:\n ae.rtime = NR_TM + (max(min(nearest, FA_DIST), NR_DIST) - NR_DIST) / \\\n (FA_DIST - NR_DIST) * (FA_TM - NR_TM)\n #TODO tidy up inactive others; flag not to draw, delete if inactive for long enough\n return True\n else:\n print(jstring)\n return False\n else:\n print(r.getcode())\n return False\n except Exception as e:\n print(\"exception:\", e)\n'''\n\n#New networking\ndef json_load(ae, others): ### Replace this with UDP networking\n \"\"\"Sends own data and gets back array of all\n other players within sight. This function runs in a background thread\n \"\"\"\n #TODO pass nearest, nearest.hp and own hp merge in some way\n tm_now = time.time()\n jstring = json.dumps([ae.refid, ae.last_time, ae.x, ae.y, ae.z,\n ae.h_speed, ae.v_speed, ae.pitch, ae.direction, ae.roll,\n ae.pitchrate, ae.yaw, ae.rollrate, ae.power_setting, ae.damage], separators=(',',':'))\n print(jstring)\n if ae.nearest:\n n_id = ae.nearest.refid\n n_damage = ae.nearest.other_damage\n ae.nearest.other_damage = 0.0\n else:\n n_id = \"\"\n n_damage = 0.0\n params = urllib_parse.urlencode({\"id\":ae.refid, \"tm\":tm_now, \"x\":ae.x, \"z\":ae.z,\n \"json\":jstring, \"nearest\":n_id, \"damage\":n_damage}) ##!\n others[\"start\"] = tm_now #used for polling freqency\n #urlstring = \"http://www.eldwick.org.uk/sharecalc/rpi_json.php?{0}\".format(params)\n urlstring = \"http://localhost/rpi_json.php?{0}\".format(params) ##!\n \n try:\n #Start UDP networking here\n r = urllib_request.urlopen(urlstring) ##!\n if r.getcode() == 200: #good response ##!\n jstring = r.read().decode(\"utf-8\") ##!\n #print \"jstring: %s\" % (jstring)\n if len(jstring) > 50: #error messages are shorter than this\n olist = json.loads(jstring)\n #smooth time offset value\n ae.del_time = ae.del_time * 0.9 + olist[0] * 0.1 if ae.del_time else olist[0]\n #own damage is cumulative and not reset on server until dead!\n ae.damage = olist[1]\n #if ae.damage > 2.0 * DAMAGE_FACTOR: #explode return to GO etc\n #print(ae.damage)\n olist = olist[2:]\n \"\"\"\n synchronisation system: sends time.time() which is used to calculate\n an offset on the server and which is inserted as the second term \n in the json string. When the list of other players comes back from\n the server it is preceded by the same offset time inserted in this json.\n This is used to adjust the last_time for all\n the other avatars.\n \"\"\"\n nearest = None\n ae.rtime = 60\n for o in olist: ## AI should go somewhere in here on the server....\n if not(o[0] in others):\n others[o[0]] = Aeroplane(\"assets/models/cigar1.obj\", 0.9, o[0])\n oa = others[o[0]] #oa is other aeroplane, ae is this one!\n oa.refif = o[0]\n #exponential smooth time offset values\n oa.del_time = oa.del_time * 0.9 + o[1] * 0.1 if oa.del_time else o[1]\n oa.last_time = o[2] + oa.del_time - ae.del_time # o[1] inserted by server code\n dt = tm_now - oa.last_time\n if oa.x == 0.0:\n oa.x, oa.y, oa.z = o[3], o[4], o[5]\n nx = o[3] + o[6] * math.sin(math.radians(o[9])) * dt\n ny = o[4] + o[7] * dt\n nz = o[5] + o[6] * math.cos(math.radians(o[9])) * dt\n distance = math.hypot(nx - ae.x, nz - ae.z)\n if not nearest or distance < nearest:\n nearest = distance\n ae.nearest = oa\n oa.x_perr, oa.y_perr, oa.z_perr = oa.x - nx, oa.y - ny, oa.z - nz\n oa.x_ierr += oa.x_perr\n oa.y_ierr += oa.y_perr\n oa.z_ierr += oa.z_perr\n oa.d_err = ((oa.direction - (o[9] + o[12] * dt) + 180) % 360 - 180) / 2\n oa.h_speed = o[6]\n oa.v_speed = o[7]\n oa.pitch = o[8]\n oa.roll = o[10]\n oa.pitchrate = o[11]\n oa.yaw = o[12]\n oa.rollrate = o[13]\n oa.power_setting = o[14]\n oa.damage = o[15]\n\n if nearest:\n ae.rtime = NR_TM + (max(min(nearest, FA_DIST), NR_DIST) - NR_DIST) / \\\n (FA_DIST - NR_DIST) * (FA_TM - NR_TM)\n #TODO tidy up inactive others; flag not to draw, delete if inactive for long enough\n return True\n else:\n print(jstring)\n return False\n \n else:\n print(r.getcode()) #!!\n return False\n except Exception as e:\n print(\"exception:\", e) \n \n \n#create the instances of Aeroplane\na = Aeroplane(\"assets/models/starship.obj\", 0.00, refid) ### Our ship\na.z, a.direction = 905, 180\n#a.z, a.direction = 1200, 180\n#create instance of instruments\ninst = Instruments()\nothers = {\"start\": 0.0} #contains a dictionary of other players keyed by refid\nthr = threading.Thread(target=json_load, args=(a, others))\nthr.daemon = True #allows the program to exit even if a Thread is still running\nthr.start()\n# Load textures for the environment cube\nectex = pi3d.loadECfiles(\"assets/textures/ecubes\", \"bkg1\")\nmyecube = pi3d.EnvironmentCube(size=7000.0, maptype=\"FACES\", camera=CAMERA)\nmyecube.set_draw_details(FLATSH, ectex)\nmyecube.set_fog((0.0,0.0,0.0,1.0), 4000)\n# Create elevation map\nmapwidth = 50000.0 #probably need to increase these\nmapdepth = 50000.0\nmapheight = 3000.0\n#mountimg1 = pi3d.Texture(\"assets/textures/mountains3_512.jpg\") ### get rid of this (we're in space)\nmountimg1 = pi3d.Texture(\"assets/textures/grid.png\") ### get rid of this (we're in space)\nbumpimg = pi3d.Texture(\"assets/textures/grasstile_n.jpg\") ### get rid of this (we're in space)\nreflimg = pi3d.Texture(\"assets/textures/stars.jpg\") ### update with space skybox\n#mymap = pi3d.ElevationMap(\"assets/textures/mountainsHgt.jpg\", name=\"map\",\n# width=mapwidth, depth=mapdepth, height=mapheight,\n# divx=64, divy=64, camera=CAMERA) ###we don't need this\nmymap = pi3d.ElevationMap(\"assets/textures/mountainsHgt.jpg\", name=\"map\",\n width=mapwidth, depth=mapdepth, height=mapheight,\n divx=64, divy=64, camera=CAMERA) ###we don't need this\n#mymap.set_draw_details(SHADER, [mountimg1, bumpimg, reflimg], 1024.0, 0.0)\nmymap.set_draw_details(SHADER, [mountimg1, bumpimg, reflimg], 0.0, 0.0)\n#mymap.set_fog((0.5, 0.5, 0.5, 1.0), 4000) ### make fog dark to hide?\n#mymap.set_fog((0.0, 0.0, 0.0, 1,0), 4000) ### make fog dark to hide?\n# init events\nif hasattr(sys, 'getwindowsversion') :\n print(\"OS is Windows - Input doesn't work here\")\nelse :\n inputs = pi3d.InputEvents()\n\n#inputs.get_mouse_movement()\nCAMERA.position((0.0, 0.0, -10.0)) #org\n\n\ncam_rot, cam_pitch = 0, 0\ncam_toggle = True #control mode\nmx=0\nmy=0\n\nif hasattr(sys, 'getwindowsversion') : ## If Windows, don't use input - This could go away when networking functions\n while DISPLAY.loop_running() :\n a.update_variables()\n loc = a.update_position(mymap.calcHeight(a.x, a.z))\n CAMERA.reset()\n #CAMERA.rotate(-20 + cam_pitch, -loc[3] + cam_rot, 0) #unreal view\n CAMERA.rotate(-20 + cam_pitch, -loc[3] + cam_rot, -a.roll) #air-sick view\n CAMERA.position((loc[0], loc[1], loc[2]))\n if instdisplay==True:\n inst.draw() ### comment this out to disable instruments\n a.draw() ### Draw your ship\n\n for i in others:\n if i == \"start\":\n continue\n b = others[i]\n b.update_variables()\n b.update_position(mymap.calcHeight(b.x, b.z))\n b.draw()\n #do httprequest if thread not already started and enough time has elapsed\n if not (thr.isAlive()) and (a.last_pos_time > (others[\"start\"] + a.rtime)):\n thr = threading.Thread(target=json_load, args=(a, others))\n thr.daemon = True #allows the program to exit even if a Thread is still running\n thr.start()\n \n if a.last_pos_time > (inst.update_time + NR_TM):\n inst.update(a, others)\n\n #mymap.draw() ### Draw \"ground\"\n myecube.position(loc[0], loc[1], loc[2])\n myecube.draw()\nelse: #Other OS's - like Linux\n while DISPLAY.loop_running() and not inputs.key_state(\"KEY_ESC\"):\n inputs.do_input_events() \n\n if inputs.key_state(\"KEY_Q\") or inputs.key_state(\"BTN_BASE3\"): #control mode\n print(\"X - 1 %s\" % (mx))\n mx=mx-1\n #mx=-1\n if inputs.key_state(\"KEY_E\") or inputs.key_state(\"BTN_BASE4\"): #control mode\n print(\"X + 1 %s\" % (mx))\n mx=mx+1\n #mx=1\n if inputs.key_state(\"KEY_SPACE\") or inputs.key_state(\"BTN_BASE4\"): #control mode\n print(\"Centering. X=%s Y=%s\" % (mx,my))\n mx=0\n my=0\n if inputs.key_state(\"KEY_I\") or inputs.key_state(\"BTN_BASE5\"): #control mode\n print(\"Y - 1 %s\" % (my))\n my=my-1\n #my=-1\n if inputs.key_state(\"KEY_K\") or inputs.key_state(\"BTN_BASE6\"): #control mode\n print(\"Y + 1 %s \" % (my))\n my=my+1\n #my=1\n\n #mx, my, mv, mh, md = inputs.get_mouse_movement()\n print(\"--%s--\"%(mx))\n #_, _, mv, mh, md = inputs.get_mouse_movement()\n if cam_toggle:\n a.set_ailerons(-mx * 0.001)\n a.set_elevator(my * 0.001)\n else:\n cam_rot -= mx * 0.1\n cam_pitch -= my * 0.1\n \n ### Control this over network\n if inputs.key_state(\"KEY_W\") or inputs.get_hat()[1] == -1: #increase throttle\n a.set_power(1)\n print(\"+ speed\")\n if inputs.key_state(\"KEY_S\") or inputs.get_hat()[1] == 1: #throttle back\n a.set_power(-1)\n print(\"- speed\")\n if inputs.key_state(\"KEY_X\"): #jump to first enemy!\n print(\"Jump\")\n for i in others:\n if i != \"start\":\n b = others[i]\n a.x, a.y, a.z = b.x, b.y + 5, b.z\n break\n if inputs.key_state(\"KEY_B\") or inputs.key_state(\"BTN_BASE2\"): #brakes\n print(\"brakes\")\n a.h_speed *= 0.99\n if inputs.key_state(\"KEY_V\") or inputs.key_state(\"BTN_TOP2\"): #view mode\n print(\"viewmode\")\n cam_toggle = False\n a.set_ailerons(0)\n a.set_elevator(0)\n if inputs.key_state(\"KEY_C\") or inputs.key_state(\"BTN_BASE\"): #control mode\n print(\"control mode\")\n cam_toggle = True\n cam_rot, cam_pitch = 0, 0\n\n if inputs.key_state(\"KEY_1\"): \n print(\"Toggle Instuments\")\n if instdisplay==True:\n instdisplay=False\n else:\n instdisplay=True\n\n if inputs.key_state(\"KEY_0\"): \n print(\"Screenshot\")\n pi3d.screenshot(\"screenshots/screenshot.jpg\")\n\n #if inputs.key_state(\"BTN_LEFT\") or inputs.key_state(\"BTN_PINKIE\") or inputs.key_state(\"KEY_P\"): #shoot\n if inputs.key_state(\"KEY_P\"): #shoot\n print(\"shoot\")\n #target is always nearest others set during last json_load()\n #tx, ty, tz = 0., 0.0, 0.0\n if a.nearest:\n tx, ty, tz = a.nearest.x, a.nearest.y, a.nearest.z\n a.nearest.other_damage += a.shoot([tx, ty, tz])\n\n a.update_variables()\n loc = a.update_position(mymap.calcHeight(a.x, a.z))\n CAMERA.reset()\n #CAMERA.rotate(-20 + cam_pitch, -loc[3] + cam_rot, 0) #unreal view\n CAMERA.rotate(-20 + cam_pitch, -loc[3] + cam_rot, -a.roll) #air-sick view\n CAMERA.position((loc[0], loc[1], loc[2]))\n if instdisplay==True:\n inst.draw() ### comment this out to disable instruments\n a.draw() ### Draw your ship\n\n for i in others:\n if i == \"start\":\n continue\n b = others[i]\n b.update_variables()\n b.update_position(mymap.calcHeight(b.x, b.z))\n b.draw()\n #do httprequest if thread not already started and enough time has elapsed\n if not (thr.isAlive()) and (a.last_pos_time > (others[\"start\"] + a.rtime)):\n thr = threading.Thread(target=json_load, args=(a, others))\n thr.daemon = True #allows the program to exit even if a Thread is still running\n thr.start()\n \n if a.last_pos_time > (inst.update_time + NR_TM):\n inst.update(a, others)\n\n #mymap.draw() ### Draw \"ground\"\n myecube.position(loc[0], loc[1], loc[2])\n myecube.draw()\n\n inputs.release()\n \n \nDISPLAY.destroy()\n","sub_path":"mainscreen.py","file_name":"mainscreen.py","file_ext":"py","file_size_in_byte":31353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"113429335","text":"\"\"\"\nWritten by: Irtiza Ali\nDate: 20/09/2018\nDesription: It contains an example related to python reduce function. In this example we will calculate factorial using \n reduce\n\"\"\"\nfrom functools import reduce\n\nnum = 4\n\nnums = list(range(1, num + 1))\nfactorial = reduce(lambda x, y: x * y, nums)\n\nprint(factorial)","sub_path":"functional-prog-py/reduce-function/reduce-function-exp2.py","file_name":"reduce-function-exp2.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"591165307","text":"\"\"\"\nЦарулкова Анастасия Витальевна\n2 группа 3 подгруппа\n\nCopyright: 09.2019\n\nЭтот скрипт вычисляет сумму элементов арифметической прогрессии от 1 до 50\n\"\"\"\n\nmySum = 0\nn = 51\nfor i in range (1,n):\n mySum = mySum + i\nprint(mySum)\n\n \n","sub_path":"sr1/isr/Sr1_isr1.2.py","file_name":"Sr1_isr1.2.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53068813","text":"from rest_framework import serializers\nfrom .models import Interviewer, Candidate, TimeSlot_Interviewer, TimeSlot_Candidate\n\nclass InterviewerSerializer(serializers.ModelSerializer):\n class Meta:\n model = Interviewer\n fields = ('id', 'first_name', 'last_name', 'email')\n\nclass CandidateSerializer(serializers.ModelSerializer):\n class Meta:\n model = Candidate\n fields = ('id', 'first_name', 'last_name', 'email')\n\nclass CandidateTimeSlotSerializer(serializers.ModelSerializer):\n def validate(self, data):\n errors = {}\n\n if ('start_date' in data and 'end_date' in data):\n start_date = data['start_date']\n end_date = data['end_date'] \n\n if(start_date > end_date):\n errors['error'] = u'end date before start date error'\n \n if(start_date == end_date):\n errors['error'] = u'end date should not be equal to start date'\n raise serializers.ValidationError(errors)\n\n return data\n\n class Meta:\n model = TimeSlot_Candidate \n fields = ('id', 'candidate', 'start_date', 'end_date')\n\n\nclass InterviewerTimeSlotSerializer(serializers.ModelSerializer):\n\n def validate(self, data):\n errors = {}\n\n if ('start_date' in data and 'end_date' in data):\n start_date = data['start_date']\n end_date = data['end_date'] \n\n if(start_date > end_date):\n errors['error'] = u'end date before start date error'\n \n if(start_date == end_date):\n errors['error'] = u'end date should not be equal to start date'\n raise serializers.ValidationError(errors)\n \n return data\n\n class Meta:\n model = TimeSlot_Interviewer\n fields = ('id', 'interviewer', 'start_date', 'end_date')\n\nclass MatchedTimeSlotsSerializer(serializers.Serializer):\n interviewer = InterviewerSerializer()\n start_date = serializers.DateTimeField()\n end_date = serializers.DateTimeField()\n\n class Meta:\n fields = ('interviewer', 'start_date', 'end_date')\n\nclass MatchedTimeSlotsSerializer_SM(serializers.Serializer):\n start_date = serializers.DateTimeField()\n end_date = serializers.DateTimeField()\n\n class Meta:\n fields = ('start_date', 'end_date')","sub_path":"timeslots_app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"318772523","text":"import random\nimport turtle\ndef polago(x , y, size, n, clr):\n \"\"\"\n funtion that draw random polagon and draw in random position \n by input begin x and y position, size of polagon, number, and collor\n \"\"\"\n # turtle setting\n turtle.screensize(1000)\n turtle.speed(30)\n turtle.setheading(0)\n turtle.color(clr)\n turtle.fillcolor(clr) \n turtle.goto(x, y)\n # draw random polagon \n while n > 1:\n # make random polagon\n turtle.pendown()\n turtle.begin_fill()\n # random size\n s = random.randint(10, size)\n a = random.randint(3, 8)\n for i in range (a):\n turtle.forward(s)\n turtle.left(360 / a) \n turtle.end_fill()\n n -= 1\n turtle.penup()\n turtle.goto(random.uniform(-300, 300), random.uniform(-300, 300))\n\n turtle.done\n\npolago(0, 0, 100, 50, \"blue\")","sub_path":"ex3/polygon_art.py","file_name":"polygon_art.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"221755796","text":"import os\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.linear_model import BayesianRidge\r\nfrom sklearn.linear_model import LinearRegression,LogisticRegression\r\nfrom sklearn import metrics\r\nfrom scipy import stats\r\nfrom sklearn.ensemble import RandomForestRegressor,GradientBoostingRegressor,RandomForestClassifier\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.ensemble import AdaBoostRegressor\r\nfrom sklearn import linear_model\r\nfrom sklearn.linear_model import SGDRegressor\r\nfrom category_encoders import TargetEncoder\r\nfrom sklearn.feature_selection import SelectKBest, f_regression\r\nimport xgboost\r\nfrom xgboost import XGBRegressor\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.tree import DecisionTreeClassifier\r\n\r\ndef S2(s1):\r\n if (s1 is not None):\r\n return str(s1).replace(' ','')[:8]\r\n else:\r\n return s1\r\n\r\ndef S3(s1):\r\n if (s1 is not None):\r\n return str(s1).replace(' ','')[:10]\r\n else:\r\n return s1 \r\n\r\ndef S4(s1):\r\n if (s1 is not None):\r\n return str(s1).replace(' ','')[:3]\r\n else:\r\n return s1\r\n\r\ndef S5(s1):\r\n if (s1 is not None):\r\n return str(s1).replace('-','')\r\n else:\r\n return s1 \r\n\r\ndef S6(s1):\r\n if (s1 is not None):\r\n return str(s1).replace('/','')\r\n else:\r\n return s1 \r\n\r\n\r\ndataset=pd.read_csv('MyVolts_train.csv', na_values=[\"\\\\N\",\"nA\"])\r\ndataset1\r\ndataset.isnull().any()\r\n# dataset['Gender']=dataset['Gender'].fillna('missing')\r\n# dataset['Profession']=dataset['Profession'].fillna('missing')\r\n# dataset['University Degree']=dataset['University Degree'].fillna('missing')\r\n# dataset['Hair Color']=dataset['Hair Color'].fillna('missing')\r\n# dataset.isnull().any()\r\n# dataset['Year of Record']\r\n\r\n#dropping cols which have \\N and nA in test data as they are not required for learning\r\ndatasetnoncateg=dataset.drop(['response_delivered','rec_processing_time','number_of_recs_in_set','time_recs_recieved','time_recs_displayed','time_recs_viewed','clicks','ctr','user_os','user_os_version','user_java_version','user_timezone','document_language_provided','year_published','number_of_authors','first_author_id','num_pubs_by_first_author','app_version'],axis=1)\r\n#find the % of missing values in each col\r\ndatasetnoncateg.isnull().mean().round(4) *100\r\n#drop cols with more than 50% of missing values\r\ndatasetnoncateg=datasetnoncateg.drop(['timezone_by_ip','local_time_of_request','local_hour_of_request'],axis=1)\r\ndatasetnoncateg.shape\r\n# datasetnoncateg.to_csv(r'C:\\projects\\tcd-ml-comp-201920-rec-alg-click-pred-group\\datasetnoncateg1.csv',index=False)\r\n\r\n#imputation of cols will be taken care by target encoder in case of cols with string values\r\n\r\n#trimming and imputation of the cols\r\nfrom sklearn.impute import SimpleImputer\r\nsimpleimputermedian=SimpleImputer(strategy='median')\r\ndatasetnoncateg['query_char_count']=simpleimputermedian.fit_transform(datasetnoncateg['query_char_count'].values.reshape(-1,1))\r\ndatasetnoncateg['query_word_count']=simpleimputermedian.fit_transform(datasetnoncateg['query_word_count'].values.reshape(-1,1))\r\ndatasetnoncateg['query_document_id']=simpleimputermedian.fit_transform(datasetnoncateg['query_document_id'].values.reshape(-1,1))\r\ndatasetnoncateg['abstract_word_count']=simpleimputermedian.fit_transform(datasetnoncateg['abstract_word_count'].values.reshape(-1,1))\r\ndatasetnoncateg['abstract_char_count']=simpleimputermedian.fit_transform(datasetnoncateg['abstract_char_count'].values.reshape(-1,1))\r\ndatasetnoncateg.query_identifier = list(datasetnoncateg.query_identifier.map(S2))\r\ndatasetnoncateg.item_type = list(datasetnoncateg.item_type.map(S2))\r\ndatasetnoncateg.request_received = list(datasetnoncateg.request_received.map(S3))\r\ndatasetnoncateg.request_received = list(datasetnoncateg.request_received.map(S5))\r\ndatasetnoncateg.request_received = list(datasetnoncateg.request_received.map(S6))\r\ndatasetnoncateg.request_received =pd.to_numeric(datasetnoncateg['request_received'])\r\ndatasetnoncateg['request_received']=datasetnoncateg['request_received'].fillna(method='ffill')\r\ndatasetnoncateg['request_received']=datasetnoncateg['request_received'].fillna(method='bfill')\r\ndatasetnoncateg.algorithm_class = list(datasetnoncateg.algorithm_class.map(S4))\r\ndatasetnoncateg.cbf_parser = list(datasetnoncateg.cbf_parser.map(S4))\r\n\r\n# datasetnoncateg.to_csv(r'C:\\projects\\tcd-ml-comp-201920-rec-alg-click-pred-group\\datasetnoncateg2.csv',index=False)\r\ndatasetnoncateg.isnull().any()\r\n\r\n\r\n\r\n# dataset['Age']=simpleimputermedian.fit_transform(dataset['Age'].values.reshape(-1,1))\r\n# dataset['Body Height [cm]']=simpleimputermedian.fit_transform(dataset['Body Height [cm]'].values.reshape(-1,1))\r\n# datasetnoncateg.Profession = list(datasetnoncateg.Profession.map(S2))\r\n\r\n#datasetcateg=pd.get_dummies(datasetnoncateg, prefix_sep='_')\r\n#colsToDrop = [col for col in datasetcateg.columns if 'missing' in col]\r\n#datasetcategnonmissing=datasetcateg.drop(colsToDrop,axis=1)\r\n\r\n\r\n\r\nM=pd.read_csv('MyVolts_test.csv', na_values=[\"\\\\N\",\"nA\"])\r\n# M.isnull().any()\r\n# M['Gender']=M['Gender'].fillna('missing')\r\n# M['Profession']=M['Profession'].fillna('missing')\r\n# M['University Degree']=M['University Degree'].fillna('missing')\r\n# M['Hair Color']=M['Hair Color'].fillna('missing')\r\n\r\n#dropping cols which have \\N and nA in test data as they are not required for learning\r\nMnoncateg=M.drop(['response_delivered','rec_processing_time','number_of_recs_in_set','time_recs_recieved','time_recs_displayed','time_recs_viewed','clicks','ctr','user_os','user_os_version','user_java_version','user_timezone','document_language_provided','year_published','number_of_authors','first_author_id','num_pubs_by_first_author','app_version'],axis=1)\r\n#find the % of missing values in each col\r\nMnoncateg.isnull().mean().round(4) *100\r\n#drop cols with more than 50% of missing values like in training\r\nMnoncateg=Mnoncateg.drop(['timezone_by_ip','local_time_of_request','local_hour_of_request'],axis=1)\r\nMnoncateg=Mnoncateg.drop(['set_clicked'],axis=1)\r\n#trimming the cols\r\nfrom sklearn.impute import SimpleImputer\r\nsimpleimputermedian=SimpleImputer(strategy='median')\r\nMnoncateg['query_char_count']=simpleimputermedian.fit_transform(Mnoncateg['query_char_count'].values.reshape(-1,1))\r\nMnoncateg['query_word_count']=simpleimputermedian.fit_transform(Mnoncateg['query_word_count'].values.reshape(-1,1))\r\nMnoncateg['query_document_id']=simpleimputermedian.fit_transform(Mnoncateg['query_document_id'].values.reshape(-1,1))\r\nMnoncateg['abstract_word_count']=simpleimputermedian.fit_transform(Mnoncateg['abstract_word_count'].values.reshape(-1,1))\r\nMnoncateg['abstract_char_count']=simpleimputermedian.fit_transform(Mnoncateg['abstract_char_count'].values.reshape(-1,1))\r\nMnoncateg.query_identifier = list(Mnoncateg.query_identifier.map(S2))\r\nMnoncateg.item_type = list(Mnoncateg.item_type.map(S2))\r\nMnoncateg.request_received = list(Mnoncateg.request_received.map(S3))\r\nMnoncateg.request_received = list(Mnoncateg.request_received.map(S5))\r\nMnoncateg.request_received = list(Mnoncateg.request_received.map(S6))\r\nMnoncateg.request_received =pd.to_numeric(Mnoncateg['request_received'])\r\nMnoncateg['request_received']=datasetnoncateg['request_received'].fillna(method='ffill')\r\nMnoncateg['request_received']=datasetnoncateg['request_received'].fillna(method='bfill')\r\nMnoncateg.algorithm_class = list(Mnoncateg.algorithm_class.map(S4))\r\nMnoncateg.cbf_parser = list(Mnoncateg.cbf_parser.map(S4))\r\n\r\n\r\n# M['Year of Record']=simpleimputermedian.fit_transform(M['Year of Record'].values.reshape(-1,1))\r\n# M['Age']=simpleimputermedian.fit_transform(M['Age'].values.reshape(-1,1))\r\n# M['Body Height [cm]']=simpleimputermedian.fit_transform(M['Body Height [cm]'].values.reshape(-1,1))\r\n# Mnoncateg=M.drop(['Instance','Hair Color','Wears Glasses','Hair Color','Income'],axis=1)\r\n# Mnoncateg.Profession = list(Mnoncateg.Profession.map(S2))\r\n# Mcateg=pd.get_dummies(Mnoncateg, prefix_sep='_')\r\n# colsToDropM = [col for col in Mcateg.columns if 'missing' in col]\r\n# Mcategnonmissing=Mcateg.drop(colsToDropM,axis=1)\r\n\r\n\r\n# for column in datasetcategnonmissing:\r\n# if column not in Mcategnonmissing:\r\n# if column != 'Income in EUR':\r\n# Mcategnonmissing[column]=0\r\n\r\n\r\n# for column in Mcategnonmissing:\r\n# if column not in datasetcategnonmissing:\r\n# datasetcategnonmissing[column]=0 \r\n\r\n\r\n#datasetcategnonmissing=datasetcategnonmissing.sort_index(axis=1)\r\n#Mcategnonmissing=Mcategnonmissing.sort_index(axis=1)\r\n\r\n#z1 = np.abs(stats.zscore(datasetcategnonmissing))\r\n#z2 = np.abs(stats.zscore(Mcategnonmissing))\r\n#datasetcategnonmissing=datasetcategnonmissing[(z1 < 3).all(axis=1)]\r\n#Mcategnonmissing=Mcategnonmissing[(z2 < 3).all(axis=1)]\r\n\r\n#X=datasetcategnonmissing.drop('Income in EUR',axis=1).values\r\n#Y=datasetcategnonmissing['Income in EUR'].values\r\n\r\n\r\nX=datasetnoncateg.drop('set_clicked',axis=1).values\r\nY=datasetnoncateg['set_clicked'].values\r\n#target encoding\r\nt1 = TargetEncoder()\r\nt1.fit(X, Y)\r\nX = t1.transform(X)\r\n\r\nX.isnull().any()\r\n\r\n#auto feature selection\r\n# K= SelectKBest(f_regression, k=10)\r\n# K.fit(X,Y)\r\n# X=K.transform(X)\r\n\r\n\r\nXtrain, Xtest, Ytrain, Ytest = train_test_split(X, Y, test_size=0.2, random_state=0)\r\n# regressor = BayesianRidge()\r\n# regressor = RandomForestClassifier(n_estimators=100, min_samples_leaf=3)\r\n#regressor = AdaBoostRegressor()\r\n#regressor = = linear_model.SGDRegressor(max_iter=1000, tol=1e-3)\r\n#regressor = XGBRegressor()\r\n# regressor = GradientBoostingRegressor(n_estimators=1000)\r\n# regressor = LogisticRegression()\r\n# regressor=GaussianNB()\r\n# regressor=DecisionTreeClassifier(random_state=0)\r\nregressor = RandomForestClassifier(n_estimators=1000)\r\n\r\n\r\n\r\nfitResult = regressor.fit(Xtrain, Ytrain)\r\nYPredTest = regressor.predict(Xtest)\r\n#learningTest = pd.DataFrame({'Predicted': YPredTest, 'Actual': Ytest })\r\n# np.sqrt(metrics.mean_squared_error(Ytest, YPredTest))\r\nfrom sklearn.metrics import confusion_matrix\r\nprint(confusion_matrix(Ytest, YPredTest))\r\nprint('Accuracy: %d',(regressor.score(Xtest,Ytest)))\r\nprint('scores: %d',(cross_val_score(regressor, X, Y, cv=5)))\r\n\r\n\r\nA=Mnoncateg.values\r\nA1=t1.transform(A)\r\n# A2 = K.transform(A1)\r\nB=regressor.predict(A1)\r\n\r\ndf2=pd.DataFrame()\r\ndf2['recommendation_set_id']=M['recommendation_set_id']\r\ndf2['set_clicked']=B\r\n\r\ndf2.to_csv(r'C:\\projects\\tcd-ml-comp-201920-rec-alg-click-pred-group\\outputRF1002_minleaf3.csv',index=False)\r\n","sub_path":"MyVolts.py","file_name":"MyVolts.py","file_ext":"py","file_size_in_byte":10506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"310581468","text":"\nimport math\n\n\n\ndef solution(n):\n answer = 0\n for i in range(2, n+1):\n if isSosu(i):\n answer += 1\n return answer\n\n\ndef isSosu(number):\n for i in range(2, int(math.floor(math.sqrt(number)))+1):\n if number % i == 0:\n return False\n\n return True","sub_path":"programers/findSosu.py","file_name":"findSosu.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248267939","text":"\n\nfrom xai.brain.wordbase.verbs._yammer import _YAMMER\n\n#calss header\nclass _YAMMERING(_YAMMER, ):\n\tdef __init__(self,): \n\t\t_YAMMER.__init__(self)\n\t\tself.name = \"YAMMERING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"yammer\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_yammering.py","file_name":"_yammering.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"474049508","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom math import sqrt\nfrom random import random\nfrom typing import List, Iterator\nfrom radixal import radify, InvalidBase\n\n\ndef primes(n: int) -> List[int]:\n \"\"\"\n Returns a list of primes < n.\n\n :param n: maximum value\n :returns: sequence of primes\n \"\"\"\n sieve = [True] * n\n\n for i in range(3, int(sqrt(n)) + 1, 2):\n if sieve[i]:\n start = i * i\n step = 2 * i\n sieve[start::step] = [False] * ((n - i * i - 1) // (2 * i) + 1)\n\n return [2] + [i for i in range(3, n, 2) if sieve[i]]\n\n\ndef values(n: int) -> Iterator[int]:\n \"\"\"\n Generate test values (0 and primes).\n Sign of prime numbers is pseudo-random.\n\n :param n: maximum value\n :return: iterator of ints\n \"\"\"\n yield 0\n for p in primes(n):\n yield -p if random() < 0.5 else p\n\n\n@pytest.mark.parametrize(\n 'value', [\n pytest.param(\n i, id=\"value={:d}\".format(i)\n ) for i in values(100)\n ]\n)\n@pytest.mark.parametrize(\n 'base', [\n pytest.param(\n i, id=\"base={:d}\".format(i)\n ) for i in range(2, 37)\n ]\n)\ndef test_valid_base(value: int, base: int):\n \"\"\"\n Test output from :func:`radify` passed to :class:`int` equals input.\n\n :param value:\n :param base:\n :return:\n \"\"\"\n string = radify(value, base)\n actual = int(string, base)\n assert actual == value\n\n\n@pytest.mark.parametrize(\n 'base', [\n pytest.param(\n i, id=\"base={:d}\".format(i)\n ) for i in (-1, 0, 37, 50, 64)\n ]\n)\ndef test_invalid_base(base: int):\n \"\"\"\n Test that :class:`InvalidBase` raises in appropriate conditions.\n\n :param base: test value\n \"\"\"\n with pytest.raises(InvalidBase):\n radify(255, base)\n","sub_path":"tests/func/test_radify.py","file_name":"test_radify.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398078623","text":"'''\n\n\n709. To Lower Case\n\n\nImplement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. \n\nExample 1:\n\nInput: \"Hello\"\nOutput: \"hello\"\nExample 2:\n\nInput: \"here\"\nOutput: \"here\"\nExample 3:\n\nInput: \"LOVELY\"\nOutput: \"lovely\"\n\n'''\n\nclass Solution:\n def toLowerCase(self, str):\n \"\"\"\n :type str: str\n :rtype: str\n \"\"\"\n \n result = []\n for char in str:\n ascii_value = ord(char)\n if ascii_value >= 65 and ascii_value <= 90:\n ascii_value += 32\n \n result += chr(ascii_value)\n \n return \"\".join(result)\n\n","sub_path":"EASY/709_To_Lower_Case.py","file_name":"709_To_Lower_Case.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"588264990","text":"#!/usr/bin/env python3\n\"\"\"A utility script for automating the beets release process.\n\"\"\"\nimport click\nimport os\nimport re\nimport subprocess\nfrom contextlib import contextmanager\n\nBASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nCHANGELOG = os.path.join(BASE, 'docs', 'changelog.rst')\n\n\n@contextmanager\ndef chdir(d):\n \"\"\"A context manager that temporary changes the working directory.\n \"\"\"\n olddir = os.getcwd()\n os.chdir(d)\n yield\n os.chdir(olddir)\n\n\n@click.group()\ndef release():\n pass\n\n\n# Locations (filenames and patterns) of the version number.\nVERSION_LOCS = [\n (\n os.path.join(BASE, 'beets', '__init__.py'),\n [\n (\n r'__version__\\s*=\\s*[\\'\"]([0-9\\.]+)[\\'\"]',\n \"__version__ = '{version}'\",\n )\n ]\n ),\n (\n os.path.join(BASE, 'docs', 'conf.py'),\n [\n (\n r'version\\s*=\\s*[\\'\"]([0-9\\.]+)[\\'\"]',\n \"version = '{minor}'\",\n ),\n (\n r'release\\s*=\\s*[\\'\"]([0-9\\.]+)[\\'\"]',\n \"release = '{version}'\",\n ),\n ]\n ),\n (\n os.path.join(BASE, 'setup.py'),\n [\n (\n r'version\\s*=\\s*[\\'\"]([0-9\\.]+)[\\'\"]',\n \" version='{minor}',\",\n )\n ]\n ),\n]\n\n@release.command()\n@click.argument('version')\ndef bump(version):\n \"\"\"Update the version number in setup.py, docs config, changelog,\n and root module.\n \"\"\"\n version_parts = [int(p) for p in version.split('.')]\n assert len(version_parts) == 3, \"invalid version number\"\n minor = '{}.{}'.format(*version_parts)\n major = '{}'.format(*version_parts)\n\n # Replace the version each place where it lives.\n for filename, locations in VERSION_LOCS:\n # Read and transform the file.\n out_lines = []\n with open(filename) as f:\n for line in f:\n for pattern, template in locations:\n match = re.match(pattern, line)\n if match:\n # Check that this version is actually newer.\n old_version = match.group(1)\n old_parts = [int(p) for p in old_version.split('.')]\n assert version_parts > old_parts, \\\n \"version must be newer than {}\".format(old_version)\n\n # Insert the new version.\n out_lines.append(template.format(\n version=version,\n major=major,\n minor=minor,\n ) + '\\n')\n\n break\n \n else:\n # Normal line.\n out_lines.append(line)\n\n # Write the file back.\n with open(filename, 'w') as f:\n f.write(''.join(out_lines))\n \n # Generate bits to insert into changelog.\n header_line = '{} (in development)'.format(version)\n header = '\\n\\n' + header_line + '\\n' + '-' * len(header_line) + '\\n\\n'\n header += 'Changelog goes here!\\n'\n\n # Insert into the right place.\n with open(CHANGELOG) as f:\n contents = f.read()\n location = contents.find('\\n\\n') # First blank line.\n contents = contents[:location] + header + contents[location:]\n\n # Write back.\n with open(CHANGELOG, 'w') as f:\n f.write(contents)\n\n\n@release.command()\ndef build():\n \"\"\"Use `setup.py` to build a source tarball.\n \"\"\"\n with chdir(BASE):\n subprocess.check_call(['python2', 'setup.py', 'sdist'])\n\n\n@release.command()\ndef changelog():\n \"\"\"Translate the most recent version's changelog to Markdown using Pandoc.\n \"\"\"\n # Extract the first section of the changelog.\n started = False\n lines = []\n with open(CHANGELOG) as f:\n for line in f:\n if re.match(r'^--+$', line.strip()):\n # Section boundary. Start or end.\n if started:\n # Remove last line, which is the header of the next\n # section.\n del lines[-1]\n break\n else:\n started = True\n\n elif started:\n lines.append(line)\n changelog = ''.join(lines).strip()\n\n print(changelog)\n\n\nif __name__ == '__main__':\n release()\n","sub_path":"extra/release.py","file_name":"release.py","file_ext":"py","file_size_in_byte":4423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"158319547","text":"#Importación de librerías\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\nimport pandas as pd\n\n#Creación de la app de dash\napp = dash.Dash()\n\n# Carga datos\ndf_iris = pd.read_csv(r'C:\\Users\\ivan_pinar\\Dropbox\\Creación de MOCs\\MOC Dash Python\\Datasets\\4.6\\iris_dataset.csv',encoding = 'ISO-8859-1',delimiter=',')\n\n#Objetos plotly.graph\ndata1 = [go.Scatter(x=df_iris[\"longitud_sépalo\"],\n y=df_iris[\"anchura_sépalo\"],\n mode=\"markers\",\n marker = dict(\n size=12,\n symbol=\"circle\",\n line={\"width\":3} #línea del marcador\n ))]\n\nlayout1 = go.Layout(title=\"Iris Scatter plot sépalo\",\n xaxis=dict(title=\"Longitud sépalo\"),\n yaxis=dict(title=\"Anchura sépalo\"))\n\ndata2 = [go.Scatter(x=df_iris[\"longitud_pétalo\"],\n y=df_iris[\"anchura_pétalo\"],\n mode=\"markers\",\n marker = dict(\n size=12,\n symbol=\"circle\",\n line={\"width\":3} #línea del marcador\n ))]\n\nlayout2 = go.Layout(title=\"Iris Scatter plot pétalo\",\n xaxis=dict(title=\"Longitud pétalo\"),\n yaxis=dict(title=\"Anchura pétalo\"))\n\n#Definición del layout de la app a partir de componentes HTML y Core\napp.layout = html.Div([dcc.Graph(id='scatterplot',\n figure = {'data':data1,\n 'layout':layout1}\n ),\n dcc.Graph(id='scatterplot2',\n figure = {'data':data2,\n 'layout':layout2}\n )\n ])\n\n#Sentencias para abrir el servidor al ejecutar este script\nif __name__ == '__main__':\n app.run_server(port=8000)\n","sub_path":"Scripts/4.6_Plotly_a_dash.py","file_name":"4.6_Plotly_a_dash.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"579438625","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport compte.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('projets', '__first__'),\n ('ressources', '0002_compte_gl_employe'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Depense_Eci',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('date', models.DateField(verbose_name='Date')),\n ('detail', models.CharField(max_length=50, verbose_name='D\\xe9tails')),\n ('montant', models.DecimalField(default=0.0, verbose_name='Montant sans taxes', max_digits=12, decimal_places=2)),\n ('tps', models.DecimalField(default=0.0, verbose_name='TPS/TVH', max_digits=12, decimal_places=2)),\n ('tvq', models.DecimalField(default=0.0, verbose_name='TVQ', max_digits=12, decimal_places=2)),\n ('photo', models.ImageField(upload_to=compte.models.upload_path, blank=True)),\n ('approuve', models.BooleanField(default=False, verbose_name='Approuv\\xe9?')),\n ('paye', models.BooleanField(default=False, verbose_name='Pay\\xe9?')),\n ('approved_on', models.DateTimeField(null=True, verbose_name='Approuv\\xe9 le', blank=True)),\n ('approved_by', models.ForeignKey(related_name='approving_employe', verbose_name='Approuv\\xe9 par', to='ressources.Employe')),\n ('employe', models.ForeignKey(verbose_name='Employ\\xe9', to='ressources.Employe')),\n ('gl', models.ForeignKey(verbose_name='GL', to='ressources.Compte_gl')),\n ('projet', models.ForeignKey(verbose_name='Num\\xe9ro de projet', to='projets.Projet_Eugenie')),\n ],\n options={\n 'verbose_name': 'D\\xe9pense Eug\\xe9nie Canada',\n 'verbose_name_plural': 'D\\xe9penses Eug\\xe9nie Canada',\n },\n ),\n ]\n","sub_path":"django/intranet/compte/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"527896699","text":"import os\nimport time\n\ndef timer(hours, minutes, seconds):\n seconds = (hours * 60 * 60) + (minutes * 60) + (seconds)\n v1 = int(time.time())\n v2 = v1 + seconds\n while v1 != v2:\n v1 = int(time.time())\n time.sleep(1)\n return True\n\ndef timerS(hours, minutes, seconds, sleep=[30]):\n seconds = (hours * 60 * 60) + (minutes * 60) + (seconds)\n v1 = int(time.time())\n v2 = v1 + seconds\n while v1 != v2:\n v1 = int(time.time())\n time.sleep(1)\n os.system(\"alarm.wav\")\n time.sleep(3*60)\n while True:\n time.sleep(sleep[0])\n while v1 != v2:\n v1 = int(time.time())\n time.sleep(1)\n os.system(\"alarm2.wav\")\n time.sleep(2*60)\n \n\n#if timer(0, 0, 25):\n# #os.system(r'\"C:\\Documents and Settings\\Owner\\My Documents\\alex\\scripts\\music projects\\Music\\10000.wav\"')\n# os.system('msg * \"TIME\"')\ntimerS(6, 45, 10)\n","sub_path":"Python/Python scripts/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"188350489","text":"# -------------------------------------------------------\n# Median of Two Sorted Arrays - https://leetcode.com/problems/median-of-two-sorted-arrays/\n# -------------------------------------------------------\n# Author: Arshad Mehmood\n# Github: https://github.com/arshad115\n# Blog: https://arshadmehmood.com\n# LinkedIn: https://www.linkedin.com/in/arshadmehmood115\n# Date : 2020-07-20\n# Project: 100-days-of-leetcode\n# Comments: Binary search algorithm learned from https://www.youtube.com/watch?v=LPFhl65R7ww https://github.com/mission-peace/interview/blob/master/src/com/interview/binarysearch/MedianOfTwoSortedArrayOfDifferentLength.java\n# -------------------------------------------------------\nimport sys\nfrom math import inf\nfrom statistics import median\nfrom typing import List\n\n\nclass Solution:\n def medianUsingStatistics(self, nums1: List[int], nums2: List[int]) -> float:\n numbs = nums1 + nums2\n numbs = sorted(numbs) # n log n\n\n m = median(numbs)\n return m\n def medianUsingPython(self, nums1: List[int], nums2: List[int]) -> float:\n numbs = nums1 + nums2\n numbs = sorted(numbs) # n log n\n\n n = len(numbs)\n if n %2 == 0:\n return float(numbs[n//2 - 1] + numbs[n//2 + 1])/2 # // is floor\n else:\n return numbs[n//2]\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n \"\"\"\n Solution\n Take minimum size of two array. Possible number of partitions are from 0 to m in m size array.\n Try every cut in binary search way. When you cut first array at i then you cut second array at (m + n + 1)/2 - i\n Now try to find the i where a[i-1] <= b[j] and b[j-1] <= a[i]. So this i is partition around which lies the median.\n\n Time complexity is O(log(min(x,y))\n Space complexity is O(1)\n \"\"\"\n # if input1 length is greater than switch them so that input1 is smaller than input2.\n if len(nums1) > len(nums2):\n nums1, nums2 = nums2, nums1 #swap\n\n x, y = len(nums1), len(nums2)\n low, high = 0, x\n\n while low <= high:\n partitionX = int((low + high) / 2)\n partitionY = int((x + y + 1) / 2 - partitionX) # +1 to deal with odd cases\n\n # if partitionX is 0 it means nothing is there on left side.Use -INF for maxLeftX\n # if partitionX is length of input then there is nothing on right side.Use +INF for minRightX\n maxLeftX = nums1[partitionX - 1] if partitionX != 0 else -inf\n minRightX = nums1[partitionX] if partitionX != x else inf\n\n maxLeftY = nums2[partitionY - 1] if partitionY != 0 else -inf\n minRightY = nums2[partitionY] if partitionY != y else inf\n\n if maxLeftX <= minRightY and maxLeftY <= minRightX:\n # We have partitioned array at correct place\n # Now get max of left elements and min of right elements to get the median in case of even length combined array size\n # or get max of left for odd length combined array size.\n if ((x + y) % 2 == 0):\n return float(max(maxLeftX, maxLeftY) + min(minRightX, minRightY))/2;\n else:\n return float(max(maxLeftX, maxLeftY))\n elif (maxLeftX > minRightY): # we are too far on right side for partitionX.Go on left side.\n high = partitionX - 1\n else: # we are too far on left side for partitionX.Go on right side.\n low = partitionX + 1\n return 0\n\n\nsolution = Solution()\nnum = solution.findMedianSortedArrays([1,3],[2])\nprint(num)","sub_path":"codes/2020-07-20-median-of-two-sorted-arrays.py","file_name":"2020-07-20-median-of-two-sorted-arrays.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631286117","text":"from matplotlib import pyplot\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nsize_list = [50, 100, 300, 500, 1000]\r\nwindow_list = [2, 5, 7, 10]\r\nmin_count_list = [10, 20, 50, 100]\r\n\r\nparam_list = {\r\n 'size': size_list,\r\n 'window': window_list,\r\n 'count': min_count_list\r\n}\r\n\r\ndef select_dataframe(df, model, type):\r\n return df[(df['model'] == model) & (df['type'] == type)]\r\n\r\ndef compare_param(df, pivot_param):\r\n type = df['type'].get_values()[0]\r\n model = df['model'].get_values()[0]\r\n\r\n fig, ax1 = plt.subplots()\r\n series_list = []\r\n name_list = []\r\n for param in param_list[pivot_param]:\r\n selected_df = df[df[pivot_param] == param]\r\n selected_df = selected_df.reset_index(drop=True)\r\n series_list.append(selected_df['val_acc'])\r\n name_list.append(str(param))\r\n result_df = pd.concat(series_list, axis=1, ignore_index=True)\r\n result_df.columns = [name_list]\r\n ax1.set_title(\"{0}_{1}_{2}\".format(type, model, pivot_param))\r\n result_df.boxplot(ax = ax1, showfliers=False, showbox=True, showcaps=True)\r\n plt.show()\r\n\r\ndef compare_model(*args):\r\n fig, ax1 = plt.subplots()\r\n vs = []\r\n names = []\r\n for arg in args:\r\n v1 = arg['val_acc']\r\n v1 = v1.reset_index(drop=True)\r\n type1 = arg['type'].get_values()[0]\r\n model1 = arg['model'].get_values()[0]\r\n names.append((type1, model1))\r\n vs.append(v1)\r\n all = pd.concat(vs, axis=1, ignore_index=True)\r\n column_names = [\"{0}_{1}\".format(i[0], i[1]) for i in names]\r\n all.columns=[column_names]\r\n all.boxplot(ax = ax1, showfliers=False, showbox=True, showcaps=True)\r\n ax1.set_title(\"val_acc\")\r\n plt.show()\r\n\r\n\r\ndef plot_3d_surf(df, size):\r\n from mpl_toolkits.mplot3d import Axes3D\r\n import matplotlib.pyplot as plt\r\n from matplotlib import cm\r\n import numpy as np\r\n import pandas as pd\r\n from sys import argv\r\n type = df['type'].get_values()[0]\r\n model = df['model'].get_values()[0]\r\n selected_df = df[df['size'] == size]\r\n x = selected_df.as_matrix([\"count\"])\r\n y = selected_df.as_matrix([\"window\"])\r\n z = selected_df.as_matrix([\"val_acc\"])\r\n\r\n fig = plt.figure()\r\n ax = Axes3D(fig)\r\n surf = ax.plot_trisurf(x.reshape(-1),y.reshape(-1),z.reshape(-1), cmap=cm.jet, linewidth=0.1)\r\n\r\n max_index= np.argmax(z)\r\n min_index = np.argmin(z)\r\n ax.text(x[max_index][0], y[max_index][0], z[max_index][0], 'max %s' % (str(z[max_index])), size=10, zorder=1,\r\n color='k')\r\n ax.text(x[min_index][0], y[min_index][0], z[min_index][0], 'min %s' % (str(z[min_index])), size=10, zorder=1,\r\n color='k')\r\n\r\n fig.colorbar(surf, shrink=0.5, aspect=5)\r\n\r\n ax.set_xlabel('min count')\r\n ax.set_ylabel('window')\r\n ax.set_zlabel('val_acc')\r\n ax.set_title(\"{0} dim/{1}_{2}\".format(str(size), type, model))\r\n\r\n plt.show()\r\n\r\ndef scatter(df, size, groupBy='window', line=False):\r\n max_values = []\r\n\r\n size_filtered_df = df[df['size']==size]\r\n\r\n type = df['type'].get_values()[0]\r\n model = df['model'].get_values()[0]\r\n\r\n xs = []\r\n ys = []\r\n zs = []\r\n\r\n fig = pyplot.figure()\r\n ax = Axes3D(fig)\r\n\r\n color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']\r\n if(groupBy is not None):\r\n assert groupBy in ['window', 'count']\r\n for param in param_list[groupBy]:\r\n selected_df = size_filtered_df[size_filtered_df[groupBy] == param]\r\n if(groupBy == \"window\"):\r\n xs.append(selected_df.as_matrix([\"count\"]))\r\n ys.append(selected_df.as_matrix([\"window\"]))\r\n zs.append(selected_df.as_matrix([\"val_acc\"]))\r\n else:\r\n xs.append(selected_df.as_matrix([\"window\"]))\r\n ys.append(selected_df.as_matrix([\"count\"]))\r\n zs.append(selected_df.as_matrix([\"val_acc\"]))\r\n\r\n for i, x in enumerate(xs):\r\n x = xs[i]\r\n y = ys[i]\r\n z = zs[i]\r\n max_values.append(max(z))\r\n\r\n pivot_order = x.argsort(axis=0)\r\n x = x[pivot_order].reshape(-1,1)\r\n y = y[pivot_order].reshape(-1,1)\r\n z = z[pivot_order].reshape(-1,1)\r\n\r\n pivot_order = y.argsort(axis=0)\r\n x = x[pivot_order].reshape(-1,1)\r\n y = y[pivot_order].reshape(-1,1)\r\n z = z[pivot_order].reshape(-1,1)\r\n\r\n if(line == True):\r\n ax.plot_wireframe(x, y, z, color=color_list[i], label=str(param_list[groupBy][i]))\r\n else:\r\n ax.scatter(x, y, z, label=str(param_list[groupBy][i]))\r\n ax.set_xlabel('min_count')\r\n ax.set_ylabel('window')\r\n ax.set_zlabel('val_acc')\r\n ax.set_title(\"{0} dim/{1}_{2}\".format(str(size), type, model))\r\n plt.legend(loc='upper left', numpoints=1, ncol=4, fontsize=8, bbox_to_anchor=[0.1, 0], title=groupBy)\r\n else:\r\n x = size_filtered_df.as_matrix([\"count\"])\r\n y = size_filtered_df.as_matrix([\"window\"])\r\n z = size_filtered_df.as_matrix([\"val_acc\"])\r\n ax.scatter(x, y, z)\r\n ax.set_xlabel('min_count')\r\n ax.set_ylabel('window')\r\n ax.set_zlabel('val_acc')\r\n ax.set_title(\"{0}_{1}/{2} dim\".format(type, model,str(size)))\r\n pyplot.show()\r\n\r\n result_order = np.argsort(max_values, axis=0).reshape(-1)\r\n return np.array(param_list[groupBy])[result_order]","sub_path":"visualize_result.py","file_name":"visualize_result.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88067193","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api, exceptions\nimport base64\nfrom openerp.osv import osv\nfrom reportlab.lib.enums import TA_JUSTIFY\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.units import inch\nfrom reportlab.lib.colors import magenta, red , black, white, blue, gray, Color, HexColor, PCMYKColor, PCMYKColorSep\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.lib.pagesizes import letter, A4, legal\nfrom reportlab.platypus import SimpleDocTemplate, Table, TableStyle\nfrom reportlab.lib import colors\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.platypus import Paragraph, Table\nfrom reportlab.lib.units import cm,mm\nfrom reportlab.lib.utils import simpleSplit\nfrom cgi import escape\nfrom functools import reduce\nimport decimal\nimport calendar\n\ndef dig_5(n):\n\treturn (\"%5d\" % n).replace(' ','0')\n\nclass rm_report_extraccion_line(models.Model):\n\t_inherit = 'rm.report.extraccion.line'\n\n\tenero_usd = fields.Float('Enero',digits=(12,2),compute='get_enero_usd')\n\tfebrero_usd = fields.Float('Febrero',digits=(12,2),compute='get_febrero_usd')\n\tmarzo_usd = fields.Float('Marzo',digits=(12,2),compute='get_marzo_usd')\n\tabril_usd = fields.Float('Abril',digits=(12,2),compute='get_abril_usd')\n\tmayo_usd = fields.Float('Mayo',digits=(12,2),compute='get_mayo_usd')\n\tjunio_usd = fields.Float('Junio',digits=(12,2),compute='get_junio_usd')\n\tjulio_usd = fields.Float('Julio',digits=(12,2),compute='get_julio_usd')\n\tagosto_usd = fields.Float('Agosto',digits=(12,2),compute='get_agosto_usd')\n\tseptiembre_usd = fields.Float('Septiembre',digits=(12,2),compute='get_septiembre_usd')\n\toctubre_usd = fields.Float('Octubre',digits=(12,2),compute='get_octubre_usd')\n\tnoviembre_usd = fields.Float('Noviembre',digits=(12,2),compute='get_noviembre_usd')\n\tdiciembre_usd = fields.Float('Diciembre',digits=(12,2),compute='get_diciembre_usd')\n\n\t@api.one\n\tdef get_enero_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '01/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '01/'))==1 else 1 \n\t\tself.enero_usd = self.enero/ex\n\n\t@api.one\n\tdef get_febrero_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '02/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '02/'))==1 else 1 \n\t\tself.febrero_usd = self.febrero/ex\n\n\t@api.one\n\tdef get_marzo_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '03/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '03/'))==1 else 1 \n\t\tself.marzo_usd = self.marzo/ex\n\n\t@api.one\n\tdef get_abril_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '04/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '04/'))==1 else 1 \n\t\tself.abril_usd = self.abril/ex\n\n\t@api.one\n\tdef get_mayo_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '05/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '05/'))==1 else 1 \n\t\tself.mayo_usd = self.mayo/ex\n\t@api.one\n\tdef get_junio_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '06/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '06/'))==1 else 1 \n\t\tself.junio_usd = self.junio/ex\n\n\t@api.one\n\tdef get_julio_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '07/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '07/'))==1 else 1 \n\t\tself.julio_usd = self.julio/ex\n\n\t@api.one\n\tdef get_agosto_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '08/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '08/'))==1 else 1 \n\t\tself.agosto_usd = self.agosto/ex\n\n\t@api.one\n\tdef get_septiembre_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '09/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '09/'))==1 else 1 \n\t\tself.septiembre_usd = self.septiembre/ex\n\n\t@api.one\n\tdef get_octubre_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '10/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '10/'))==1 else 1 \n\t\tself.octubre_usd = self.octubre/ex\n\n\t@api.one\n\tdef get_noviembre_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '11/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '11/'))==1 else 1 \n\t\tself.noviembre_usd = self.noviembre/ex\n\n\t@api.one\n\tdef get_diciembre_usd(self):\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.rm_report_extraccion_id.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\t\tex = ex.filtered(lambda x:x.periodo_id.name[:3] == '12/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '12/'))==1 else 1 \n\t\tself.diciembre_usd = self.diciembre/ex\n\n\t@api.one\n\tdef get_acumulado_usd(self):\n\t\tself.acumulado_usd = self.enero_usd + self.febrero_usd + self.marzo_usd + self.abril_usd + self.mayo_usd + self.junio_usd + self.julio_usd + self.agosto_usd + self.septiembre_usd + self.octubre_usd + self.noviembre_usd + self.diciembre_usd\n\tacumulado_usd = fields.Float('Acumulado USD', readonly=True, default=0, compute=\"get_acumulado_usd\")\n\n\t@api.one\n\tdef get_acumulado_pciento_usd(self):\n\t\tif self.acumulado_usd != 0:\n\t\t\tself.acumulado_pciento_usd = self.acumulado_usd / self.rm_report_extraccion_id.total_general_usd\n\t\telse:\n\t\t\tself.acumulado_pciento_usd = 0\n\tacumulado_pciento_usd = fields.Float('% ACUM', readonly=True, compute=\"get_acumulado_pciento_usd\")\n\n\t@api.one\n\tdef get_promedio_usd(self):\n\t\tvalues = []\n\t\tif self.enero_usd != 0:\n\t\t\tvalues.append(self.enero_usd)\n\t\tif self.febrero_usd != 0:\n\t\t\tvalues.append(self.febrero_usd)\n\t\tif self.marzo_usd != 0:\n\t\t\tvalues.append(self.marzo_usd)\n\t\tif self.abril_usd != 0:\n\t\t\tvalues.append(self.abril_usd)\n\t\tif self.mayo_usd != 0:\n\t\t\tvalues.append(self.mayo_usd)\n\t\tif self.junio_usd != 0:\n\t\t\tvalues.append(self.junio_usd)\n\t\tif self.julio_usd != 0:\n\t\t\tvalues.append(self.julio_usd)\n\t\tif self.agosto_usd != 0:\n\t\t\tvalues.append(self.agosto_usd)\n\t\tif self.septiembre_usd != 0:\n\t\t\tvalues.append(self.septiembre_usd)\n\t\tif self.octubre_usd != 0:\n\t\t\tvalues.append(self.octubre_usd)\n\t\tif self.noviembre_usd != 0:\n\t\t\tvalues.append(self.noviembre_usd)\n\t\tif self.diciembre_usd != 0:\n\t\t\tvalues.append(self.diciembre_usd)\n\t\tif len(values) > 0:\n\t\t\tself.promedio_usd = reduce(lambda x,y:x+y,values)/len(values)\n\t\telse:\n\t\t\tself.promedio_usd = 0\n\tpromedio_usd = fields.Float('Promedio', readonly=True, compute=\"get_promedio_usd\")\n\n\t@api.one\n\tdef get_promedio_pciento_usd(self):\n\t\tif self.acumulado_usd != 0:\n\t\t\tself.promedio_pciento_usd = self.promedio_usd / self.rm_report_extraccion_id.total_promedio_general_usd\n\t\telse:\n\t\t\tself.promedio_pciento_usd = 0\n\tpromedio_pciento_usd = fields.Float('% PROM', readonly=True, compute=\"get_promedio_pciento_usd\")\n\nclass rm_report_extraccion(models.Model):\n\t_inherit= 'rm.report.extraccion'\n\n\t@api.one\n\tdef get_total_general_usd(self):\n\t\tif len(self.conf_line_ids) > 0:\n\t\t\tself.total_general_usd = reduce(lambda x,y:x+y,self.conf_line_ids.mapped('acumulado_usd'))\n\t\telse:\n\t\t\tself.total_general_usd = 0\n\ttotal_general_usd = fields.Float('Total general USD', compute=\"get_total_general_usd\")\n\n\n\t@api.one\n\tdef get_total_promedio_general_usd(self):\n\t\tif len(self.conf_line_ids) > 0:\n\t\t\tself.total_promedio_general_usd = reduce(lambda x,y:x+y,self.conf_line_ids.mapped('promedio_usd'))\n\t\telse:\n\t\t\tself.total_promedio_general_usd = 0\n\ttotal_promedio_general_usd = fields.Float(compute=\"get_total_promedio_general_usd\")\n\n\t\"\"\" ----------------------------- REPORTE EXCEL USD----------------------------- \"\"\"\n\n\t@api.multi\n\tdef export_excel_usd(self):\n\t\timport io\n\t\tfrom xlsxwriter.workbook import Workbook\n\n\t\timport sys\n\t\treload(sys)\n\t\tsys.setdefaultencoding('iso-8859-1')\n\n\t\toutput = io.BytesIO()\n\t\t########### PRIMERA HOJA DE LA DATA EN TABLA\n\t\t#workbook = Workbook(output, {'in_memory': True})\n\n\t\tdireccion = self.env['main.parameter'].search([])[0].dir_create_file\n\t\tif not direccion:\n\t\t\traise osv.except_osv('Alerta!', u\"No fue configurado el directorio para los archivos en Configuracion.\")\n\n\t\tworkbook = Workbook(direccion +'Reporte_Extracción_USD.xlsx')\n\t\tworksheet = workbook.add_worksheet(u\"Extracción\")\n\t\tbold = workbook.add_format({'bold': True})\n\t\tnormal = workbook.add_format()\n\t\tboldbord = workbook.add_format({'bold': True})\n\t\tboldbord.set_border(style=2)\n\t\tboldbord.set_align('center')\n\t\tboldbord.set_align('vcenter')\n\t\tboldbord.set_text_wrap()\n\t\tboldbord.set_font_size(9)\n\t\tboldbord.set_bg_color('#DCE6F1')\n\t\tnumbertres = workbook.add_format({'num_format':'0.000'})\n\t\tnumberdos = workbook.add_format({'num_format':'#,##0.00'})\n\t\tbord = workbook.add_format()\n\t\tbord.set_border(style=1)\n\t\tnumberdos.set_border(style=1)\n\t\tnumbertres.set_border(style=1)\t\n\n\t\tnumberdoscon = workbook.add_format({'num_format':'#,##0.00'})\n\n\t\tboldtotal = workbook.add_format({'bold': True})\n\t\tboldtotal.set_align('right')\n\t\tboldtotal.set_align('vright')\n\n\t\tmerge_format = workbook.add_format({\n\t\t\t\t\t\t\t\t\t\t\t'bold': 1,\n\t\t\t\t\t\t\t\t\t\t\t'border': 1,\n\t\t\t\t\t\t\t\t\t\t\t'align': 'center',\n\t\t\t\t\t\t\t\t\t\t\t'valign': 'vcenter',\n\t\t\t\t\t\t\t\t\t\t\t})\t\n\t\tmerge_format.set_bg_color('#DCE6F1')\n\t\tmerge_format.set_text_wrap()\n\t\tmerge_format.set_font_size(9)\n\n\t\tm = str(self.period_actual.code).split('/')\n\t\tm = int(m[0])\n\t\tdoce = 12\n\n\t\tworksheet.insert_image('C2', 'calidra.jpg')\n\t\tworksheet.write(1,8, u'ANEXO DE OPERACIÓN {0}'.format(self.fiscal.name), bold)\n\t\tworksheet.write(2,8, 'Sitio:', bold)\n\t\tworksheet.write(2,12, self.sitio if self.sitio else '', normal)\n\t\tworksheet.write(3,8, 'Centro de Costo:', bold)\n\t\tworksheet.write(3,12, self.centro_de_costo if self.centro_de_costo else '', normal)\n\t\tworksheet.write(4,8, u'Propósito:', bold)\n\t\tworksheet.write(4,12, self.proposito if self.proposito else '', normal)\n\t\tworksheet.write(5,8, u'Fecha de Emisión del Reporte:', bold)\n\t\tworksheet.write(5,12, self.fecha_emision_reporte if self.fecha_emision_reporte else '', normal)\n\t\tworksheet.write(6,8, 'Usuario:', bold)\n\t\tworksheet.write(6,12, self.usuario.name if self.usuario.name else '', normal)\n\t\tworksheet.write(7,8, 'Moneda:', bold)\n\t\tworksheet.write(7,12,u'Dólares', normal)\n\n\t\tcolum = {\n\t\t\t1: \"Enero\",\n\t\t\t2: \"Febrero\",\n\t\t\t3: \"Marzo\",\n\t\t\t4: \"Abril\",\n\t\t\t5: \"Mayo\",\n\t\t\t6: \"Junio\",\n\t\t\t7: \"Julio\",\n\t\t\t8: \"Agosto\",\n\t\t\t9: \"Septiembre\",\n\t\t\t10: \"Octubre\",\n\t\t\t11: \"Noviembre\",\n\t\t\t12: \"Diciembre\",\n\t\t}\n\n\t\tperiodos = self.env['account.period'].search([('fiscalyear_id','=',self.fiscal.id)])\n\t\tex = self.env['tipo.cambio.mexicano'].search([('periodo_id','in',periodos.ids)])\n\n\t\texchange = {\n\t\t\t1:ex.filtered(lambda x:x.periodo_id.name[:3] == '01/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '01/'))==1 else 1 ,\n\t\t\t2:ex.filtered(lambda x:x.periodo_id.name[:3] == '02/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '02/'))==1 else 1 ,\n\t\t\t3:ex.filtered(lambda x:x.periodo_id.name[:3] == '03/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '03/'))==1 else 1 ,\n\t\t\t4:ex.filtered(lambda x:x.periodo_id.name[:3] == '04/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '04/'))==1 else 1 ,\n\t\t\t5:ex.filtered(lambda x:x.periodo_id.name[:3] == '05/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '05/'))==1 else 1 ,\n\t\t\t6:ex.filtered(lambda x:x.periodo_id.name[:3] == '06/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '06/'))==1 else 1 ,\n\t\t\t7:ex.filtered(lambda x:x.periodo_id.name[:3] == '07/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '07/'))==1 else 1 ,\n\t\t\t8:ex.filtered(lambda x:x.periodo_id.name[:3] == '08/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '08/'))==1 else 1 ,\n\t\t\t9:ex.filtered(lambda x:x.periodo_id.name[:3] == '09/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '09/'))==1 else 1 ,\n\t\t\t10:ex.filtered(lambda x:x.periodo_id.name[:3] == '10/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '10/'))==1 else 1 ,\n\t\t\t11:ex.filtered(lambda x:x.periodo_id.name[:3] == '11/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '11/'))==1 else 1 ,\n\t\t\t12:ex.filtered(lambda x:x.periodo_id.name[:3] == '12/')[0].t_cambio_venta if len(ex.filtered(lambda x:x.periodo_id.name[:3] == '12/'))==1 else 1 ,\n\t\t}\n\t\t\n\t\tworksheet.write(14,0, u'TIPO COSTO', boldbord)\n\t\tcol = 1\n\t\tmon = 0\n\t\twhile mon+1 <= doce:\n\t\t\tworksheet.write(13,col, exchange[mon+1] if exchange[mon+1] > 1 else '', numberdoscon)\n\t\t\tworksheet.write(14,col, u'{0}'.format(colum[mon+1]), boldbord)\n\t\t\tcol += 1\n\t\t\tmon += 1\n\t\tworksheet.write(14,col, u'Acumulado', boldbord)\n\t\tcol+=1\n\t\tworksheet.write(14,col, u'% ACUM', boldbord)\n\t\tcol+=1\n\t\tworksheet.write(14,col, u'Promedio', boldbord)\n\t\tcol+=1\n\t\tworksheet.write(14,col, u'% PROM', boldbord)\n\t\tcol+=1\n\t\t\n\t\telements = self.env['rm.report.extraccion.line'].search([('rm_report_extraccion_id','=',self.id)]).sorted(key=lambda r: dig_5(r.tipo.order)+dig_5(r.grupo.order))\n\t\tflag = True\n\t\tn_grupo = None\n\t\tn_tipo = None\n\t\tultimo_elem = None\n\n\t\tsub_tot = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\t\ttot_tot = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\t\ttot_tot_tot = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\n\t\tx= 15\n\t\tfor i in elements:\n\t\t\tif n_tipo == None:\n\t\t\t\tn_tipo = i.tipo\n\t\t\t\tworksheet.write(x,0, u'{0}'.format(i.tipo.titulo), bold)\n\t\t\t\tx += 1\n\t\t\tif n_grupo == None:\n\t\t\t\tn_grupo = i.grupo\n\t\t\t\tworksheet.write(x,0, u'{0}'.format(i.grupo.titulo), bold)\n\t\t\t\tx += 1\n\t\t\tif n_tipo != i.tipo:\n\t\t\t\tworksheet.write(x,0, u'SUB TOTAL', boldtotal)\n\t\t\t\tcol = 1\n\t\t\t\tmon = 0\n\t\t\t\twhile mon+1 <= doce:\n\t\t\t\t\tworksheet.write(x,col, ((sub_tot[mon])), numberdos)\n\t\t\t\t\tcol += 1\n\t\t\t\t\tmon += 1\n\t\t\t\tworksheet.write(x,col, ((sub_tot[-4])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((sub_tot[-3])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((sub_tot[-2])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((sub_tot[-1])), numberdos)\n\n\t\t\t\ttot_tot[0] += sub_tot[0]\n\t\t\t\ttot_tot[1] += sub_tot[1]\n\t\t\t\ttot_tot[2] += sub_tot[2]\n\t\t\t\ttot_tot[3] += sub_tot[3]\n\t\t\t\ttot_tot[4] += sub_tot[4]\n\t\t\t\ttot_tot[5] += sub_tot[5]\n\t\t\t\ttot_tot[6] += sub_tot[6]\n\t\t\t\ttot_tot[7] += sub_tot[7]\n\t\t\t\ttot_tot[8] += sub_tot[8]\n\t\t\t\ttot_tot[9] += sub_tot[9]\n\t\t\t\ttot_tot[10] += sub_tot[10]\n\t\t\t\ttot_tot[11] += sub_tot[11]\n\t\t\t\ttot_tot[12] += sub_tot[12]\n\t\t\t\ttot_tot[13] += sub_tot[13]\n\t\t\t\ttot_tot[14] += sub_tot[14]\n\t\t\t\ttot_tot[15] += sub_tot[15]\n\t\t\t\ttot_tot_tot[0] += tot_tot[0]\n\t\t\t\ttot_tot_tot[1] += tot_tot[1]\n\t\t\t\ttot_tot_tot[2] += tot_tot[2]\n\t\t\t\ttot_tot_tot[3] += tot_tot[3]\n\t\t\t\ttot_tot_tot[4] += tot_tot[4]\n\t\t\t\ttot_tot_tot[5] += tot_tot[5]\n\t\t\t\ttot_tot_tot[6] += tot_tot[6]\n\t\t\t\ttot_tot_tot[7] += tot_tot[7]\n\t\t\t\ttot_tot_tot[8] += tot_tot[8]\n\t\t\t\ttot_tot_tot[9] += tot_tot[9]\n\t\t\t\ttot_tot_tot[10] += tot_tot[10]\n\t\t\t\ttot_tot_tot[11] += tot_tot[11]\n\t\t\t\ttot_tot_tot[12] += tot_tot[12]\n\t\t\t\ttot_tot_tot[13] += tot_tot[13]\n\t\t\t\ttot_tot_tot[14] += tot_tot[14]\n\t\t\t\ttot_tot_tot[15] += tot_tot[15]\n\n\t\t\t\tx += 1\n\t\t\t\tworksheet.write(x,0, u\"TOTAL \" + n_tipo.titulo.upper(), boldtotal)\n\t\t\t\tcol = 1\n\t\t\t\tmon = 0\n\t\t\t\twhile mon+1 <= doce:\n\t\t\t\t\tworksheet.write(x,col, ((tot_tot[mon])), numberdos)\n\t\t\t\t\tcol += 1\n\t\t\t\t\tmon += 1\n\t\t\t\tworksheet.write(x,col, ((tot_tot[-4])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((tot_tot[-3])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((tot_tot[-2])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((tot_tot[-1])), numberdos)\n\t\t\t\tcol += 1\n\n\t\t\t\tsub_tot = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\t\t\t\ttot_tot = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\n\t\t\t\tx += 1\n\t\t\t\tworksheet.write(x,0, u'{0}'.format(i.tipo.titulo), bold)\n\t\t\t\tx += 1\n\t\t\t\tworksheet.write(x,0, u'{0}'.format(i.grupo.titulo), bold)\n\t\t\t\tx += 1\n\t\t\t\tworksheet.write(x,0, u'{0}'.format(i.concepto), normal)\n\t\t\t\tmon_m = {\n\t\t\t\t\t0: i.enero_usd,\n\t\t\t\t\t1: i.febrero_usd,\n\t\t\t\t\t2: i.marzo_usd,\n\t\t\t\t\t3: i.abril_usd,\n\t\t\t\t\t4: i.mayo_usd,\n\t\t\t\t\t5: i.junio_usd,\n\t\t\t\t\t6: i.julio_usd,\n\t\t\t\t\t7: i.agosto_usd,\n\t\t\t\t\t8: i.septiembre_usd,\n\t\t\t\t\t9: i.octubre_usd,\n\t\t\t\t\t10: i.noviembre_usd,\n\t\t\t\t\t11: i.diciembre_usd,\n\t\t\t\t}\n\t\t\t\tcol = 1\n\t\t\t\tmon = 0\n\t\t\t\twhile mon+1 <= doce:\n\t\t\t\t\tworksheet.write(x,col, ((mon_m[mon])), numberdoscon)\n\t\t\t\t\tcol += 1\n\t\t\t\t\tmon += 1\n\t\t\t\tworksheet.write(x,col, ((i.acumulado_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.acumulado_pciento_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.promedio_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.promedio_pciento_usd)), numberdoscon)\n\n\t\t\t\tsub_tot[0] += i.enero_usd\n\t\t\t\tsub_tot[1] += i.febrero_usd\n\t\t\t\tsub_tot[2] += i.marzo_usd\n\t\t\t\tsub_tot[3] += i.abril_usd\n\t\t\t\tsub_tot[4] += i.mayo_usd\n\t\t\t\tsub_tot[5] += i.junio_usd\n\t\t\t\tsub_tot[6] += i.julio_usd\n\t\t\t\tsub_tot[7] += i.agosto_usd\n\t\t\t\tsub_tot[8] += i.septiembre_usd\n\t\t\t\tsub_tot[9] += i.octubre_usd\n\t\t\t\tsub_tot[10] += i.noviembre_usd\n\t\t\t\tsub_tot[11] += i.diciembre_usd\n\t\t\t\tsub_tot[12] += i.acumulado_usd\n\t\t\t\tsub_tot[13] += i.acumulado_pciento_usd\n\t\t\t\tsub_tot[14] += i.promedio_usd\n\t\t\t\tsub_tot[15] += i.promedio_pciento_usd\n\t\t\t\tx += 1\n\t\t\t\tn_grupo = i.grupo\n\t\t\t\tn_tipo = i.tipo\n\t\t\telif n_grupo != i.grupo:\n\t\t\t\tworksheet.write(x,0, u'SUB TOTAL', boldtotal)\n\t\t\t\tcol = 1\n\t\t\t\tmon = 0\n\t\t\t\twhile mon+1 <= doce:\n\t\t\t\t\tworksheet.write(x,col, ((sub_tot[mon])), numberdos)\n\t\t\t\t\tcol += 1\n\t\t\t\t\tmon += 1\n\t\t\t\tworksheet.write(x,col, ((sub_tot[-4])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((sub_tot[-3])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((sub_tot[-2])), numberdos)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((sub_tot[-1])), numberdos)\n\t\t\t\t\n\t\t\t\ttot_tot[0] += sub_tot[0]\n\t\t\t\ttot_tot[1] += sub_tot[1]\n\t\t\t\ttot_tot[2] += sub_tot[2]\n\t\t\t\ttot_tot[3] += sub_tot[3]\n\t\t\t\ttot_tot[4] += sub_tot[4]\n\t\t\t\ttot_tot[5] += sub_tot[5]\n\t\t\t\ttot_tot[6] += sub_tot[6]\n\t\t\t\ttot_tot[7] += sub_tot[7]\n\t\t\t\ttot_tot[8] += sub_tot[8]\n\t\t\t\ttot_tot[9] += sub_tot[9]\n\t\t\t\ttot_tot[10] += sub_tot[10]\n\t\t\t\ttot_tot[11] += sub_tot[11]\n\t\t\t\ttot_tot[12] += sub_tot[12]\n\t\t\t\ttot_tot[13] += sub_tot[13]\n\t\t\t\ttot_tot[14] += sub_tot[14]\n\t\t\t\ttot_tot[15] += sub_tot[15]\n\t\t\t\tsub_tot = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\t\t\t\tx += 1\n\t\t\t\tworksheet.write(x,0, u'{0}'.format(i.grupo.titulo), bold)\n\t\t\t\tx += 1\n\t\t\t\t\n\t\t\t\tworksheet.write(x,0, u'{0}'.format(i.concepto), normal)\n\t\t\t\tmon_m = {\n\t\t\t\t\t0: i.enero_usd,\n\t\t\t\t\t1: i.febrero_usd,\n\t\t\t\t\t2: i.marzo_usd,\n\t\t\t\t\t3: i.abril_usd,\n\t\t\t\t\t4: i.mayo_usd,\n\t\t\t\t\t5: i.junio_usd,\n\t\t\t\t\t6: i.julio_usd,\n\t\t\t\t\t7: i.agosto_usd,\n\t\t\t\t\t8: i.septiembre_usd,\n\t\t\t\t\t9: i.octubre_usd,\n\t\t\t\t\t10: i.noviembre_usd,\n\t\t\t\t\t11: i.diciembre_usd,\n\t\t\t\t}\n\t\t\t\tcol = 1\n\t\t\t\tmon = 0\n\t\t\t\twhile mon+1 <= doce:\n\t\t\t\t\tworksheet.write(x,col, ((mon_m[mon])), numberdoscon)\n\t\t\t\t\tcol += 1\n\t\t\t\t\tmon += 1\n\t\t\t\tworksheet.write(x,col, ((i.acumulado_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.acumulado_pciento_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.promedio_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.promedio_pciento_usd)), numberdoscon)\n\t\t\t\t\n\t\t\t\tsub_tot[0] += i.enero_usd\n\t\t\t\tsub_tot[1] += i.febrero_usd\n\t\t\t\tsub_tot[2] += i.marzo_usd\n\t\t\t\tsub_tot[3] += i.abril_usd\n\t\t\t\tsub_tot[4] += i.mayo_usd\n\t\t\t\tsub_tot[5] += i.junio_usd\n\t\t\t\tsub_tot[6] += i.julio_usd\n\t\t\t\tsub_tot[7] += i.agosto_usd\n\t\t\t\tsub_tot[8] += i.septiembre_usd\n\t\t\t\tsub_tot[9] += i.octubre_usd\n\t\t\t\tsub_tot[10] += i.noviembre_usd\n\t\t\t\tsub_tot[11] += i.diciembre_usd\n\t\t\t\tsub_tot[12] += i.acumulado_usd\n\t\t\t\tsub_tot[13] += i.acumulado_pciento_usd\n\t\t\t\tsub_tot[14] += i.promedio_usd\n\t\t\t\tsub_tot[15] += i.promedio_pciento_usd\n\t\t\t\tx += 1\n\t\t\t\tn_grupo = i.grupo\n\t\t\telse:\n\t\t\t\t\n\t\t\t\tworksheet.write(x,0, u'{0}'.format(i.concepto), normal)\n\t\t\t\tmon_m = {\n\t\t\t\t\t0: i.enero_usd,\n\t\t\t\t\t1: i.febrero_usd,\n\t\t\t\t\t2: i.marzo_usd,\n\t\t\t\t\t3: i.abril_usd,\n\t\t\t\t\t4: i.mayo_usd,\n\t\t\t\t\t5: i.junio_usd,\n\t\t\t\t\t6: i.julio_usd,\n\t\t\t\t\t7: i.agosto_usd,\n\t\t\t\t\t8: i.septiembre_usd,\n\t\t\t\t\t9: i.octubre_usd,\n\t\t\t\t\t10: i.noviembre_usd,\n\t\t\t\t\t11: i.diciembre_usd,\n\t\t\t\t}\n\t\t\t\tcol = 1\n\t\t\t\tmon = 0\n\t\t\t\twhile mon+1 <= doce:\n\t\t\t\t\tworksheet.write(x,col, ((mon_m[mon])), numberdoscon)\n\t\t\t\t\tcol += 1\n\t\t\t\t\tmon += 1\n\t\t\t\tworksheet.write(x,col, ((i.acumulado_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.acumulado_pciento_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.promedio_usd)), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tworksheet.write(x,col, ((i.promedio_pciento_usd)), numberdoscon)\n\t\t\t\t\n\t\t\t\tsub_tot[0] += i.enero_usd\n\t\t\t\tsub_tot[1] += i.febrero_usd\n\t\t\t\tsub_tot[2] += i.marzo_usd\n\t\t\t\tsub_tot[3] += i.abril_usd\n\t\t\t\tsub_tot[4] += i.mayo_usd\n\t\t\t\tsub_tot[5] += i.junio_usd\n\t\t\t\tsub_tot[6] += i.julio_usd\n\t\t\t\tsub_tot[7] += i.agosto_usd\n\t\t\t\tsub_tot[8] += i.septiembre_usd\n\t\t\t\tsub_tot[9] += i.octubre_usd\n\t\t\t\tsub_tot[10] += i.noviembre_usd\n\t\t\t\tsub_tot[11] += i.diciembre_usd\n\t\t\t\tsub_tot[12] += i.acumulado_usd\n\t\t\t\tsub_tot[13] += i.acumulado_pciento_usd\n\t\t\t\tsub_tot[14] += i.promedio_usd\n\t\t\t\tsub_tot[15] += i.promedio_pciento_usd\n\t\t\t\tx += 1\n\n\t\t\tultimo_elem = i\n\t\t\t\n\t\ttot_tot[0] += sub_tot[0]\n\t\ttot_tot[1] += sub_tot[1]\n\t\ttot_tot[2] += sub_tot[2]\n\t\ttot_tot[3] += sub_tot[3]\n\t\ttot_tot[4] += sub_tot[4]\n\t\ttot_tot[5] += sub_tot[5]\n\t\ttot_tot[6] += sub_tot[6]\n\t\ttot_tot[7] += sub_tot[7]\n\t\ttot_tot[8] += sub_tot[8]\n\t\ttot_tot[9] += sub_tot[9]\n\t\ttot_tot[10] += sub_tot[10]\n\t\ttot_tot[11] += sub_tot[11]\n\t\ttot_tot[12] += sub_tot[12]\n\t\ttot_tot[13] += sub_tot[13]\n\t\ttot_tot[14] += sub_tot[14]\n\t\ttot_tot[15] += sub_tot[15]\n\n\t\ttot_tot_tot[0] += tot_tot[0]\n\t\ttot_tot_tot[1] += tot_tot[1]\n\t\ttot_tot_tot[2] += tot_tot[2]\n\t\ttot_tot_tot[3] += tot_tot[3]\n\t\ttot_tot_tot[4] += tot_tot[4]\n\t\ttot_tot_tot[5] += tot_tot[5]\n\t\ttot_tot_tot[6] += tot_tot[6]\n\t\ttot_tot_tot[7] += tot_tot[7]\n\t\ttot_tot_tot[8] += tot_tot[8]\n\t\ttot_tot_tot[9] += tot_tot[9]\n\t\ttot_tot_tot[10] += tot_tot[10]\n\t\ttot_tot_tot[11] += tot_tot[11]\n\t\ttot_tot_tot[12] += tot_tot[12]\n\t\ttot_tot_tot[13] += tot_tot[13]\n\t\ttot_tot_tot[14] += tot_tot[14]\n\t\ttot_tot_tot[15] += tot_tot[15]\n\n\t\tworksheet.write(x,0, u'SUB TOTAL', boldtotal)\n\t\tcol = 1\n\t\tmon = 0\n\t\twhile mon+1 <= doce:\n\t\t\tworksheet.write(x,col, ((sub_tot[mon])), numberdos)\n\t\t\tcol += 1\n\t\t\tmon += 1\n\t\tworksheet.write(x,col, ((sub_tot[-4])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((sub_tot[-3])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((sub_tot[-2])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((sub_tot[-1])), numberdos)\n\t\tx += 1\n\t\t\n\t\t#lugar del error:\n\t\t#correccion temporal:\n\t\ttitle_tmp = ''\n\t\ttry:\n\t\t\ttitle_tmp = n_tipo.titulo.upper()\n\t\texcept Exception as e:\n\t\t\tprint('Error: ',e)\n\t\t#title_tmp = n_tipo.titulo.upper() if n_tipo.titulo else ''\n\t\tworksheet.write(x,0, u\"TOTAL \" + title_tmp, boldtotal)\n\n\t\tcol = 1\n\t\tmon = 0\n\t\twhile mon+1 <= doce:\n\t\t\tworksheet.write(x,col, ((tot_tot[mon])), numberdos)\n\t\t\tcol += 1\n\t\t\tmon += 1\n\t\tworksheet.write(x,col, ((tot_tot[-4])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((tot_tot[-3])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((tot_tot[-2])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((tot_tot[-1])), numberdos)\n\t\tcol += 1\n\t\tx += 1\n\n\t\tworksheet.write(x,0, u\"COSTO TOTAL DEL PROCESO\", boldtotal)\n\t\tcol = 1\n\t\tmon = 0\n\t\twhile mon+1 <= doce:\n\t\t\tworksheet.write(x,col, ((tot_tot_tot[mon])), numberdos)\n\t\t\tcol += 1\n\t\t\tmon += 1\n\t\tworksheet.write(x,col, ((tot_tot_tot[-4])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((tot_tot_tot[-3])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((tot_tot_tot[-2])), numberdos)\n\t\tcol += 1\n\t\tworksheet.write(x,col, ((tot_tot_tot[-1])), numberdos)\n\t\tcol += 1\n\t\tx += 1\n\n\t\tt = 11.86\n\t\tworksheet.set_column('A:A', 49)\n\t\tworksheet.set_column('B:B', t)\n\t\tworksheet.set_column('C:C', t)\n\t\tworksheet.set_column('D:D', t)\n\t\tworksheet.set_column('E:E', t)\n\t\tworksheet.set_column('F:F', t)\n\t\tworksheet.set_column('G:G', t)\n\t\tworksheet.set_column('H:H', t)\n\t\tworksheet.set_column('I:I', t)\n\t\tworksheet.set_column('J:J', t)\n\t\tworksheet.set_column('K:K', t)\n\t\tworksheet.set_column('L:L', t)\n\t\tworksheet.set_column('M:M', t)\n\t\tworksheet.set_column('N:N', t)\n\t\tworksheet.set_column('O:O', t)\n\t\tworksheet.set_column('P:P', t)\n\t\tworksheet.set_column('Q:Q', t)\n\n\n\t\tx += 2\n\t\tworksheet.write(x,0, u'Otros datos Informativos'.format(i.tipo.titulo), bold)\n\t\tx += 1\n\n\t\tnombres = [\"TONELADAS PRODUCIDAS\",\"COSTO PROCESO POR TONELADA\", \"COSTO POR TONELADA SIN EXPLOSIVOS\", \"COSTO DE EXPLOSIVOS\", \"COSTO LABORATORIO POR TON.\", u\"COSTO POR TON. SIN DEPRECIACIÓN\"]\n\t\tvalores = [[0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0]]\n\t\tvalores = self.get_valores()[0]\n\t\tfor k in range(12):\n\t\t\tif valores[0][k] == 0:\n\t\t\t\tvalores[1][k] = 0\n\t\t\t\tvalores[2][k] = 0\n\t\t\t\tvalores[3][k] = 0\n\t\t\t\tvalores[4][k] = 0\n\t\t\t\tvalores[5][k] = 0\n\t\t\telse:\n\t\t\t\texplosivo = self.env['rm.report.extraccion.line'].search( [('rm_report_extraccion_id','=',self.id),('pie_pagina','=','explosivo')] )\n\t\t\t\texplosivo_val = 0\n\t\t\t\tif len(explosivo) >0:\n\t\t\t\t\texplosivo = explosivo[0]\n\t\t\t\t\tif k == 0:\n\t\t\t\t\t\texplosivo_val = explosivo.enero_usd\n\t\t\t\t\telif k== 1:\n\t\t\t\t\t\texplosivo_val = explosivo.febrero_usd\n\t\t\t\t\telif k== 2:\n\t\t\t\t\t\texplosivo_val = explosivo.marzo_usd\n\t\t\t\t\telif k== 3:\n\t\t\t\t\t\texplosivo_val = explosivo.abril_usd\n\t\t\t\t\telif k== 4:\n\t\t\t\t\t\texplosivo_val = explosivo.mayo_usd\n\t\t\t\t\telif k== 5:\n\t\t\t\t\t\texplosivo_val = explosivo.junio_usd\n\t\t\t\t\telif k== 6:\n\t\t\t\t\t\texplosivo_val = explosivo.julio_usd\n\t\t\t\t\telif k== 7:\n\t\t\t\t\t\texplosivo_val = explosivo.agosto_usd\n\t\t\t\t\telif k== 8:\n\t\t\t\t\t\texplosivo_val = explosivo.septiembre_usd\n\t\t\t\t\telif k== 9:\n\t\t\t\t\t\texplosivo_val = explosivo.octubre_usd\n\t\t\t\t\telif k== 10:\n\t\t\t\t\t\texplosivo_val = explosivo.noviembre_usd\n\t\t\t\t\telif k== 11:\n\t\t\t\t\t\texplosivo_val = explosivo.diciembre_usd\n\n\n\t\t\t\tlaboratorio = self.env['rm.report.extraccion.line'].search( [('rm_report_extraccion_id','=',self.id),('pie_pagina','=','laboratorio')] )\n\t\t\t\tlaboratorio_val = 0\n\t\t\t\tif len(laboratorio) >0:\n\t\t\t\t\tlaboratorio = laboratorio[0]\n\t\t\t\t\tif k == 0:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.enero_usd\n\t\t\t\t\telif k== 1:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.febrero_usd\n\t\t\t\t\telif k== 2:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.marzo_usd\n\t\t\t\t\telif k== 3:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.abril_usd\n\t\t\t\t\telif k== 4:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.mayo_usd\n\t\t\t\t\telif k== 5:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.junio_usd\n\t\t\t\t\telif k== 6:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.julio_usd\n\t\t\t\t\telif k== 7:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.agosto_usd\n\t\t\t\t\telif k== 8:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.septiembre_usd\n\t\t\t\t\telif k== 9:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.octubre_usd\n\t\t\t\t\telif k== 10:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.noviembre_usd\n\t\t\t\t\telif k== 11:\n\t\t\t\t\t\tlaboratorio_val = laboratorio.diciembre_usd\n\n\n\t\t\t\tdepreciacion = self.env['rm.report.extraccion.line'].search( [('rm_report_extraccion_id','=',self.id),('pie_pagina','=','depreciacion')] )\n\t\t\t\tdepreciacion_val = 0\n\t\t\t\tfor dep in depreciacion:\n\t\t\t\t\tif k == 0:\n\t\t\t\t\t\tdepreciacion_val += dep.enero_usd\n\t\t\t\t\telif k== 1:\n\t\t\t\t\t\tdepreciacion_val += dep.febrero_usd\n\t\t\t\t\telif k== 2:\n\t\t\t\t\t\tdepreciacion_val += dep.marzo_usd\n\t\t\t\t\telif k== 3:\n\t\t\t\t\t\tdepreciacion_val += dep.abril_usd\n\t\t\t\t\telif k== 4:\n\t\t\t\t\t\tdepreciacion_val += dep.mayo_usd\n\t\t\t\t\telif k== 5:\n\t\t\t\t\t\tdepreciacion_val += dep.junio_usd\n\t\t\t\t\telif k== 6:\n\t\t\t\t\t\tdepreciacion_val += dep.julio_usd\n\t\t\t\t\telif k== 7:\n\t\t\t\t\t\tdepreciacion_val += dep.agosto_usd\n\t\t\t\t\telif k== 8:\n\t\t\t\t\t\tdepreciacion_val += dep.septiembre_usd\n\t\t\t\t\telif k== 9:\n\t\t\t\t\t\tdepreciacion_val += dep.octubre_usd\n\t\t\t\t\telif k== 10:\n\t\t\t\t\t\tdepreciacion_val += dep.noviembre_usd\n\t\t\t\t\telif k== 11:\n\t\t\t\t\t\tdepreciacion_val += dep.diciembre_usd\n\n\t\t\t\tvalores[1][k] = tot_tot_tot[k] / valores[0][k]\n\t\t\t\tvalores[2][k] = (tot_tot_tot[k] - explosivo_val )/valores[0][k]\n\t\t\t\tvalores[3][k] = explosivo_val / valores[0][k]\n\t\t\t\tvalores[4][k] = laboratorio_val / valores[0][k]\n\t\t\t\tvalores[5][k] = (tot_tot_tot[k] - (depreciacion_val))/valores[0][k]\n\n\t\t\n\t\tworksheet.write(x,0, u'CONCEPTO', boldbord)\n\t\tcol = 1\n\t\tmon = 0\n\t\twhile mon+1 <= doce:\n\t\t\tworksheet.write(x,col, u'{0}'.format(colum[mon+1]), boldbord)\n\t\t\tcol += 1\n\t\t\tmon += 1\n\n\t\tx += 1\n\n\n\t\tfor i in range(0,6):\n\t\t\tworksheet.write(x,0, u'{0}'.format(nombres[i]), normal)\n\t\t\tcol = 1\n\t\t\tmon = 0\n\t\t\twhile mon+1 <= doce:\n\t\t\t\tworksheet.write(x,col, ((valores[i][mon])), numberdoscon)\n\t\t\t\tcol += 1\n\t\t\t\tmon += 1\n\t\t\tx += 1\n\n\t\tx += 2\n\t\tworksheet.write(x,0, u'Pie de Página', bold)\n\t\tx += 1\n\t\tworksheet.merge_range(x,0,x+1,0, u'CONCEPTO', merge_format)\n\t\tworksheet.merge_range(x,1,x,3, u'MES ACTUAL', merge_format)\n\t\tworksheet.merge_range(x,4,x,6, u'ACUMULADO', merge_format)\n\t\tworksheet.write(x,7, u'TCVP', boldbord)\n\t\tx += 1\n\t\tworksheet.write(x,1, u'TONS', boldbord)\n\t\tworksheet.write(x,2, u'PROMEDIO', boldbord)\n\t\tworksheet.write(x,3, u'IMPORTE', boldbord)\n\t\tworksheet.write(x,4, u'TONS', boldbord)\n\t\tworksheet.write(x,5, u'PROMEDIO', boldbord)\n\t\tworksheet.write(x,6, u'IMPORTE', boldbord)\n\t\ttcvp = self.env['tipo.cambio.mexicano'].search([('periodo_id','=',self.period_actual.id)])\n\t\tif len(tcvp) != 1:\n\t\t\traise exceptions.Warning('No se ha encontrado el tipo de cambio promedio para el periodo: '\n\t\t\t\t+str(self.period_actual.name)+ '\\n o el T.C. para dicho periodo esta duplicado')\n\t\ttcvp = tcvp[0].promedio_venta if tcvp[0].promedio_venta > 0 else 1\n\t\tworksheet.write(x,7,tcvp , numberdoscon)\n\t\tx += 1\n\n\t\tnombres = [\"TRASPASO PROCESO ANTERIOR\",\"PRODUCCION COSTO POR TONELADA\",\"INVENTARIO INICIAL\",\"COMPRAS\",\"DISPONIBLE\",\"ENVIO TR\",\"TRASPASO A TRITURACION\",\"TRASPASO A AGREGADOS\",\"VENTAS\",\"AJUSTE DE INVENTARIO\",\"OTRAS SALIDAS\",\"INVENTARIO FINAL\"]\n\t\t\n\t\tdata_final_pagina = self.get_pie_pagina()[0]\n\t\t#print \"esto es lo raro\",data_final_pagina\n\n\t\tfor i in range(12):\n\t\t\tworksheet.write(x,0, nombres[i], normal)\n\t\t\tworksheet.write(x,1, (data_final_pagina[i][0]), numberdoscon)\n\t\t\tworksheet.write(x,2, ((data_final_pagina[i][1]))/tcvp, numberdoscon)\n\t\t\tworksheet.write(x,3, ((data_final_pagina[i][2]))/tcvp, numberdoscon)\n\t\t\tworksheet.write(x,4, ((data_final_pagina[i][3])), numberdoscon)\n\t\t\tworksheet.write(x,5, ((data_final_pagina[i][4]))/tcvp, numberdoscon)\n\t\t\tworksheet.write(x,6, ((data_final_pagina[i][5]))/tcvp, numberdoscon)\n\t\t\tx += 1\n\n\t\tworkbook.close()\n\t\t\n\t\tf = open(direccion + 'Reporte_Extracción_USD.xlsx', 'rb')\n\t\t\n\t\tvals = {\n\t\t\t'output_name': 'Reportes_Mexicanos_Extrracción_USD.xlsx',\n\t\t\t'output_file': base64.encodestring(''.join(f.readlines())),\t\t\n\t\t}\n\n\t\tsfs_id = self.env['export.file.save'].create(vals)\n\t\treturn {\n\t\t\t\"type\": \"ir.actions.act_window\",\n\t\t\t\"res_model\": \"export.file.save\",\n\t\t\t\"views\": [[False, \"form\"]],\n\t\t\t\"res_id\": sfs_id.id,\n\t\t\t\"target\": \"new\",\n\t\t}\n\n\t\"\"\" ----------------------------- REPORTE EXCEL ----------------------------- \"\"\"\n","sub_path":"calquipa_reportemexicanos_parte1_it/reporte_mexicano_extraccion_usd.py","file_name":"reporte_mexicano_extraccion_usd.py","file_ext":"py","file_size_in_byte":32747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"225908810","text":"# encoding:utf-8\nimport logging\nfrom logging.handlers import SMTPHandler\n\nimport os\nimport datetime\nimport flask\nfrom flask import Flask, url_for, request, jsonify, redirect, render_template\nfrom flask_user import current_user\nfrom flask_user import login_required, UserManager, UserMixin, SQLAlchemyAdapter\nfrom flask_mail import Mail\nfrom flask.ext.user import roles_required\n\nfrom ..database import User\nimport config\n\ntry:\n THIS_PATH = os.path.dirname(os.path.abspath(__file__))\nexcept NameError:\n THIS_PATH = os.getcwd()\n\n\ndef init_app(app, db, extra_config_settings={}):\n \"\"\" Flask application factory \"\"\"\n \n # Setup Flask app and app.config\n app.config.from_object(config.ConfigClass)\n\n filename = extra_config_settings.get(\"filename\")\n if filename:\n init_logger_with_file_handler(app, filename)\n\n # Initialize Flask extensions\n mail = Mail(app) # Initialize Flask-Mail\n init_error_logger_with_email_handler(app)\n\n # Create all database tables\n db.create_all()\n\n # Setup Flask-User\n db_adapter = SQLAlchemyAdapter(db, User) # Register the User model\n user_manager = UserManager(db_adapter, app) # Initialize Flask-User\n\n from reporto.view import home_view\n from reporto.view import global_view\n\n return app\n\n\ndef init_error_logger_with_email_handler(app):\n \"\"\"\n Initialize a logger to send emails on error-level messages.\n Unhandled exceptions will now send an email message to app.config.ADMINS.\n \"\"\"\n if app.debug: return # Do not send error emails while developing\n\n # Retrieve email settings from app.config\n host = app.config['MAIL_SERVER']\n port = app.config['MAIL_PORT']\n from_addr = app.config['MAIL_DEFAULT_SENDER']\n username = app.config['MAIL_USERNAME']\n password = app.config['MAIL_PASSWORD']\n secure = () if app.config.get('MAIL_USE_TLS') else None\n\n # Retrieve app settings from app.config\n to_addr_list = app.config['ADMINS']\n subject = app.config.get('APP_SYSTEM_ERROR_SUBJECT_LINE', 'System Error')\n\n # Setup an SMTP mail handler for error-level messages\n mail_handler = SMTPHandler(\n mailhost=(host, port), # Mail host and port\n fromaddr=from_addr, # From address\n toaddrs=to_addr_list, # To address\n subject=subject, # Subject line\n credentials=(username, password), # Credentials\n secure=secure,\n )\n mail_handler.setLevel(logging.ERROR)\n app.logger.addHandler(mail_handler)\n\n # Log errors using: app.logger.error('Some error message')\n #\n\n\ndef init_logger_with_file_handler(app, filename):\n import logging\n file_handler = logging.FileHandler(filename)\n file_handler.setLevel(logging.INFO)\n\n file_handler.setFormatter(logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s '\n '[in %(module)s:%(funcName)s]'\n ))\n\n app.logger.addHandler(file_handler)\n","sub_path":"reporto/startup/init_app.py","file_name":"init_app.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"373498016","text":"from django.http import JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.decorators.http import require_POST\n\nfrom inventory.forms import ItemForm, AccountForm\nfrom inventory.models import Item, Account\n\n\ndef item_list(request):\n items = Item.objects.all()\n ctx = {\n \"items\": items\n }\n return render(request, \"inventory/item_list.html\", ctx)\n\n\n@require_POST\ndef amount_ajax(request):\n pk = request.POST.get(\"pk\")\n status = request.POST.get(\"status\")\n item = get_object_or_404(Item, pk=pk)\n\n if status == \"plus\":\n item.amount += 1\n else:\n if item.amount > 0:\n item.amount -= 1\n else:\n redirect('item_list')\n item.save()\n ctx = {\n \"amount\": item.amount,\n }\n return JsonResponse(ctx)\n\n\ndef item_read(request, pk):\n item = Item.objects.get(pk=pk)\n ctx = {\n \"item\": item\n }\n return render(request, \"inventory/item_read.html\", ctx)\n\n\ndef item_create(request):\n if request.method == \"POST\":\n form = ItemForm(request.POST, request.FILES)\n if form.is_valid():\n item = form.save()\n return redirect(\"item_read\", item.pk)\n else:\n form = ItemForm()\n ctx = {\n \"form\": form\n }\n return render(request, \"inventory/item_create.html\", ctx)\n\n\ndef item_update(request, pk):\n item = Item.objects.get(pk=pk)\n\n if request.method == \"POST\":\n form = ItemForm(request.POST, request.FILES, instance=item)\n if form.is_valid():\n item = form.save()\n return redirect(\"item_read\", item.pk)\n\n else:\n form = ItemForm(instance=item)\n ctx = {\n \"form\": form\n }\n return render(request, \"inventory/item_update.html\", ctx)\n\n\ndef item_delete(request, pk):\n item = Item.objects.get(pk=pk)\n\n if request.method == \"POST\":\n item.delete()\n return redirect(\"item_list\")\n\n return redirect(\"item_read\", item.pk)\n\ndef account_list(request):\n accounts = Account.objects.all()\n ctx = {\n \"accounts\": accounts\n }\n return render(request, \"inventory/account_list.html\", ctx)\n\n\ndef account_read(request, pk):\n account = Account.objects.get(pk=pk)\n ctx = {\n \"account\": account\n }\n return render(request, \"inventory/account_read.html\", ctx)\n\n\ndef account_create(request):\n if request.method == \"POST\":\n form = AccountForm(request.POST)\n if form.is_valid():\n account = form.save()\n return redirect(\"account_read\", account.pk)\n else:\n form = AccountForm()\n ctx = {\n \"form\": form\n }\n return render(request, \"inventory/account_create.html\", ctx)\n\n\ndef account_update(request, pk):\n account = Account.objects.get(pk=pk)\n\n if request.method == \"POST\":\n form = AccountForm(request.POST, instance=account)\n if form.is_valid():\n account = form.save()\n return redirect(\"account_read\", account.pk)\n\n else:\n form = AccountForm(instance=account)\n ctx = {\n \"form\": form\n }\n return render(request, \"inventory/account_update.html\", ctx)\n\n\ndef account_delete(request, pk):\n account = Account.objects.get(pk=pk)\n\n if request.method == \"POST\":\n account.delete()\n return redirect(\"account_list\")\n\n return redirect(\"account_read\", account.pk)","sub_path":"inventory/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232278825","text":"#!/usr/bin/env python\r\n# coding:utf-8\r\n\r\nimport random, math\r\nimport numpy as np\r\n\r\n\r\ndef rotate(x, y ,rad):\r\n _x = np.cos(rad)*x - np.sin(rad)*y\r\n _y = np.sin(rad)*x + np.cos(rad)*y\r\n return _x, _y\r\n\r\ndef random_rotate(img, bboxes):\r\n ### random rotate value\r\n i = np.random.randint(4)\r\n\r\n ### rotate image\r\n _, H, W = img.shape\r\n img = np.transpose(img, axes=(1, 2, 0))\r\n img = np.rot90(img, i)\r\n img = np.transpose(img, axes=(2, 0, 1))\r\n\r\n ### rotate bounding boxes\r\n degree = 90 * i\r\n new_bboxes = []\r\n for bbox in bboxes:\r\n x1, y1, x2, y2 = bbox[0]-(H/2.0), bbox[1]-(W/2.0), bbox[2]-(H/2.0), bbox[3]-(W/2.0)\r\n x1, y1 = rotate(x1, y1, math.radians(degree))\r\n x2, y2 = rotate(x2, y2, math.radians(degree))\r\n x1 += H/2.0\r\n y1 += W/2.0\r\n x2 += H/2.0\r\n y2 += W/2.0\r\n new_bbox = [min(x1,x2), min(y1,y2), max(x1,x2), max(y1,y2)]\r\n new_bboxes.append(new_bbox)\r\n bboxes = np.asarray(new_bboxes)\r\n\r\n return img, bboxes\r\n\r\n","sub_path":"chainer/ssd_withRotate_Score/lib/argments/rotate.py","file_name":"rotate.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"431835681","text":"import re\ntokens = []\ndatatypes = [\"int\", \"double\", \"float\"]\narithmetic = ['+', '-', '*', '/']\nconditional = ['==', '!=', '>=', '<=']\nreserve = ['return', 'main', 'break', 'void', '#include', 'include', 'stdio.h', '<stdio.h>', 'scanf', 'printf', 'if', 'else', 'elif']\n\nfilename = input(\"enter file path: \")\nfile = open(filename,'rb')\ncontent = \"\"\nfor line in file:\n content+=str(line).rstrip()\n\nstr_content = str(content)\n\ncurlSet = []\nState = []\n\n\n\ndef paren(str_content):\n \n lastOP = 0\n firstCP = 0\n idx = 0\n\n for i in str_content:\n \n if i == '(':\n lastOP = idx\n elif i == ')':\n firstCP = idx\n break\n idx+=1\n inpar = str_content[lastOP:firstCP+1]\n for i in conditional:\n if i in inpar:\n tokens.append( '<CONDITION: '+ i + \",\" +inpar.replace(i,',').replace('(','').replace(')','')+\">\")\n return str_content.replace(inpar,'<CONDITION: '+ i + \",\" +inpar.replace(i,',').replace('(','').replace(')','')+\">\")\n else:\n pass\n if '\"' in inpar:\n tokens.append( '<STRING:'+inpar.replace('(','').replace(')',''))\n return str_content.replace(inpar,'<STRING:'+inpar.replace('(','').replace(')','')+\">\")\n else:\n tokens.append( '<parameters/arguments>:'+inpar.replace('(','').replace(')',''))\n return str_content.replace(inpar,'<parameters/arguments:'+inpar.replace('(','').replace(')','')+\">\")\n\n\ndef execute(str_content):\n lastopenCurl = 0\n firstcloseCurl = 0\n \n idx = 0\n for i in str_content:\n if i == '{':\n lastopenCurl = idx\n elif i == '}':\n firstcloseCurl = idx\n break\n idx+=1\n\n\n substring = str_content[lastopenCurl:firstcloseCurl+1]\n inside = substring.replace('{','').replace('}','')\n x = inside.strip().split(';')\n # print \"<<<\"+str(x)+\">>>\"\n for i in x:\n # print i\n if '==' in i:\n pass\n elif '+=' in i:\n tokens.append(\"<INCREMENT: +=, \"+ i.replace('+=',',')+\">\")\n inside = i.replace(i , \"<INCREMENT: +=, \"+ i.replace('+=',',')+\">\")\n \n elif '=' in i:\n tokens.append(\"<ASSIGNMENT: =, \"+ i.replace('=',',')+\">\")\n inside = inside.replace(i , \"<ASSIGNMENT: =, \"+ i.replace('=',',')+\">\")\n \n for ins in inside.split():\n\n if '+=' in inside:\n pass\n elif '+' in ins:\n tokens.append(\"<ARITHMETIC: +, \"+ ins.replace('+',',').replace(';',''))\n inside = inside.replace( ins, \"<ARITHMETIC: +, \"+ ins.replace('+',',')+\">\")\n elif '=' in ins:\n pass\n elif '+' in i:\n tokens.append(\"<ARITHMETIC: +, \"+ i.replace('+',',')+\">\")\n inside = i.replace(i , \"<ARITHMETIC: +, \"+ i.replace('+',',')+\">\")\n \n \n \n\n # for j in datatypes:\n # if j in i:\n # if 'printf' in i:\n # pass\n # else:\n # stack_of_events.append(i)\n # inside = inside.replace(i,\"<datatypes:\"+i+\">\")\n\n # for j in reserve:\n # if j in i:\n # inside = inside.replace(i,\"<reserve:\"+i+\">\")\n # print inside\n return str_content.replace(substring,inside)\n \n\n\n\nwhile '(' in str_content:\n str_content = paren(str_content)\n# print str_content\nwhile '{' in str_content:\n str_content = execute(str_content)\nfor i in tokens:\n print (i)\nprint(\"---------------------------------------------------------------------------------\" )\nprint (str_content)\n\n# for i in stack_of_events:\n# print i\n# print str_content\n# print(\"\\n\\nSET OF CURLYTOPS\")\n# print(\"-------------------------------------------------------------------------------------------\")\n# for i in curlSet:\n# print i\n# print(\"-------------------------------------------------------------------------------------------\")\n# print(\"\\n\\nSET OF STATES\")\n# print(\"___________________________________________________________________________________________\")\n# for i in State:\n# print i\n# print(\"___________________________________________________________________________________________\")","sub_path":"prev_codes/prev assignments/asignment2.py","file_name":"asignment2.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"23281452","text":"from selenium import webdriver\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nimport urllib.request\r\nimport os\r\nimport driver as driver\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver as wd\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nimport time\r\nimport re\r\nimport csv\r\n\r\ndriver = wd.Chrome('../webdriver/chromedriver.exe')\r\n\r\ndriver.get('https://www.instagram.com/accounts/login/?source=auth_switcher')\r\n\r\ntime.sleep(3) #웹 페이지 로드를 보장하기 위해 3초 쉬기\r\n\r\n#\r\n\r\nid = 'gg__heon'\r\npassword = 'Derek2020@'\r\nid_input = driver.find_elements_by_css_selector('#react-root > section > main > div > article > div > div > div > form > div > div > label > input')[0]\r\nid_input.send_keys(id)\r\npassword_input = driver.find_elements_by_css_selector('#react-root > section > main > div > article > div > div > div > form > div > div > label > input')[1]\r\npassword_input.send_keys(password)\r\npassword_input.submit()\r\n\r\ntime.sleep(5)\r\n\r\n#\r\n\r\ndriver.get('https://www.instagram.com/explore/tags/배달의민족')\r\n\r\ntime.sleep(5)\r\n\r\ninstagram_tags = []\r\ninstagram_tag_dates = []\r\n\r\n#driver = wd.Chrome(\"../webdriver/chromedriver.exe\")\r\n#driver.get(url)\r\ntime.sleep(5)\r\n#태그 디렉 크롤링\r\n\r\ndriver.find_element_by_css_selector('div.v1Nh3.kIKUG._bz0w').click()\r\n\r\nfor i in range(2000):\r\n time.sleep(1)\r\n try:\r\n data = driver.find_element_by_css_selector('.C7I1f.X7jCj') # C7I1f X7jCj\r\n tag_raw = data.text\r\n tags = re.findall('#[A-Za-z0-9가-힣]+', tag_raw)\r\n tag = ''.join(tags).replace(\"#\",\" \") # \"#\" 제거\r\n\r\n tag_data = tag.split()\r\n\r\n for tag_one in tag_data:\r\n instagram_tags.append(tag_one)\r\n print(instagram_tags)\r\n\r\n date = driver.find_element_by_css_selector(\"time.FH9sR.Nzb55\").text # 날짜 선택\r\n\r\n if date.find('시간') != -1 or date.find('일') != -1 or date.find('분') != -1:\r\n instagram_tag_dates.append('0주')\r\n else:\r\n instagram_tag_dates.append(date)\r\n print(instagram_tag_dates)\r\n except:\r\n instagram_tags.append(\"error\")\r\n instagram_tag_dates.append('error')\r\n try:\r\n print('--count :', i)\r\n WebDriverWait(driver, 100).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a._65Bje.coreSpriteRightPaginationArrow')))\r\n driver.find_element_by_css_selector('a._65Bje.coreSpriteRightPaginationArrow').click()\r\n print(len(instagram_tags))\r\n except:\r\n\r\n f = open('배달의민족_키워드_크롤링.txt', 'w', encoding='utf-8', newline='')\r\n z = open('배달의민족_키워드_주별언급.txt', 'w', encoding='utf-8', newline='')\r\n\r\n # 크롤링 태그 키워드 저장\r\n for x in instagram_tags:\r\n tags = x\r\n f.write(str(tags) + '\\n')\r\n f.close()\r\n # 크롤링 날짜 저장\r\n for o in instagram_tag_dates:\r\n dates = o\r\n z.write(str(dates) + '\\n')\r\n z.close()\r\n driver.close()\r\n # date = datum2.text\r\n # #print(date)\r\n time.sleep(3)\r\n\r\nprint('----마지막전---')\r\nprint(instagram_tag_dates)\r\nprint(instagram_tags)\r\n\r\nf = open('배달의민족_키워드_크롤링.txt', 'w', encoding='utf-8', newline='')\r\nz = open('배달의민족_키워드_주별언급.txt', 'w', encoding='utf-8', newline='')\r\n\r\n#크롤링 태그 키워드 저장\r\nfor x in instagram_tags:\r\n tags = x\r\n f.write(str(tags) + '\\n')\r\nf.close()\r\n#크롤링 날짜 저장\r\nfor o in instagram_tag_dates:\r\n dates = o\r\n z.write(str(dates) + '\\n')\r\nz.close()\r\ndriver.close()\r\n# csvWriter = csv.writer(f)\r\n# for i in instagram_tags:\r\n# csvWriter.writerow(i)\r\n# for z in instagram_tag_dates:\r\n# csvWriter.writerow(z)\r\n# f.close()\r\n# z.close()\r\n","sub_path":"요기요_태그크롤링_페이지네이션수정.py","file_name":"요기요_태그크롤링_페이지네이션수정.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"108484852","text":"import logging\r\nimport os\r\nimport sys\r\nimport multiprocessing\r\nimport numpy as np\r\nfrom gensim.models import Word2Vec\r\nfrom sklearn.utils import check_random_state\r\n\r\n#################### config ###################\r\nmodelfile = \"../wvmodel/size300window5sg1min_count100negative10iter50.model\"\r\nquestionfile = \"../wvmodel/questions-words-Zh.txt\"\r\n############### end of config #################\r\n\r\nlogger = logging.getLogger()\r\nlogging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')\r\nlogging.root.setLevel(level=logging.INFO)\r\nlogger.info(\"running test word2vec for model: %s\" % modelfile)\r\n\r\n\r\nclass Word2VecHelper(object):\r\n \"\"\"\r\n import word2vec from gensim\r\n \"\"\"\r\n def __init__(self, test_model=False, verify_model=True):\r\n model = Word2Vec.load(modelfile)\r\n\r\n if(test_model):\r\n acc = model.accuracy(questionfile)\r\n logger.info(\"Test model \" + modelfile + \" in \" + questionfile)\r\n\r\n self.vector_size = model.vector_size\r\n self.vocab_size = len(model.wv.vocab) + 1\r\n self.word2index = self.GetWord2Index(model)\r\n self.index2word = self.GetIndex2Word(model)\r\n self.wordvector = self.GetWordVector(model)\r\n\r\n if(verify_model):\r\n logger.info(\"Verifing imported word2vec model\")\r\n random_state = check_random_state(12)\r\n check_index = random_state.randint(low=0, high=self.vocab_size-2,size=1000)\r\n for index in check_index:\r\n word_wv = model.wv.index2word[index]\r\n word_our = self.index2word[index+1]\r\n #print(index, word_wv, word_our)\r\n assert word_wv == word_our\r\n assert model.wv.vocab[word_our].index == self.word2index[word_our] - 1\r\n assert np.array_equal(model.wv[word_our], self.wordvector[self.word2index[word_our]])\r\n logger.info(\"Imported word2vec model is verified\")\r\n\r\n def GetWord2Index(self, model):\r\n word2index = {}\r\n word2index[\"UNK\"] = 0\r\n for key, value in model.wv.vocab.items():\r\n word2index[key] = value.index + 1\r\n\r\n if(len(word2index) != self.vocab_size):\r\n logger.error(\"Get word2index error\")\r\n return None\r\n logger.info(\"Got Word2Index\")\r\n return word2index\r\n\r\n def GetIndex2Word(self, model):\r\n index2word = [\"UNK\"] + model.wv.index2word\r\n\r\n if(len(index2word) != self.vocab_size):\r\n logger.error(\"Get index2word error\")\r\n return None\r\n logger.info(\"Got Index2Word\")\r\n return index2word\r\n\r\n def GetWordVector(self, model):\r\n wordvector = np.zeros((self.vocab_size, self.vector_size))\r\n wordvector[0] = np.zeros((self.vector_size))\r\n count = 0\r\n for word in model.wv.index2word:\r\n wordvector[count + 1] = model.wv[word]\r\n count = count + 1\r\n\r\n if(len(wordvector) != self.vocab_size):\r\n logger.error(\"Get WordVector error\")\r\n return None\r\n logger.info(\"Got WordVector\")\r\n return wordvector\r\n\r\n def SentencesIndex(self, sentences, max_document_length):\r\n # indexed_sentences = np.zeros((len(sentences), max_document_length), np.int64)\r\n # for count, sentence in enumerate(sentences):\r\n # sentence_split = sentence.split()\r\n # for index, word in enumerate(sentence_split):\r\n # if word in self.word2index:\r\n # indexed_sentences[count][index] = (self.word2index[word])\r\n # else:\r\n # indexed_sentences[count][index] = 0\r\n indexed_sentences = np.array(\r\n [[self.word2index[word] for word in sentence.split() if word in self.word2index ] for sentence in sentences]\r\n )\r\n logger.info(\"{} Sentences have been indexed\".format(len(indexed_sentences)))\r\n indexed_sentences = np.array([x[:max_document_length - 1] + [0] * max(max_document_length - len(x), 1) for x in indexed_sentences])\r\n return indexed_sentences\r\n \r\nif __name__ == '__main__':\r\n model = Word2Vec.load(modelfile)\r\n word2vec_helpers = Word2VecHelper()\r\n","sub_path":"rnn_src/word2vec_helpers.py","file_name":"word2vec_helpers.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"451469751","text":"import fileinput\n\ndef cycle(list):\n while True:\n yield from list\n\nseen = set([0])\nfrequency = 0\nchanges = cycle(list(fileinput.input()))\n\nfor line in changes:\n try:\n frequency = frequency + int(line)\n if frequency in seen:\n break\n else:\n seen.add(frequency)\n except ValueError:\n print(\"Invalid number: {}\".format(line))\n\nprint(\"Frequency: {}\".format(frequency))","sub_path":"day1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"431627537","text":"group_number = -1\ngroup_id = []\ngroups_data = []\ndata = []\n\ndef get_group_number():\n try:\n print_groups()\n global group_number\n num = int(raw_input(\"Enter the number of the group you would like to analyze: \"))\n if num==10:\n print(\"\")\n menu()\n else:\n group_number = num\n if not ( 0<= group_number <= 9 ) :\n print(\"Not a valid integer\")\n get_group_number()\n except ValueError:\n print(\"\\nNot an integer\")\n get_group_number()\n\ndef get_group_id(groups_data, group_number):\n\n group_id = groups_data['response'][group_number]['id']\n return group_id\n\n\ndef get_group_option():\n try:\n print_group_options()\n choice = int(raw_input(\"Enter the number: \"))\n print(\"\")\n if 1<= choice <= 9 :\n return choice\n else:\n print(\"Not a valid integer\\n\")\n return get_group_option()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return get_group_option()\n\ndef get_group_option_more():\n try:\n print_group_options_more()\n choice = int(raw_input(\"Enter the number: \"))\n print(\"\")\n if 1<= choice <= 16 :\n return choice\n else:\n print(\"Not a valid integer\\n\")\n return get_group_option_more()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return get_group_option_more()\n\ndef get_person_option():\n try:\n print_person_options()\n choice = int(raw_input(\"Enter the number: \"))\n print(\"\")\n if 1<= choice <= 9 :\n return choice\n else:\n print(\"Not a valid integer\\n\")\n return get_person_option()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return get_person_option()\n\ndef get_person_option_more():\n try:\n print_person_options_more()\n choice = int(raw_input(\"Enter the number: \"))\n print(\"\")\n if 1<= choice <= 9 :\n return choice\n else:\n print(\"Not a valid integer\\n\")\n return get_person_option_more()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return get_person_option_more()\n\ndef print_person_options():\n options1=[\n 'Number of messages sent all time',\n 'Total likes given all time',\n 'Total likes received all time',\n 'Average likes received per message all time',\n 'Most popular word of all time',\n 'Most liked message',\n 'More options',\n 'Group Specific Statistics',\n 'Back' ]\n print(\"Which statistic would you like to retreive?\")\n for i in range(len(options1)):\n print(str(i+1)+\". \"+\"\\'\"+options1[i]+\"\\'\")\n\ndef print_person_options_more():\n options1=[\n 'Self likes of all time',\n 'Total likes received all time (with self likes subtracted)',\n 'Total words sent all time',\n 'Number of pictures sent all time',\n 'Number of videos sent all time',\n 'Most liked message - Text all time',\n 'Most liked message - Picture all time',\n 'Most liked message - Video all time',\n 'Back'\n ]\n print(\"More options\")\n print(\"Which statistic would you like to receive?\")\n for i in range(len(options1)):\n print(str(i+1)+\". \"+\"\\'\"+options1[i]+\"\\'\")\n\ndef print_group_options():\n options1=[\n 'Your number of messages sent',\n 'Your total likes given',\n 'Your total likes received',\n 'Your average likes received per message',\n 'Your most popular word',\n 'Your most liked message',\n 'More options',\n 'Person Specific Statistics',\n 'Back'\n ]\n print_group_name()\n print(\"Which statistic would you like to retreive?\")\n for i in range(len(options1)):\n print(str(i+1)+\". \"+\"\\'\"+options1[i]+\"\\'\")\n\ndef print_group_options_more():\n options1=[\n 'Self-likes',\n 'Total likes received (with self likes subtracted)',\n 'Total words sent',\n 'Number of pictures sent',\n 'Number of videos sent',\n 'Most liked message - Text',\n 'Most liked message - Picture',\n 'Most liked message - Video',\n 'Number of likes received from each member of group',\n 'Percent of each member\\'s total likes that went to a particular member',\n 'Number of times you liked the same post as another member',\n 'Most \"popular\" person',\n 'Least \"popular\" person',\n 'What time of day is the groupme most active',\n 'Group\\'s most popular word',\n 'Back'\n ]\n print(\"More options for \" + data['response'][group_number]['name'])\n print(\"Which statistic would you like to retreive?\")\n for i in range(len(options1)):\n print(str(i+1)+\". \"+\"\\'\"+options1[i]+\"\\'\")\n\"\"\" get_group_number retrieves the group number. It uses recursion to prompt user\nto input until a valid input is given.\n\"\"\"\ndef print_person_or_group():\n print(\"Which type of statistic would you like to retrieve?\")\n print(\"1 - Group Specific Statistics\")\n print(\"2 - Person Specific Statistics\")\n\n#function that displays groups and retrieves group data\n#Prints all of a user's groupme groups\ndef print_groups():\n\n if len(data['response']) == 0:\n print(\"You are not part of any groups.\")\n return\n print(\"Here are your ten most recent groups:\")\n for i in range(len(data['response'])):\n group = data['response'][i]['name']\n print(str(i)+\". \"+\"\\'\"+group+\"\\'\")\n print(\"10. Back\")\n global groups_data\n groups_data = data\n\ndef get_person():\n\n choice = get_person_option()\n if choice==1:\n #Number of messages sent all time\n donothing=0\n elif choice==2:\n #Total likes given all time\n donothing=0\n elif choice==3:\n #Total likes received all time\n donothing=0\n elif choice==4:\n #Average likes received per message all time\n donothing=0\n elif choice==5:\n #Most popular word of all time\n donothing=0\n elif choice==6:\n #Most liked message\n donothing=0\n elif choice==7:\n #More options\n get_person_more()\n elif choice==8:\n #Group Specific Statistics\n get_groups()\n elif choice==9:\n #Back to menu\n menu()\n\ndef get_groups():\n choice = get_group_option()\n if choice==1:\n #Your number of messages sent\n donothing=0\n elif choice==2:\n #Your total likes given\n donothing=0\n elif choice==3:\n #Your total likes received\n donothing=0\n elif choice==4:\n #Your average likes received per message\n donothing=0\n elif choice==5:\n #Your most popular word\n donothing=0\n elif choice==6:\n #MYour most liked message\n donothing=0\n elif choice==7:\n #More options\n get_groups_more()\n elif choice==8:\n #Person Specific Statistics\n get_person()\n elif choice==9:\n #Back to menu\n group()\n\ndef group():\n choose_which_group()\n get_groups()\n\ndef choose_which_group():\n get_group_number()\n group_id = get_group_id(groups_data, group_number)\n\ndef get_person_more():\n\n choice = get_person_option_more()\n if choice==1:\n #Self likes of all time\n donothing=0\n elif choice==2:\n #Total likes received all time (with self likes subtracted)\n donothing=0\n elif choice==3:\n #Total words sent all time\n donothing=0\n elif choice==4:\n #Number of pictures sent all time\n donothing=0\n elif choice==5:\n #Number of videos sent all time\n donothing=0\n elif choice==6:\n #Most liked message - Text all time\n donothing=0\n elif choice==7:\n #Most liked message - Pic all time\n donothing=0\n elif choice==8:\n #Most liked message - Video all time\n donothing=0\n elif choice==9:\n #Back to previous options\n get_person()\n\ndef print_group_name():\n print(\"\\n\"+data['response'][group_number]['name'])\n\ndef get_groups_more():\n choice = get_group_option_more()\n if choice==1:\n #Self-likes\n donothing=0\n elif choice==2:\n #Total likes received (with self likes subtracted)\n donothing=0\n elif choice==3:\n #Total words sent\n donothing=0\n elif choice==4:\n #Number of pictures sent\n donothing=0\n elif choice==5:\n #Number of videos sent\n donothing=0\n elif choice==6:\n #Most liked message - Text\n donothing=0\n elif choice==7:\n #Most liked message - Pic\n get_groups_more()\n elif choice==8:\n #Most liked message - Video\n get_person()\n elif choice==9:\n #Number of likes received from each member of group\n donothing=0\n elif choice==10:\n #Percent of each member\\'s total likes that went to a particular member\n donothing=0\n elif choice==11:\n #Number of times you liked the same post as another member\n donothing=0\n elif choice==12:\n #Most \"popular\" person\n donothing=0\n elif choice==13:\n #Least \"popular\" person\n donothing=0\n elif choice==14:\n #What time of day is the groupme most active\n donothing=0\n elif choice==15:\n #Group\\'s most popular word\n donothing=0\n elif choice==16:\n #Back\n get_groups()\n\n#function that prompts user to choose between person and group statistics\n#true means they chose group, false means they chose person\ndef chose_group():\n try:\n print_person_or_group()\n choice = int(raw_input(\"Enter the number of the type of statistic: \"))\n if choice==1:\n print(\"\")\n return True\n elif choice==2:\n print(\"\")\n return False\n else:\n print(\"Not a valid integer\\n\")\n return chose_group()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return chose_group()\n","sub_path":"Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468057003","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nfrom torch.utils import data\nimport torch.utils.model_zoo as model_zoo\nfrom torchvision import models\n\n\nclass Refine(nn.Module):\n def __init__(self, inplanes, planes, scale_factor=2):\n super(Refine, self).__init__()\n self.convFS1 = nn.Conv2d(inplanes, planes, kernel_size=3, padding=1)\n self.convFS2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)\n self.convFS3 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)\n self.convMM1 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)\n self.convMM2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)\n self.scale_factor = scale_factor\n\n def forward(self, f, pm):\n s = self.convFS1(f)\n sr = self.convFS2(F.relu(s))\n sr = self.convFS3(F.relu(sr))\n s = s + sr\n \n m = s + F.upsample(pm, scale_factor=self.scale_factor, mode='bilinear')\n\n mr = self.convMM1(F.relu(m))\n mr = self.convMM2(F.relu(mr))\n m = m + mr\n return m","sub_path":"RefinementLayers.py","file_name":"RefinementLayers.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"252980726","text":"from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\nBase = declarative_base()\n\n\nclass Person(Base):\n __tablename__ = 'person'\n id = Column(Integer, primary_key=True, unique=True)\n name = Column(String(250), nullable=False)\n screen_name = Column(String(250), nullable=False)\n description = Column(String(250), nullable=False)\n location = Column(String(250), nullable=False)\n url = Column(String(250))\n\n followers_count = Column(Integer, default=0)\n statuses_count = Column(Integer, default=0)\n friends_count = Column(Integer, default=0)\n\n def GetFields():\n f = ('id', 'screen_name', 'name', 'description', 'location',\n 'url', 'followers_count', 'statuses_count', 'friends_count')\n return f\n\n\nclass Status(Base):\n __tablename__ = 'status'\n id = Column(String(250), primary_key=True, unique=True)\n text = Column(String(250), nullable=False)\n created_at = Column(DateTime, nullable=False)\n retweet_count = Column(Integer, default=0)\n retweeted = Column(Boolean, default=False)\n person_id = Column(Integer, ForeignKey('person.id'))\n person = relationship(Person)\n\nengine = create_engine('sqlite:///twittet_app.sqlite')\n# engine = create_engine('postgresql://scott:tiger@localhost/mydatabase')\n# engine = create_engine('postgresql://power_user:$poweruserpassword@ec2-52-32-217-129.us-west-2.compute.amazonaws.com:5432/tweet_db')\n\n\nBase.metadata.create_all(engine)\n","sub_path":"declaration.py","file_name":"declaration.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"99297283","text":"import numpy as np\nfrom scipy.spatial import Voronoi\nimport matplotlib.pyplot as plt\nimport os\nimport math\nimport pandas as pd\nimport matplotlib as mpl\nfrom NucliatorsCount import NucleatorsCounter\n# import TimeResolutionInspection\n\n\nclass NucleationProbabilityAndSPI:\n # todo: refactor to recieve input as variables XY and not file paths.\n def __init__(self, XY, die_times, treatment, time_frame, n_scramble=1000,\n draw=True, dist_threshold_nucliators_detection=200):\n self.mean_time_death = None\n self.nucliators_num = None\n self.time_frame = time_frame\n self.treatment_type = treatment\n self.n_scramble = n_scramble\n self.n_instances = len(die_times)\n self.die_times = die_times\n self.num_blobs = [x for x in range(int(max(self.die_times))+1)]\n self.experiment_time = len(self.num_blobs)\n self.XY = XY\n self.scrambles = self.create_scramble(self.XY, n=n_scramble)\n self.neighbors_difference_death_times = self.get_neighbors_difference_death_times()\n self.original_difference_death_times = self.neighbors_difference_death_times[0]\n self.scramble_signficance_95 = None\n self.scramble_signficance_98 = None\n self.scramble_mean_time_death = None\n self.propagation_index = -1\n self.statistic_score = self.assess_mean()\n self.death_perc_by_time = self.calc_death_perc()\n self.neighbors_stats = []\n self.difference_from_leader = []\n self.get_distance_time_from_leader()\n self.neighbors_list = []\n self.neighbors_list2 = []\n self.neighbors_list3 = []\n self.get_neighbors()\n self.who_is_leader = None\n self.cells_to_leader = None\n self.death_wave = None\n self.identify_leader()\n self.draw() if draw else None\n self.dataframe = None\n self.dist_threshold_nucliators_detection = dist_threshold_nucliators_detection\n self.nucliators_counter = NucleatorsCounter(self.XY, self.die_times, self.neighbors_list, self.dist_threshold_nucliators_detection)\n self.nucliators = None\n self.get_nucliators_num_and_proba()\n self.propagation_index = ((self.scramble_signficance_95 - self.mean_time_death) / self.scramble_signficance_95)\n # self.create_dataframe()\n\n def get_spi_nucleators(self):\n return {'spi': self.propagation_index, 'p_nuc': self.nucliation_proba}\n\n def get_nucliators_num_and_proba(self):\n \"\"\"\n if any of the Voronoy neighbors died before a cell, it is not a nucliator.\n :return:\n \"\"\"\n XY = self.XY\n TIMES = self.die_times\n # CHEN'S IMPLEMENTATION\n # nucliators = np.array([True for i in range(len(TIMES))])\n # leaders = np.array([-1 for i in range(len(TIMES))])\n # cells_idx_sorted_by_times = np.arange(0, len(TIMES), 1)\n # for cell_idx in cells_idx_sorted_by_times:\n # # nucliators[cell_idx] = True\n # cell_death = TIMES[cell_idx]\n # neighbors_prior_death = [True for i in range(len(self.neighbors_list[cell_idx]))]\n # for neighbor_idx in self.neighbors_list[cell_idx]:\n # # if nucliators[cell_idx] == True:\n # # break\n # neighbor_death = TIMES[neighbor_idx]\n # if cell_death > neighbor_death:# and leaders[cell_idx] == -1:\n # nucliators[cell_idx] = False\n # # leaders[cell_idx] = cell_idx\n # elif cell_death == neighbor_death and not nucliators[neighbor_idx]:\n # nucliators[cell_idx] = False\n # leaders[cell_idx] = cell_idx\n # else:\n # nucliators[cell_idx] = True\n # # if leaders[neighbor_idx] != -1:\n # # leaders[cell_idx] = leaders[neighbor_idx]\n #\n # self.nucliators = nucliators\n # self.nucliators_num = nucliators.sum()\n # self.nucliation_proba = self.nucliators_num / len(XY)\n\n # MY IMPLEMENTATION\n self.nucliators = self.nucliators_counter.calc_nucliators()\n self.nucliators_num = self.nucliators.sum()\n self.nucliation_proba = self.nucliators_num / len(self.XY)\n\n def create_dataframe(self):\n instances = []\n x_array = []\n y_array = []\n time_from_leader = []\n distance_from_leader = []\n first_neighbor_distance = []\n second_neighbor_distance = []\n third_neighbor_distance = []\n first_neighbor_time = []\n second_neighbor_time = []\n third_neighbor_time = []\n death_perc = []\n neighbors_number = []\n dead_neighbors_number = []\n has_1_dead_neighbors = []\n has_2_dead_neighbors = []\n has_3_dead_neighbors = []\n has_4_dead_neighbors = []\n has_5_dead_neighbors = []\n has_6_dead_neighbors = []\n has_7_dead_neighbors = []\n has_8_dead_neighbors = []\n has_9_dead_neighbors = []\n has_10_dead_neighbors = []\n # cell_line = []\n # treatment = []\n # signal_analyzed = []\n file_name = []\n neighbors_distance_from_leader = []\n neighbors_stats = self.get_neighbors_stats(self.neighbors_list)\n second_neighbors_num = []\n avg_distance_from_neighbors = []\n for i in range(self.n_instances):\n instances.append(i)\n file_name.append(self.file_name)\n # cell_line.append(self.cell_line)\n # treatment.append(self.treatment)\n x_array.append(self.XY[i][0])\n y_array.append(self.XY[i][1])\n # signal_analyzed.append(self.signal_analyzed)\n second_neighbors_num.append(len(self.neighbors_list2[i]))\n time_from_leader.append(self.difference_from_leader[i][0])\n distance_from_leader.append(self.difference_from_leader[i][1])\n neighbors_distance_from_leader.append(4)\n n = 0\n d = 0\n dis = 0\n for x in neighbors_stats[i]:\n n += 1\n dis += x[2]\n if x[1] >= 0:\n d += 1\n if d == 1:\n first_neighbor_distance.append(x[2])\n first_neighbor_time.append(x[1])\n elif d == 2:\n second_neighbor_distance.append(x[2])\n second_neighbor_time.append(x[1])\n elif d == 3:\n third_neighbor_distance.append(x[2])\n third_neighbor_time.append(x[1])\n n = 1 if n == 0 else n\n death_perc.append(d/n)\n avg_distance_from_neighbors.append(dis / n)\n neighbors_number.append(n)\n dead_neighbors_number.append(d)\n has_2_dead_neighbors.append(1 if d > 1 else 0)\n has_3_dead_neighbors.append(1 if d > 2 else 0)\n has_4_dead_neighbors.append(1 if d > 3 else 0)\n has_5_dead_neighbors.append(1 if d > 4 else 0)\n has_6_dead_neighbors.append(1 if d > 5 else 0)\n has_7_dead_neighbors.append(1 if d > 6 else 0)\n has_8_dead_neighbors.append(1 if d > 7 else 0)\n has_9_dead_neighbors.append(1 if d > 8 else 0)\n has_10_dead_neighbors.append(1 if d > 9 else 0)\n has_1_dead_neighbors.append(1 if d > 0 else 0)\n if d < 3:\n if d <= 2:\n third_neighbor_distance.append(None)\n third_neighbor_time.append(None)\n if d <= 1:\n second_neighbor_distance.append(None)\n second_neighbor_time.append(None)\n if d == 0:\n first_neighbor_distance.append(None)\n first_neighbor_time.append(None)\n for x in self.neighbors_list3[0]:\n neighbors_distance_from_leader[x] = 3\n for x in self.neighbors_list2[0]:\n neighbors_distance_from_leader[x] = 2\n for x in self.neighbors_list[0]:\n neighbors_distance_from_leader[x] = 1\n neighbors_distance_from_leader[0] = 0\n self.get_distance_from_local_leader(dead_neighbors_number)\n feature_table = pd.DataFrame(\n {'id': instances,\n 'file_name': file_name,\n # 'cell_line': cell_line,\n # 'treatment': treatment,\n # 'signal_analyzed': signal_analyzed,\n 'x_loc': x_array,\n 'y_loc': y_array,\n 'die_time': self.die_times,\n 'die_time_real': [x * self.time_frame for x in self.die_times],\n 'cell_leader': self.who_is_leader,\n 'distance_from_leader': distance_from_leader,\n 'is_nucliator': list(self.nucliators),\n 'time_from_leader': time_from_leader,\n 'death_perc': death_perc,\n 'first_neighbor_distance': first_neighbor_distance,\n 'first_neighbor_time': first_neighbor_time,\n 'second_neighbor_distance': second_neighbor_distance,\n 'second_neighbor_time': second_neighbor_time,\n 'third_neighbor_distance': third_neighbor_distance,\n 'third_neighbor_time': third_neighbor_time,\n # 'total_density':self.density,\n # 'point_density':self.density_points,\n 'neighbors_distance_from_leader': neighbors_distance_from_leader,\n 'has_1_dead_neighbors': has_1_dead_neighbors,\n 'has_2_dead_neighbors': has_2_dead_neighbors,\n 'has_3_dead_neighbors': has_3_dead_neighbors,\n 'has_4_dead_neighbors': has_4_dead_neighbors,\n 'has_5_dead_neighbors': has_5_dead_neighbors,\n 'has_6_dead_neighbors': has_6_dead_neighbors,\n 'has_7_dead_neighbors': has_7_dead_neighbors,\n 'has_8_dead_neighbors': has_8_dead_neighbors,\n 'has_9_dead_neighbors': has_9_dead_neighbors,\n 'has_10_dead_neighbors': has_10_dead_neighbors,\n 'neighbors_number': neighbors_number,\n 'second_neighbors_num': second_neighbors_num,\n 'avg_distance_from_neighbors': avg_distance_from_neighbors,\n 'dead_neighbors_number': dead_neighbors_number\n })\n\n # location = self.data_path + \"/File_{}.csv\".format(self.file_name)\n # feature_table.to_csv(location)\n self.dataframe = feature_table\n self.propagation_index = ((self.scramble_signficance_95 - self.mean_time_death) / self.scramble_signficance_95)\n # print(\"SPI: {}\".format(propagation_index))\n\n def create_scramble(self, xy, n=1000):\n scrambles = []\n for i in range(n):\n temp_copy = xy.copy()\n np.random.shuffle(temp_copy)\n scrambles.append(temp_copy)\n return scrambles\n\n def get_neighbors_difference_death_times(self):\n times = []\n times.append(self.get_time_from_neighbors(self.die_times, self.XY))\n for i in range(self.n_scramble):\n times.append(self.get_time_from_neighbors(self.die_times, self.scrambles[i]))\n return times\n\n def get_time_from_neighbors(self, times, points):\n vor = Voronoi(points)\n neighbors = vor.ridge_points\n t = []\n for i in range(len(neighbors)):\n t.append(abs(times[neighbors[i][0]] - times[neighbors[i][1]]))\n return t\n\n def get_neighbors(self):\n vor = Voronoi(self.XY)\n neighbors = vor.ridge_points\n leaders = []\n for i in range(self.n_instances):\n self.neighbors_list.append([])\n self.neighbors_list2.append([])\n self.neighbors_list3.append([])\n for x in neighbors:\n self.neighbors_list[x[0]].append(x[1])\n self.neighbors_list[x[1]].append(x[0])\n for i in range(self.n_instances):\n for j in self.neighbors_list[i]:\n self.neighbors_list2[i] = list(set(self.neighbors_list2[i]+self.neighbors_list[j]))\n for i in range(self.n_instances):\n for j in self.neighbors_list2[i]:\n self.neighbors_list3[i] = list(set(self.neighbors_list3[i]+self.neighbors_list2[j]))\n\n def get_distance_from_local_leader(self, neighbors_death):\n leaders = []\n for i in range(self.n_instances):\n if neighbors_death[i] == 0:\n leaders.append(i)\n closest_leader = []\n distance_from_leader = []\n time_from_leader = []\n for i in range(self.n_instances):\n min_distance = math.sqrt(((self.XY[i][0]-self.XY[0][0])**2)+((self.XY[i][1]-self.XY[0][1])**2))\n min_point = 0\n for j in range(len(leaders)):\n new_distance = math.sqrt(((self.XY[i][0]-self.XY[j][0])**2)+((self.XY[i][1]-self.XY[j][1])**2))\n if new_distance < min_distance:\n min_distance = new_distance\n min_point = j\n closest_leader.append(min_point)\n distance_from_leader.append(min_distance)\n time_from_leader.append(self.die_times[i] - self.die_times[min_point])\n\n def identify_leader(self):\n who_is_leader = [-1]*self.n_instances\n for i in range(self.n_instances):\n temp = []\n for k in self.neighbors_list[i]:\n # if one of the neighbors of cell i is known to be a leader,\n # cell i defines it as its leader (first round nothing happens)\n temp.append(who_is_leader[k]) if who_is_leader[k] > -1 else None\n # if no leader was found for cell i is it's own leader else,\n # the leader for the most of the cell's neighbors is the cell's leader\n who_is_leader[i] = i if len(temp) == 0 else max(set(temp), key=temp.count)\n # calculating the distance of each cell from it's neighbors.\n neighbors_distance = [-1]*self.n_instances\n for i in range(self.n_instances):\n # if the cell is its own leader the distance is 0.\n neighbors_distance[i] = 0 if i == who_is_leader[i] else -1\n for j in range(self.n_instances):\n # for each cell j\n stop_sign = 0\n for i in range(self.n_instances):\n # if distance from neighbor i wasn't calculated so far\n if neighbors_distance[i] == -1:\n for k in self.neighbors_list[i]:\n # each of cell's i neighbors, if the distance from neighbor k was measured,\n # use it plus 1 (bc its a neighbor\n if neighbors_distance[k] > -1:\n neighbors_distance[i] = neighbors_distance[k]+1\n break\n else:\n # if neighbor k has no measured distance yet,\n # increment in 1 nad continue to the next neighbor k of neighbor i\n stop_sign += 1\n # if all neighbors (i) of cell j had all of its neighbors (k) distance measurement,\n # there is nothing to calculate, stop.\n if stop_sign == 0:\n break\n self.who_is_leader = who_is_leader\n self.death_wave = neighbors_distance\n self.nucliators_num = len(set(who_is_leader))\n\n def get_distance_time_from_leader(self):\n for i in range(self.n_instances):\n time = self.die_times[i] - self.die_times[0]\n distance = math.sqrt(((self.XY[i][0]-self.XY[0][0])**2)+((self.XY[i][1]-self.XY[0][1])**2))\n a = (time, distance)\n self.difference_from_leader.append(a)\n\n def get_neighbors_stats(self, neighbors_list):\n neighbors_stats_temp = []\n for i in range(self.n_instances):\n neighbors_stats_temp.append([])\n for j in neighbors_list[i]:\n time = self.die_times[i] - self.die_times[j]\n distance = math.sqrt(((self.XY[i][0]-self.XY[j][0])**2)+((self.XY[i][1]-self.XY[j][1])**2))\n a = (j, time, distance)\n neighbors_stats_temp[i].append(a)\n neighbors_stats = []\n for local_list in neighbors_stats_temp:\n neighbors_stats.append(sorted(local_list, key=lambda x: x[2]))\n return neighbors_stats\n\n def assess_mean(self):\n better_mean = 0\n time_death_means = []\n real_mean_time_death = self.calc_mean(self.neighbors_difference_death_times[0])\n self.mean_time_death = real_mean_time_death * self.time_frame\n for i in range(self.n_scramble):\n temp_mean_time_death = self.calc_mean(self.neighbors_difference_death_times[i + 1])\n time_death_means.append(temp_mean_time_death)\n if temp_mean_time_death > real_mean_time_death:\n better_mean += 1\n time_death_means.sort()\n self.scramble_signficance_95 = time_death_means[int(self.n_scramble * 5 / 100)] * self.time_frame\n self.scramble_signficance_98 = time_death_means[int(self.n_scramble * 2 / 100)] * self.time_frame\n self.scramble_mean_time_death = (sum(time_death_means) / len(time_death_means)) * self.time_frame\n return better_mean / self.n_scramble\n\n def calc_mean(self, l):\n return sum(l) / float(len(l))\n\n def draw(self):\n bins = np.linspace(0, 20, 20)\n histogram_scramble = []\n for z in range(len(self.num_blobs)):\n histogram_scramble.append(0)\n for z in range(len(self.neighbors_difference_death_times[0])):\n for i in range(self.n_scramble):\n j = i + 1\n histogram_scramble[int(self.neighbors_difference_death_times[j][z])] += 1\n avg_scramble_time = []\n for z in range(len(histogram_scramble)):\n histogram_scramble[z] /= self.n_scramble\n n = round(histogram_scramble[z])\n for i in range(n):\n avg_scramble_time.append(z)\n plt.hist(self.neighbors_difference_death_times[0], bins, alpha=0.5, label='Origin')\n plt.hist(avg_scramble_time, bins, alpha=0.5, label=\"Scramble\")\n plt.legend(loc='upper right')\n # location = self.pic_path + \"/histogram_{}.png\".format(self.file_name)\n # plt.savefig(location)\n plt.clf()\n plt.plot(self.death_perc_by_time)\n plt.ylabel('Death Perc')\n plt.xlabel('Time of Death')\n # location = self.pic_path + \"/death_time_{}.png\".format(self.file_name)\n # plt.savefig(location)\n plt.clf()\n self.draw_time_scatter()\n self.draw_wave_scatter()\n\n def calc_death_perc(self):\n death_by_time = [0] * len(self.num_blobs)\n for i in range(self.n_instances):\n death_by_time[int(self.die_times[i])] += 1\n death_by_time_cum = np.cumsum(death_by_time)\n return [x / self.n_instances for x in death_by_time_cum]\n\n def draw_time_scatter(self):\n fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n cmap = plt.get_cmap('jet', len(self.die_times) + 1)\n cmaplist = [cmap(i) for i in range(cmap.N)]\n cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)\n bounds = np.linspace(0, self.experiment_time, self.experiment_time + 1)\n norm = mpl.colors.BoundaryNorm(bounds, cmap.N)\n scat = ax.scatter(self.XY[:, 0], self.XY[:, 1], c=self.die_times, cmap=cmap, norm=norm)\n # scat = ax.scatter(self.listX, self.listY, c=self.die_times, cmap=cmap)\n cb = plt.colorbar(scat, spacing='proportional', ticks=bounds)\n cb.set_label('Custom cbar')\n ax.set_title('Death Time Scatter')\n # location = self.pic_path + \"/death_time_scatter_{}.png\".format(self.file_name)\n # plt.savefig(location)\n plt.clf()\n\n def draw_wave_scatter(self):\n n = max(self.death_wave)\n fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n cmap = plt.cm.jet\n cmaplist = [cmap(i) for i in range(cmap.N)]\n cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)\n bounds = np.linspace(0, n, n + 1)\n norm = mpl.colors.BoundaryNorm(bounds, cmap.N)\n scat = ax.scatter(self.XY[:, 0], self.XY[:, 1], c=self.death_wave, cmap=cmap, norm=norm)\n cb = plt.colorbar(scat, spacing='proportional', ticks=bounds)\n cb.set_label('Custom cbar')\n ax.set_title('Death Wave Scatter')\n location = self.pic_path + \"/death_wave_scatter_{}.png\".format(self.file_name)\n plt.savefig(location)\n plt.clf()\n\n# if __name__ == '__main__':\n# main_exps_fn = '/Users/yishaiazabary/Desktop/University/Thesis/CellDeathThesis/Code/Ferroptosis/ExperimentsXYT_CSVFiles'\n# exp_fn = '20160820_10A_FB_xy11.csv'\n# # exp_fn = '20171008_MCF7_H2O2_xy2.csv'\n# details_file_path = '/Users/yishaiazabary/Desktop/University/Thesis/CellDeathThesis/Code/Ferroptosis/ExperimentsXYT_CSVFiles/File details.csv'\n# full_file_path = os.sep.join([main_exps_fn, exp_fn])\n# exp_data_frame = TimeResolutionInspection.get_exp_data(full_file_path, details_file_path)\n# exp_temp_res = exp_data_frame['temporal_res']\n# exp_xy = exp_data_frame['XY']\n# exp_die_times = exp_data_frame['die_times']\n# exp_treatment = exp_data_frame['treatment']\n# nuc_p_spi = NucleationProbabilityAndSPI(XY=exp_xy,\n# die_times=exp_die_times,\n# time_frame=exp_temp_res,\n# treatment=exp_treatment,\n# n_scramble=1000,\n# draw=False,\n# dist_threshold_nucliators_detection=200)\n# print(nuc_p_spi.get_spi_nucleators())","sub_path":"NucleationProbabilityAndSPI.py","file_name":"NucleationProbabilityAndSPI.py","file_ext":"py","file_size_in_byte":21835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"47058296","text":"# -*- coding: utf-8 -*-\n__title__ = 'Copy View Parameters to Sheet'\n__doc__ = \"\"\"This allows sheet fields for drawing numbering \nto be updated with values from the placed viewport\n\nParameters include:\n\t\"Sub-Discipline\",\n\t\"Uniclass Ss - Group\",\n\t\"Uniclass Ss - Sub group\",\n\t\"Uniclass Ss - Section\",\n\t\"Uniclass Ss - Object\",\n\t\"Role Code\",\n\t\"Discipline Code\",\n\t\"View Description\"\n\n\n\n\n\n\"\"\"\n\n__helpurl__ = \"\"\n\nimport clr\nimport os\nimport os.path as op\nimport pickle as pl\n\nimport sys, os\nimport subprocess\nimport time\n\nimport rpw\nfrom rpw import doc, uidoc, DB, UI\n\nfrom System.Collections.Generic import List\nfrom Autodesk.Revit.DB import *\n\nimport sys, os\n\nfrom System import Array\n\nclr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')\nfrom Microsoft.Office.Interop import Excel\n\n\n\nimport sys, os\n## Add Path to MF Functions folder \t\n\nsys.path.append(os.path.realpath(__file__).split(\"MFTools.extension\")[0] + \"MFTools.extension\\MF_functions\")\n\t\nfrom MF_HeaderStuff import *\n\nfrom MF_SelectStuff import MF_SelectOptions\n\n\n\n\nallSheets = FilteredElementCollector(doc).OfClass(ViewSheet).ToElements()\n\n\n\n#select multiple\nselected = []\nreturn_options = SelectFromCheckBoxes.show(\n\t\t\tsorted([SheetOption(x) for x in allSheets],\n\t\t\t\t key=lambda x: x.number),\n\t\t\ttitle=\"Select Sheets\",\n\t\t\tbutton_name=\"Select Sheets\",\n\t\t\twidth=800)\nif return_options:\n\t\tselected = [x.unwrap() for x in return_options if x.state]\n\n\nsheetList = list(selected)\n\nfields = [\n\n\t\n\t\"Sub-Discipline\",\n\t\"Uniclass Ss - Group\",\n\t\"Uniclass Ss - Sub group\",\n\t\"Uniclass Ss - Section\",\n\t\"Uniclass Ss - Object\",\n\t\"Role Code\",\n\t\"Discipline Code\",\n\t\"View Description\",\n\t\"Zone Description\",\n\t\"MF_Work_section\"\n\n]\n\n#selected_fields = MF_SelectOptions(doc, \"Select Fields to Update\", fields)\n\nfrom mf_views_sheets import copy_view_parameters_to_sheet\n\ntr = Transaction(doc, __title__)\ntr.Start()\n\n\n\n\n\n'''\t\t\nops = ['option1', 'option2', 'option3', 'option4']\nswitches = ['switch1', 'switch2']\ncfgs = {'option1': { 'background': '0xFF55FF'}}\nrops, rswitches = forms.CommandSwitchWindow(\n\t\t\t\t\t\t\t\t\t\tops,\n\t\t\t\t\t\t\t\t\t\tswitches=switches,\n\t\t\t\t\t\t\t\t\t\tmessage='Select Option',\n\t\t\t\t\t\t\t\t\t\tconfig=cfgs\n\t\t\t\t\t\t\t\t\t\t)\t\t\n'''\t\t\nrename_sheet_option\t= False\n\nfor s in sheetList:\n\t\n\t\n\t\t\n\tif s.GetAllViewports():\n\t\t# get viewports placed on sheet\n\t\tviewports = s.GetAllViewports()\n\t\t\n\t\t\n\t\t\n\t\tfor vp in viewports:\n\t\t\tvPort = doc.GetElement(vp)\n\t\t\tview = doc.GetElement(vPort.ViewId)\n\t\t\t\n\t\t\n\t\t\t\n\t\t\tif view.ViewType == ViewType.FloorPlan:\n\t\t\t\tcopy_view_parameters_to_sheet(view, s, rename_sheet_option)\n\t\t\t\t\n\t# try to set the sheet name\n\t\t\n\t\t\n\n\ntr.Commit()\t\t\n\n\n\n","sub_path":"MFTools.extension/MF Project Tools.tab/Sheets.panel/sheets.stack2/Rename Sheets.pulldown/MF Update Sheet Fields from View Fields.pushbutton/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"1424095","text":"import os\nfrom torchtext import data\n\nclass MWP(data.Dataset):\n\n @staticmethod\n def sort_key(ex):\n return len(ex.text)\n\n def __init__(self, data_src, data_tgt, text_field, label_field,\n examples=None, **kwargs):\n \"\"\"Create an MWP dataset instance given a path and fields.\n\n Arguments:\n data_src: Path to source data file.\n data_tgt: Path to target data file.\n text_field: The field that will be used for text data.\n label_field: The field that will be used for label data.\n examples: The examples contain all the data.\n Remaining keyword arguments: Passed to the constructor of\n data.Dataset.\n \"\"\"\n fields = [('text', text_field), ('label', label_field)]\n examples = []\n #print(data_src,data_tgt)\n for i,text in enumerate(data_src):\n eq = data_tgt[i]\n examples += [data.Example.fromlist([text, eq], fields)]\n self.examples = examples\n super(MWP, self).__init__(examples, fields, **kwargs)\n\n @classmethod\n def splits(cls, text_field, label_field, train_src, train_tgt, val_src,\n val_tgt, test_src, test_tgt):\n \"\"\"Create an MWP dataset instance given paths and fields.\n\n Arguments:\n text_field: The field that will be used for text data.\n label_field: The field that will be used for label data.\n train_src: Path to training source data file.\n train_tgt: Path to training target data file.\n val_src: Path to validation source data file.\n val_tgt: Path to validation target data file.\n test_src: Path to test source data file.\n test_tgt: Path to test target data file.\n \"\"\"\n print('Getting training split...')\n train_data = cls(data_src=train_src, data_tgt=train_tgt,\n text_field=text_field, label_field=label_field)\n print('Getting validation split...')\n val_data = cls(data_src=val_src, data_tgt=val_tgt,\n text_field=text_field, label_field=label_field)\n print('Getting test split...')\n test_data = cls(data_src=test_src, data_tgt=val_tgt,\n text_field=text_field, label_field=label_field)\n return tuple(d for d in (train_data, val_data, test_data)\n if d is not None)\n","sub_path":"model/mydatasets.py","file_name":"mydatasets.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"640373730","text":"class Solution(object):\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n height = sorted(zip(list(xrange(len(height))), height), key=lambda x: x[1], reverse=True)\n a = b = height[0][0]\n ans = 0\n for item in height:\n a = max(item[0], a)\n b = min(item[0], b)\n ans = max((a - b) * item[1], ans)\n return ans","sub_path":"container_with_most_water.py","file_name":"container_with_most_water.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"501258479","text":"import numpy as np\n\n\ndef batch(inputs):\n batch_size = len(inputs)\n\n document_sizes = np.array([len(doc) for doc in inputs], dtype=np.int32)\n document_size = document_sizes.max()\n\n sentence_sizes_ = [[len(sent) for sent in doc] for doc in inputs]\n max_sentence_size = max(map(max, sentence_sizes_))\n\n b = np.zeros(shape=[batch_size, document_size, max_sentence_size], dtype=np.int32) # == PAD\n\n sentence_sizes = np.zeros(shape=[batch_size, document_size], dtype=np.int32)\n for i, document in enumerate(inputs):\n for j, sentence in enumerate(document):\n sentence_sizes[i, j] = sentence_sizes_[i][j]\n for k, word in enumerate(sentence):\n b[i, j, k] = word\n\n return b, document_sizes, sentence_sizes\n\ndef load_embedding_vectors_glove(vocabulary, filename, vector_size):\n # load embedding_vectors from the glove\n # initial matrix with random uniform\n embedding_vectors = np.random.uniform(-0.25, 0.25, (len(vocabulary), vector_size))\n f = open(filename)\n for line in f:\n values = line.split()\n word = values[0]\n vector = np.asarray(values[1:], dtype=\"float32\")\n idx = vocabulary.get(word)\n if idx != 0:\n embedding_vectors[idx] = vector\n f.close()\n return embedding_vectors","sub_path":"data_util.py","file_name":"data_util.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"178324638","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nData preprocessing and features extraction\r\n\r\n# features ideas\r\n\r\nfor time:\r\n - keep daytime\r\n - add hour of day = (daytime - daytime(0)) % 24\r\n - add day of year = floor(k * (daytime - daytime(0)) / 24)\r\n\r\nfor each temporal information:\r\n - avg of temporal information for each zone\r\n - difference of temporal information to average\r\n\r\n- station_id [1,2,3,4,5]\r\n- integer (0/1) for calm_day or not\r\n\r\nfor each static features\r\npreprocessing:\r\n\r\n\r\n - fill na with 0\r\n - scale data with MaxAbsScaler to handle sparse data\r\nfeatures:\r\n - a features stat indicate if the |feature| > 0 - is not NaN actually\r\n - the preprocessed value\r\n\"\"\"\r\nimport pandas as pd\r\nfrom sklearn import preprocessing\r\nfrom dataset import cols\r\nimport numpy as np\r\nimport datetime\r\n\r\n\r\ndaytime_0 = 72.0\r\n\r\n\r\ndef fillna_static(df, log=False):\r\n \"\"\" \"\"\"\r\n for col in cols[\"static\"]:\r\n if log:\r\n df[col] = np.log(df.col.fillna(1.0))\r\n else:\r\n df[col] = df[col].fillna(0)\r\n\r\n\r\ndef scale_temporal(train, features_train, dev=None, features_dev=None):\r\n \"\"\" \"\"\"\r\n robust_scaler = preprocessing.RobustScaler()\r\n tmp = pd.DataFrame(\r\n robust_scaler.fit_transform(train[cols[\"temporal\"]]),\r\n columns=[col for col in cols[\"temporal\"]],\r\n index=train.index)\r\n features_train = pd.concat([features_train, tmp], axis=1)\r\n if dev is not None:\r\n tmp = pd.DataFrame(\r\n robust_scaler.transform(dev[cols[\"temporal\"]]),\r\n columns=[col for col in cols[\"temporal\"]],\r\n index=dev.index)\r\n features_dev = pd.concat([features_dev, tmp], axis=1)\r\n return features_train, features_dev\r\n\r\n\r\ndef scale_static(train, features_train, dev=None, features_dev=None, log=False):\r\n \"\"\" \"\"\"\r\n # fill static NaN with 0\r\n fillna_static(train, log)\r\n if dev is not None:\r\n fillna_static(dev, log)\r\n # scale data with MaxAbsScaler to handle sparse static data\r\n max_abs_scaler = preprocessing.MaxAbsScaler()\r\n tmp = pd.DataFrame(\r\n max_abs_scaler.fit_transform(train[cols[\"static\"]]),\r\n columns=[\"%s_sc\" % col for col in cols[\"static\"]],\r\n index=train.index)\r\n features_train = pd.concat([features_train, tmp], axis=1)\r\n if dev is not None:\r\n tmp = pd.DataFrame(\r\n max_abs_scaler.transform(dev[cols[\"static\"]]),\r\n columns=[\"%s_sc\" % col for col in cols[\"static\"]],\r\n index=dev.index)\r\n features_dev = pd.concat([features_dev, tmp], axis=1)\r\n return features_train, features_dev\r\n\r\n\r\ndef binarize_static(train, features_train, dev=None, features_dev=None):\r\n \"\"\" \"\"\"\r\n # binary static features\r\n binarizer = preprocessing.Binarizer()\r\n tmp = pd.DataFrame(\r\n binarizer.fit_transform(train[cols[\"static\"]]),\r\n columns=[\"%s_i\" % col for col in cols[\"static\"]],\r\n index=train.index)\r\n features_train = pd.concat([features_train, tmp], axis=1)\r\n if dev is not None:\r\n tmp = pd.DataFrame(\r\n binarizer.fit_transform(dev[cols[\"static\"]]),\r\n columns=[\"%s_i\" % col for col in cols[\"static\"]],\r\n index=dev.index)\r\n features_dev = pd.concat([features_dev, tmp], axis=1)\r\n return features_train, features_dev\r\n\r\n\r\ndef delta_temporal_station_zone(train, features_train, dev=None,\r\n features_dev=None):\r\n \"\"\" \"\"\"\r\n # add difference of average in zone and value in station\r\n for col in cols[\"temporal\"]:\r\n features_train[\"delta_%s\" % col] = train[\"%s_avg\" % col] - train[col]\r\n if dev is not None:\r\n features_dev[\"delta_%s\" % col] = dev[\"%s_avg\" % col] - dev[col]\r\n # scaled it\r\n scaler = preprocessing.StandardScaler()\r\n features_train[[\"delta_%s\" % col for col in cols[\"temporal\"]]] = \\\r\n scaler.fit_transform(\r\n features_train[[\"delta_%s\" % col for col in cols[\"temporal\"]]])\r\n if dev is not None:\r\n features_dev[[\"delta_%s\" % col for col in cols[\"temporal\"]]] = \\\r\n scaler.transform(\r\n features_dev[[\"delta_%s\" % col for col in cols[\"temporal\"]]])\r\n return features_train, features_dev\r\n\r\n\r\ndef add_temporal_rolling_mean(delta, train, features_train,\r\n dev=None, features_dev=None,\r\n columns=None):\r\n \"\"\" \"\"\"\r\n if columns is None:\r\n columns = cols[\"temporal\"]\r\n # compute rolling mean of step delta\r\n rol_df = train.groupby(\"block\")[columns] \\\r\n .rolling(delta, min_periods=0).mean() \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_mean_%i\" % (col, delta))\r\n for col in columns),\r\n inplace=True)\r\n features_train = features_train.merge(\r\n rol_df, left_index=True, right_index=True, copy=False)\r\n if dev is not None:\r\n rol_df = dev.groupby(\"block\")[columns] \\\r\n .rolling(delta, min_periods=0).mean() \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_mean_%i\" % (col, delta))\r\n for col in columns),\r\n inplace=True)\r\n features_dev = features_dev.merge(\r\n rol_df, left_index=True, right_index=True,\r\n suffixes=(\"\", \"_mean_%i\" % delta))\r\n # scale it\r\n # scaler = preprocessing.RobustScaler()\r\n # features_train[\r\n # [\"%s_mean_%i\" % (col, delta) for col in cols[\"temporal\"]]\r\n # ] = scaler.fit_transform(\r\n # features_train[[\"%s_mean_%i\" % (col, delta)\r\n # for col in cols[\"temporal\"]]])\r\n # if dev is not None:\r\n # features_dev[\r\n # [\"%s_mean_%i\" % (col, delta) for col in cols[\"temporal\"]]\r\n # ] = scaler.transform(\r\n # features_dev[[\"%s_mean_%i\" % (col, delta)\r\n # for col in cols[\"temporal\"]]])\r\n return features_train, features_dev\r\n\r\n\r\ndef rolling_mean_col(df, delta, cols):\r\n \"\"\" \"\"\"\r\n if isinstance(cols, basestring):\r\n cols = [cols]\r\n # compute rolling mean of step delta\r\n rol_df = df.groupby(\"block\")[cols] \\\r\n .rolling(delta, min_periods=0).mean() \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_mean_%i\" % (col, delta)) for col in cols),\r\n inplace=True)\r\n return rol_df\r\n\r\n\r\ndef add_temporal_rolling_std(delta, train, features_train,\r\n dev=None, features_dev=None):\r\n \"\"\" \"\"\"\r\n # compute rolling mean of step delta\r\n rol_df = train.groupby(\"block\")[cols[\"temporal\"]] \\\r\n .rolling(delta, min_periods=0).std() \\\r\n .fillna(method=\"bfill\") \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_std_%i\" % (col, delta))\r\n for col in cols[\"temporal\"]),\r\n inplace=True)\r\n features_train = features_train.merge(\r\n rol_df, left_index=True, right_index=True, copy=False)\r\n if dev is not None:\r\n rol_df = dev.groupby(\"block\")[cols[\"temporal\"]] \\\r\n .rolling(delta, min_periods=0).std() \\\r\n .fillna(method=\"bfill\") \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_std_%i\" % (col, delta))\r\n for col in cols[\"temporal\"]),\r\n inplace=True)\r\n features_dev = features_dev.merge(\r\n rol_df, left_index=True, right_index=True,\r\n suffixes=(\"\", \"_std_%i\" % delta))\r\n # scale it\r\n # scaler = preprocessing.RobustScaler()\r\n # features_train[\r\n # [\"%s_std_%i\" % (col, delta) for col in cols[\"temporal\"]]\r\n # ] = scaler.fit_transform(\r\n # features_train[[\"%s_std_%i\" % (col, delta)\r\n # for col in cols[\"temporal\"]]])\r\n # if dev is not None:\r\n # features_dev[\r\n # [\"%s_std_%i\" % (col, delta) for col in cols[\"temporal\"]]\r\n # ] = scaler.transform(\r\n # features_dev[[\"%s_std_%i\" % (col, delta)\r\n # for col in cols[\"temporal\"]]])\r\n return features_train, features_dev\r\n\r\n\r\ndef add_temporal_shift(config, features_train, features_dev=None):\r\n \"\"\" \"\"\"\r\n for col, delays in config.items():\r\n for delay in delays:\r\n features_train[\"%s_shift_%i\" % (col, delay)] = \\\r\n features_train[col].shift(delay).fillna(method=\"bfill\")\r\n if features_dev is not None:\r\n features_dev[\"%s_shift_%i\" % (col, delay)] = \\\r\n features_dev[col].shift(delay).fillna(method=\"bfill\")\r\n #\r\n return features_train, features_dev\r\n\r\n\r\ndef add_temporal_decomposition(freq, train, features_train, dev=None,\r\n features_dev=None, scale=False):\r\n \"\"\" \"\"\"\r\n temporal_train_dec = decompose_temporal(freq, train)\r\n # scale it\r\n if scale:\r\n scaler = preprocessing.StandardScaler(with_mean=True)\r\n temporal_train_dec[temporal_train_dec.columns] = \\\r\n scaler.fit_transform(temporal_train_dec)\r\n # merge\r\n features_train = features_train.merge(\r\n temporal_train_dec, left_index=True, right_index=True)\r\n if dev is not None:\r\n temporal_dev_dec = decompose_temporal(freq, dev)\r\n # scale it\r\n if scale:\r\n temporal_dev_dec[temporal_dev_dec.columns] = \\\r\n scaler.transform(temporal_dev_dec)\r\n # merge\r\n features_dev = features_dev.merge(\r\n temporal_dev_dec, left_index=True, right_index=True)\r\n return features_train, features_dev\r\n\r\n\r\ndef decompose_temporal(freq, train, log=True):\r\n \"\"\" \"\"\"\r\n import statsmodels.api as sm\r\n hour = datetime.timedelta(hours=1)\r\n d = datetime.datetime(2014, 1, 1, 0, 0)\r\n decompose = []\r\n for k, g in train.groupby(\"block\"):\r\n #\r\n g[\"daytime\"] = g[\"daytime\"].map(lambda x: d + int(x) * hour)\r\n tmp = g.set_index(pd.DatetimeIndex(g[\"daytime\"]))\r\n acc = g[[\"daytime\"]]\r\n for col in cols[\"temporal\"]:\r\n dec = sm.tsa.seasonal_decompose(tmp[[col]], freq=freq)\r\n res = concat_decomposition(dec)\r\n res = res.fillna(0.)\r\n acc = acc.merge(res, left_index=False, right_index=True,\r\n left_on=\"daytime\")\r\n decompose.append(acc)\r\n return pd.concat(decompose, axis=0).drop(\"daytime\", axis=1).sort_index()\r\n\r\n\r\ndef concat_decomposition(dec):\r\n \"\"\" \"\"\"\r\n to_merge = [\r\n dec.seasonal.rename(\r\n index=str,\r\n columns={dec.seasonal.columns[0]: \"%s_seasonal\" % dec.seasonal.columns[0]}),\r\n dec.trend.rename(\r\n index=str,\r\n columns={dec.trend.columns[0]: \"%s_trend\" % dec.trend.columns[0]}),\r\n dec.resid.rename(\r\n index=str,\r\n columns={dec.resid.columns[0]: \"%s_resid\" % dec.resid.columns[0]}),\r\n ]\r\n res = pd.concat(to_merge, axis=1)\r\n # cast index to datetime\r\n res = res.set_index(pd.DatetimeIndex(res.index))\r\n return res\r\n\r\n\r\ndef to_log(df):\r\n \"\"\" \"\"\"\r\n res = df.copy()\r\n for col in [\"temperature\", \"pressure\"]:\r\n res[col] = np.log(273.0 + df[col])\r\n return res\r\n\r\n\r\ndef hours_day(df):\r\n \"\"\" \"\"\"\r\n return df.daytime.map(lambda x: (x - daytime_0) % 24)\r\n # df[\"day_of_year\"] = df.hour_of_day.map(lambda x: x % 24)\r\n\r\n\r\ndef day_of_week(df):\r\n \"\"\" \"\"\"\r\n return df.daytime.map(lambda x: ((x - daytime_0) // 24) % 7)\r\n\r\n\r\ndef normalize_df(df):\r\n \"\"\" \"\"\"\r\n return pd.DataFrame(preprocessing.normalize(df), columns=df.columns,\r\n index=df.index)\r\n\r\n\r\ndef drop_cols(df, cols):\r\n \"\"\" \"\"\"\r\n return df[[col for col in df.columns if col not in cols]]\r\n\r\n\r\ndef make_features(train, dev=None, scale_temp=True,\r\n rolling_mean=True, deltas_mean=[], roll_mean_conf={},\r\n rolling_std=True, deltas_std=[],\r\n shift_config={}, temp_dec_freq=0,\r\n binary_static=False,\r\n pollutant=False,\r\n remove_temporal=False, log=False):\r\n \"\"\" \"\"\"\r\n general_col = [\"zone_id\", \"is_calmday\", \"daytime\"]\r\n f_train = train[general_col]\r\n if pollutant:\r\n encoder = preprocessing.LabelEncoder()\r\n f_train[\"pollutant\"] = encoder.fit_transform(train[\"pollutant\"])\r\n # hour of day & day of week\r\n f_train[\"hour_of_day\"] = hours_day(train)\r\n f_train[\"day_of_week\"] = day_of_week(train)\r\n # day of week\r\n if dev is not None:\r\n f_dev = dev[general_col]\r\n if pollutant:\r\n f_dev[\"pollutant\"] = encoder.fit_transform(dev[\"pollutant\"])\r\n # hour of day & day of week\r\n f_dev[\"hour_of_day\"] = hours_day(dev)\r\n f_dev[\"day_of_week\"] = day_of_week(dev)\r\n else:\r\n f_dev = None\r\n # to log for temperature and pressure\r\n if log:\r\n train = to_log(train)\r\n if dev is not None:\r\n dev = to_log(dev)\r\n # scale temporal features with robust scaling\r\n if scale_temp:\r\n f_train, f_dev = scale_temporal(train, f_train, dev, f_dev)\r\n else:\r\n f_train[cols[\"temporal\"]] = train[cols[\"temporal\"]]\r\n if dev is not None:\r\n f_dev[cols[\"temporal\"]] = dev[cols[\"temporal\"]]\r\n # scale data with MaxAbsScaler to handle sparse static data\r\n f_train, f_dev = scale_static(train, f_train, dev, f_dev, log=log)\r\n # binary static features\r\n if binary_static:\r\n f_train, f_dev = binarize_static(train, f_train, dev, f_dev)\r\n # Rolling mean of step delta\r\n if rolling_mean:\r\n if roll_mean_conf:\r\n for delta, columns in roll_mean_conf.items():\r\n f_train, f_dev = add_temporal_rolling_mean(\r\n delta, train, f_train, dev, f_dev, columns)\r\n else:\r\n for delta in deltas_mean:\r\n f_train, f_dev = add_temporal_rolling_mean(\r\n delta, train, f_train, dev, f_dev)\r\n # Rolling Std of step deltas_std\r\n if rolling_std:\r\n for delta in deltas_std:\r\n f_train, f_dev = add_temporal_rolling_std(\r\n delta, train, f_train, dev, f_dev)\r\n # temporal shift\r\n if shift_config:\r\n f_train, f_dev = add_temporal_shift(shift_config, f_train, f_dev)\r\n # temporal decomposition\r\n if temp_dec_freq:\r\n f_train, f_dev = add_temporal_decomposition(\r\n temp_dec_freq, train, f_train, dev, f_dev)\r\n if remove_temporal:\r\n f_train = drop_cols(f_train, cols[\"temporal\"])\r\n if dev is not None:\r\n f_dev = drop_cols(f_dev, cols[\"temporal\"])\r\n # drop daytime col\r\n if \"daytime\" in f_train:\r\n f_train.drop(\"daytime\", axis=1, inplace=True)\r\n if dev is not None:\r\n if \"daytime\" in f_dev:\r\n f_dev.drop(\"daytime\", axis=1, inplace=True)\r\n #\r\n if dev is not None:\r\n return f_train, f_dev\r\n else:\r\n return f_train\r\n\r\n\r\ndef build_sequences(df, seq_length, pad=False, pad_value=0., norm=True):\r\n \"\"\" \"\"\"\r\n seqs = []\r\n ids = np.empty(shape=[0])\r\n for _, g in df.groupby(\"block\"):\r\n g[\"ID\"] = g.index\r\n g = g.set_index(\"daytime\").sort_index().drop(\"block\", axis=1)\r\n array = g.drop(\"ID\", axis=1).values\r\n ids.append(g.ID)\r\n np.concatenate((ids, g.ID.as_matrix()), axis=0)\r\n # L2 normalize\r\n if norm:\r\n array = preprocessing.normalize(array)\r\n # seqs = []\r\n for k in range(1, seq_length + 1):\r\n seqs.append(array[:k])\r\n for k in range(seq_length, array.shape[0]):\r\n seqs.append(array[k - seq_length:k])\r\n if pad:\r\n from keras.preprocessing.sequence import pad_sequences\r\n seqs = pad_sequences(seqs, maxlen=seq_length, dtype='float32',\r\n padding='pre', truncating='pre', value=pad_value)\r\n return seqs, ids\r\n\r\n\r\ndef make_seqential_features(train, dev=None, seq_length=12, normalize=False,\r\n temp_dec_freq=0, pollutant=False,\r\n remove_temporal=False, log=False):\r\n \"\"\" \"\"\"\r\n # make standard features\r\n f_train, f_dev = make_features(train, dev=dev, scale_temporal=True,\r\n temp_dec_freq=temp_dec_freq,\r\n pollutant=pollutant,\r\n remove_temporal=remove_temporal, log=log)\r\n # sequantialize\r\n # add block column\r\n f_train[\"block\"] = train[\"block\"]\r\n train_seqs, train_ids = build_sequences(f_train, seq_length=seq_length,\r\n pad=True, norm=normalize)\r\n if dev is not None:\r\n f_dev[\"block\"] = dev[\"block\"]\r\n dev_seqs, dev_ids = build_sequences(f_dev, seq_length=seq_length,\r\n pad=True, norm=normalize)\r\n # return\r\n if dev is not None:\r\n return train_seqs, train_ids, dev_seqs, dev_ids\r\n else:\r\n return train_seqs, train_ids\r\n\r\n\r\ndef make_hybrid_features(train, dev=None, seq_length=12, normalize=False,\r\n temp_dec_freq=0, pollutant=False,\r\n remove_temporal=False, log=False):\r\n \"\"\" \"\"\"\r\n columns = [\"daytime\", \"zone_id\", \"hour_of_day\", \"day_of_week\",\r\n \"is_calmday\", \"block\"]\r\n if temp_dec_freq:\r\n remove_temporal = True\r\n # make standard features\r\n f_train, f_dev = make_features(train, dev=dev, scale_temporal=True,\r\n temp_dec_freq=temp_dec_freq,\r\n pollutant=pollutant,\r\n remove_temporal=remove_temporal, log=log)\r\n\r\n # add block column\r\n f_train[\"block\"] = train[\"block\"]\r\n # temporal features: sequential\r\n temp_cols = [col for col in cols[\"temporal\"]]\r\n f_temp_train = f_train[columns + temp_cols].drop(\"zone_id\", axis=1)\r\n train_temp_seqs, train_ids = build_sequences(\r\n f_temp_train, seq_length=seq_length, pad=True, norm=normalize)\r\n if dev is not None:\r\n f_dev[\"block\"] = dev[\"block\"]\r\n f_temp_dev = f_dev[columns + temp_cols].drop(\"zone_id\", axis=1)\r\n dev_temp_seqs, dev_ids = build_sequences(\r\n f_temp_dev, seq_length=seq_length, pad=True, norm=normalize)\r\n # static features\r\n static_cols = [\"%s_sc\" % col for col in cols[\"static\"]] + [\"zone_id\"]\r\n # add wind sin and cosin\r\n static_cols.extend(\"windbearingcos\", \"windbearingsin\")\r\n train_static_ds = np.empty(shape=[0, len(static_cols)])\r\n gb = f_train.groupby(\"block\")\r\n for k, group in gb:\r\n group = group.set_index(\"daytime\").sort_index()\r\n train_static_ds = np.concatenate(\r\n (train_static_ds, group[static_cols].values), axis=0)\r\n if normalize:\r\n train_static_ds = preprocessing.normalize(train_static_ds)\r\n if dev is not None:\r\n dev_static_ds = np.empty(shape=[0, len(static_cols)])\r\n gb = f_dev.set_index(\"daytime\").groupby(\"block\")\r\n for k, group in gb:\r\n dev_static_ds = np.concatenate(\r\n (dev_static_ds, group[static_cols].values), axis=0)\r\n if normalize:\r\n dev_static_ds = preprocessing.normalize(dev_static_ds)\r\n # return\r\n if dev is not None:\r\n return [train_temp_seqs, train_static_ds, train_ids], [dev_temp_seqs, dev_static_ds, dev_ids]\r\n else:\r\n return [train_temp_seqs, train_static_ds, train_ids]\r\n\r\n\r\ndef get_seq_Y(X, Y, pollutant=None):\r\n \"\"\" \"\"\"\r\n Y_seq = np.empty(shape=[0])\r\n X_u = X[[\"daytime\", \"block\", \"pollutant\"]]\r\n Y_u = Y.merge(X_u, left_index=True, right_index=True, how=\"inner\")\r\n # if no pollutant passed find it\r\n if pollutant is None:\r\n tmp = Y_u.pollutant.unique()\r\n if len(tmp) == 1:\r\n pollutant = tmp[0]\r\n else:\r\n raise ValueError(\r\n \"Many pollutants in df, please set one in pollutant arg\")\r\n gb = Y_u[Y_u[\"pollutant\"] == pollutant].groupby(\"block\")\r\n for k, group in gb:\r\n Y_seq = np.concatenate((Y_seq, group.TARGET.values))\r\n return Y_seq\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n \"\"\" \"\"\"\r\n pass\r\n\r\n\r\n\r\n","sub_path":"features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":20345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"459929353","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"Text viewer widget for use with QAD and Redux.\"\"\"\n\ntry:\n from PyQt5 import QtWidgets, QtGui, QtCore\n from sofia_redux.pipeline.gui.ui import ui_textview\nexcept ImportError:\n HAS_PYQT5 = False\n QtGui = None\n\n # duck type parents to allow class definition\n class QtWidgets:\n class QDialog:\n pass\n\n class ui_textview:\n class Ui_TextWindow:\n pass\nelse:\n HAS_PYQT5 = True\n\n__all__ = ['TextView']\n\n\nclass TextView(QtWidgets.QDialog, ui_textview.Ui_TextWindow):\n \"\"\"\n View, find, and filter text.\n\n All attributes and methods for this class are intended for internal\n use, in response to user actions within a Qt5 application.\n \"\"\"\n def __init__(self, parent=None):\n \"\"\"\n Initialize the text viewer widget.\n\n Parameters\n ----------\n parent : `QWidget`\n Parent widget.\n \"\"\"\n if not HAS_PYQT5: # pragma: no cover\n raise ImportError('PyQt5 package is required for Redux GUI.')\n\n # parent initialization\n QtWidgets.QDialog.__init__(self, parent)\n\n # set up UI from Designer generated file\n self.setupUi(self)\n\n # make sure there's a close button\n self.setWindowFlags(QtCore.Qt.Window\n | QtCore.Qt.WindowMaximizeButtonHint\n | QtCore.Qt.WindowMinimizeButtonHint\n | QtCore.Qt.WindowCloseButtonHint)\n\n # connect buttons\n self.findButton.clicked.connect(self.find)\n self.filterButton.clicked.connect(self.filter)\n self.tableButton.setEnabled(False)\n\n # hide save button: should only appear if text is editable\n self.saveButton.setVisible(False)\n\n # last loaded text\n self.text = None\n self.html = None\n\n def load(self, text):\n \"\"\"\n Load text into the widget.\n\n Parameters\n ----------\n text : list of str\n The text to display.\n \"\"\"\n if text is None:\n text = ''\n if type(text) is not list:\n text = [text]\n\n self.text = text\n\n # format to HTML\n self.html = self.format()\n\n # set text in text window\n self.textEdit.setHtml(self.html)\n self.textEdit.repaint()\n\n def setTitle(self, title):\n \"\"\"Set the window title.\"\"\"\n self.setWindowTitle(title)\n\n def find(self):\n \"\"\"Find a string within the text.\"\"\"\n\n # read text to find\n # whole field will be matched; comma-separated fields not allowed\n find_text = self.findText.text().strip()\n\n cursor = self.textEdit.textCursor()\n if find_text == '':\n # set cursor back to beginning of document\n cursor.movePosition(QtGui.QTextCursor.Start)\n self.textEdit.setTextCursor(cursor)\n else:\n # find next instance\n found = self.textEdit.find(find_text)\n if not found:\n # wrap back to beginning and try one more find\n cursor.movePosition(QtGui.QTextCursor.Start)\n self.textEdit.setTextCursor(cursor)\n self.textEdit.find(find_text)\n self.textEdit.repaint()\n\n def filter(self):\n \"\"\"Filter text to lines containing a specified string.\"\"\"\n\n # read text to filter\n # may be comma-separated substrings\n find_text = self.findText.text().strip()\n\n if find_text == '':\n # clear previous filter / table\n self.textEdit.setHtml(self.html)\n else:\n # allow multiple filter keys\n sep = find_text.split(',')\n\n # split text on lines\n header = self.html.split('<br>')\n\n # find substrings in lines\n filtered = []\n for line in header:\n added = False\n\n # keep anchored lines -- filename headers, <pre> tags\n if '<a name=\"anchor\">' in line:\n filtered.append(line)\n else:\n for text in sep:\n if added:\n break\n if text.strip().lower() in line.lower():\n filtered.append(line)\n added = True\n self.textEdit.setHtml('<br>'.join(filtered))\n\n # repaint required for some versions of Qt/OS\n self.textEdit.repaint()\n\n def format(self):\n \"\"\"\n Format the input text to HTML for display.\n\n Returns\n -------\n str\n HTML-formatted text.\n \"\"\"\n anchor = '<a name=\"anchor\"></a>'\n br = '<br>'\n\n text_str = br.join(self.text)\n html = '<pre>' + anchor + br + text_str + br + '</pre>' + anchor\n\n return html\n","sub_path":"sofia_redux/pipeline/gui/textview.py","file_name":"textview.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"481058330","text":"from django.shortcuts import render\nfrom rest_framework.generics import CreateAPIView, ListAPIView\nfrom .serializers import UserSerializer, PublicUserSerizlizer\nfrom rest_framework import permissions\nfrom django.contrib.auth.models import User\n\nclass UserCreateView(CreateAPIView):\n serializer_class = UserSerializer\n permission_classes = [permissions.AllowAny]\n\n\nclass UserListView(ListAPIView):\n permission_classes = [permissions.IsAuthenticated]\n serializer_class = PublicUserSerizlizer\n\n def get_queryset(self):\n queryset = User.objects.exclude(id=self.request.user.pk)\n\n return queryset\n \nclass UsernameView(ListAPIView):\n permission_classes = [permissions.IsAuthenticated]\n serializer_class = PublicUserSerizlizer\n\n def get_queryset(self):\n return User.objects.filter(id=self.request.user.id)\n ","sub_path":"chat/apps/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468874931","text":"import numpy as np\nfrom KalmanFilter import KalmanFilter\nfrom scipy.optimize import linear_sum_assignment\nfrom collections import deque\nimport cv2\n\nclass Tracks(object):\n\t\"\"\"docstring for Tracks\"\"\"\n\tdef __init__(self, detection, trackId):\n\t\tsuper(Tracks, self).__init__()\n\t\tself.KF = KalmanFilter()\n\t\tself.KF.predict()\n\t\tself.KF.correct(np.matrix(detection).reshape(2,1))\n\t\tself.trace = deque(maxlen=500)\n\t\tself.nframe = deque(maxlen=500)\n\t\tself.prediction = detection.reshape(1,2)\n\t\tself.trackId = trackId\n\t\tself.skipped_frames = 0\n\n\tdef predict(self,detection):\n\t\tself.prediction = np.array(self.KF.predict()).reshape(1,2)\n\t\tself.KF.correct(np.matrix(detection).reshape(2,1))\n\n\tdef genMainPoints(self, fps = 25):\n\n\t\tmain_points = np.ones(9)*-1\n\t\tmain_points[0] = self.trackId\n\t\tif len(self.trace) == 0:\n\t\t\treturn main_points\n\t\tmain_points[1] = self.nframe[0]/fps\n\t\tif (40 > self.trace[0][0,0]) and (20 < self.trace[0][0,1]):\n\t\t\tmain_points[2] = 0\n\t\t\tmain_points[3] = 1\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0,0] > 40:\n\t\t\t\t\tmain_points[7] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] > 200:\n\t\t\t\t\tmain_points[8] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\telif (340 < self.trace[0][0,0]) and (20 < self.trace[0][0,1]):\n\t\t\tmain_points[2] = 3\n\t\t\tmain_points[3] = 2\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] < 200:\n\t\t\t\t\tmain_points[7] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] < 40:\n\t\t\t\t\tmain_points[8] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\telif (340 > self.trace[0][0,0] > 200) and (20 > self.trace[0][0,1]):\n\t\t\tmain_points[2] = 5\n\t\t\tmain_points[3] = 4\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] < 200:\n\t\t\t\t\tmain_points[7] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] < 40:\n\t\t\t\t\tmain_points[8] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\tmain_points[4] = self.nframe[-1]/fps\n\t\tif (40 > self.trace[-1][0,0]) and (20 < self.trace[-1][0,1]):\n\t\t\tmain_points[5] = 1\n\t\t\tmain_points[6] = 0\n\t\telif (340 < self.trace[-1][0,0]) and (20 < self.trace[-1][0,1]):\n\t\t\tmain_points[5] = 2\n\t\t\tmain_points[6] = 3\n\t\telif (340 > self.trace[-1][0,0] > 200) and (20 > self.trace[-1][0,1]):\n\t\t\tmain_points[5] = 4\n\t\t\tmain_points[6] = 5\n\n\t\treturn main_points\n\n\n\n\nclass PeopleTrack(object):\n\t\"\"\"docstring for Tracker\"\"\"\n\tdef __init__(self, dist_threshold, max_frame_skipped, max_trace_length):\n\t\tsuper(PeopleTrack, self).__init__()\n\t\tself.dist_threshold = dist_threshold\n\t\tself.max_frame_skipped = max_frame_skipped\n\t\tself.max_trace_length = max_trace_length\n\n\n\t\t#private\n\t\tself.__trackId = 0\n\t\tself.__tracks = []\n\t\tself.__removed_tracks = []\n\t\tself.__nframes = -1\n\t\tself.__track_colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0),\n\t\t\t\t\t\t(127, 127, 255), (255, 0, 255), (255, 127, 255),\n\t\t\t\t\t\t(127, 0, 255), (127, 0, 127),(127, 10, 255), (0,255, 127)]\n\n\n\tdef update(self, detections):\n\t\t'''This function update the tracker positions and manage them'''\n\n\t\t# Update the current frame\n\t\tself.__nframes += 1\n\t\t# If no detections are passed, them these statements manage it.\n\t\tif detections.size == 0:\n\n\t\t\tfor i in range(len(self.__tracks)):\n\t\t\t\tself.__tracks[i].skipped_frames +=1\n\n\t\t\tdel_tracks = []\n\t\t\tfor i in range(len(self.__tracks)):\n\t\t\t\tif self.__tracks[i].skipped_frames > self.max_frame_skipped:\n\t\t\t\t\tdel_tracks.append(i)\n\n\t\t\tif len(del_tracks) > 0:\n\t\t\t\tfor i in range(len(del_tracks)):\n\t\t\t\t\tself.__removed_tracks.append(self.__tracks[del_tracks[i]])\n\t\t\t\t\tdel self.__tracks[del_tracks[i]]\n\n\t\t\treturn 0\n\n\n\t\tif len(self.__tracks) == 0:\n\t\t\tfor i in range(detections.shape[0]):\n\t\t\t\ttrack = Tracks(detections[i], self.__trackId)\n\t\t\t\tself.__trackId +=1\n\t\t\t\tself.__tracks.append(track)\n\n\t\t# Calculate the distance between detentions and prediction for each track\n\t\tN = len(self.__tracks)\n\t\tM = len(detections)\n\t\tcost = []\n\t\tfor i in range(N):\n\t\t\tdiff = np.linalg.norm(self.__tracks[i].prediction - detections.reshape(-1,2), axis=1)\n\t\t\tcost.append(diff)\n\n\t\tcost = np.array(cost)*0.1\n\t\trow, col = linear_sum_assignment(cost)\n\t\tassignment = [-1]*N\n\t\tfor i in range(len(row)):\n\t\t\tassignment[row[i]] = col[i]\n\n\t\tun_assigned_tracks = []\n\n\t\t# Check if the threshold condition is fulfilled\n\t\tfor i in range(len(assignment)):\n\t\t\tif assignment[i] != -1:\n\t\t\t\tif (cost[i][assignment[i]] > self.dist_threshold):\n\t\t\t\t\tassignment[i] = -1\n\t\t\t\t\tun_assigned_tracks.append(i)\n\t\t\t\t# else:\n\t\t\t\t# \tself.tracks[i].skipped_frames += 1\n\t\t\telse:\n\t\t\t\tself.__tracks[i].skipped_frames +=1\n\n\t\t#Those with no assigments are deleted\n\t\tdel_tracks = []\n\t\tfor i in range(len(self.__tracks)):\n\t\t\tif self.__tracks[i].skipped_frames > self.max_frame_skipped :\n\t\t\t\tdel_tracks.append(i)\n\n\t\tif len(del_tracks) > 0:\n\t\t\tfor i in range(len(del_tracks)):\n\t\t\t\tself.__removed_tracks.append(self.__tracks[del_tracks[i]])\n\t\t\t\tdel self.__tracks[del_tracks[i]]\n\t\t\t\tdel assignment[del_tracks[i]]\n\n\t\tfor i in range(len(detections)):\n\t\t\tif i not in assignment:\n\t\t\t\ttrack = Tracks(detections[i], self.__trackId)\n\t\t\t\tself.__trackId +=1\n\t\t\t\tself.__tracks.append(track)\n\n\n\t\tfor i in range(len(assignment)):\n\t\t\tif(assignment[i] != -1):\n\t\t\t\tself.__tracks[i].skipped_frames = 0\n\t\t\t\tself.__tracks[i].predict(detections[assignment[i]])\n\t\t\tself.__tracks[i].trace.append(self.__tracks[i].prediction)\n\t\t\tself.__tracks[i].nframe.append(self.__nframes)\n\n\tdef drawTracks(self, frame):\n\t\t'''This function allows you tu paint tracks on the frame'''\n\t\tfor j in range(len(self.__tracks)):\n\t\t\tif (len(self.__tracks[j].trace) > 1):\n\t\t\t\tx = int(self.__tracks[j].trace[-1][0, 0])\n\t\t\t\ty = int(self.__tracks[j].trace[-1][0, 1])\n\t\t\t\ttl = (x - 10, y - 10)\n\t\t\t\tbr = (x + 10, y + 10)\n\t\t\t\tcv2.rectangle(frame, tl, br, self.__track_colors[j], 1)\n\t\t\t\tcv2.putText(frame, str(self.__tracks[j].trackId), (x - 10, y - 20), 0, 0.5, self.__track_colors[j], 2)\n\t\t\t\tfor k in range(len(self.__tracks[j].trace)):\n\t\t\t\t\tx = int(self.__tracks[j].trace[k][0, 0])\n\t\t\t\t\ty = int(self.__tracks[j].trace[k][0, 1])\n\t\t\t\t\tcv2.circle(frame, (x, y), 3, self.__track_colors[j], -1)\n\t\t\t\tcv2.circle(frame, (x, y), 6, self.__track_colors[j], -1)\n\n\t\treturn frame\n\n\tdef reportMainPoints(self, rtype = 'all', timelapsemin = 5, fps = 25):\n\t\t'''Generate a report of the main points concerning to each track\n\t\t:param rtype: type of report to be generated. Choose between 'all' or 'best'\n\t\t:type rtype: str\n\t\t:param timelapsemin: minime time distance between first and last frame\n\t\t:type timelapsemin: int\n\t\t:param fps: frames per second\n\t\t:type fps: int\n\t\t'''\n\t\tall_tracks = self.__tracks + self.__removed_tracks\n\t\treport = []\n\t\tfor i in range(len(all_tracks)):\n\t\t\treport.append(all_tracks[i].genMainPoints(fps = fps))\n\n\t\tif rtype == 'all':\n\t\t\treturn np.array(report)\n\t\tif rtype == 'best':\n\t\t\treport_best = []\n\t\t\tfor rp in report:\n\t\t\t\tif (rp[4]-rp[1]) > timelapsemin:\n\t\t\t\t\treport_best.append(rp)\n\t\t\treturn np.array(report_best)\n\n\n\n\n\n\n\t\t\n\n\n\n","sub_path":"PeopleTrack.py","file_name":"PeopleTrack.py","file_ext":"py","file_size_in_byte":6896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"191042774","text":"\"\"\"Implementation of a LinkedList\"\"\"\n\n\nclass LinkedList:\n \"\"\"An implementation of a linked list data structure\"\"\"\n\n def __init__(self):\n self.__size = 0\n self.__head = None\n\n def append(self, item):\n \"\"\"Append element\"\"\"\n\n if self.__size == 0:\n self.__head = Node(item, None)\n else:\n new_node = Node(item, None)\n last_node = self.__head\n\n for i in range(0, self.__size - 1):\n last_node = last_node.pointer\n\n last_node.pointer = new_node\n\n self.__size += 1\n\n def get(self, index):\n \"\"\"Get element given index\"\"\"\n\n node = self.__head\n\n for i in range(0, index):\n node = node.pointer\n\n return node.value\n\n def delete(self, index):\n \"\"\"Delete element given index\"\"\"\n\n if index == 0:\n self.__head = self.__head.pointer\n else:\n last_node = self.__head\n\n for i in range(0, index - 1):\n last_node = last_node.pointer\n\n last_node.pointer = last_node.pointer.pointer\n\n self.__size -= 1\n\n def size(self):\n \"\"\"Get size of array\"\"\"\n\n return self.__size\n\n\nclass Node:\n\n def __init__(self, value, pointer):\n\n self.value = value\n self.pointer = pointer\n","sub_path":"data_structures/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"276111802","text":"\"Write a Program to show whether the entered number is prime or not\"\n\ndef is_prime(number:int) -> bool:\n # Edge Cases\n if number == 1: return False\n \n # loop through all numbers from 2 to number and check remainder\n for i in range(2, number):\n if number % i == 0:\n return False\n return True\n\ndef main():\n __input = int(input(\"Enter number to check: \"))\n if is_prime(__input):\n print(f\"Number {__input} is Prime\")\n else:\n print(f\"Number {__input} is not Prime\")\n \nif __name__ == \"__main__\":\n main()\n\n__OUTPUT__ = \"\"\"\nEnter number to check: 13\nNumber 13 is Prime\n\"\"\"","sub_path":"22_is_prime.py","file_name":"22_is_prime.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"138601506","text":"from thetis import *\r\nimport pyproj\r\nimport numpy as np\r\nimport input_file_paths\r\nimport pandas as pd\r\nfrom modules import utm\r\n\r\n\r\ndef read_tide_gauge_data_file():\r\n tidegauge_file = input_file_paths.tidegauge_file\r\n data = pd.read_csv(tidegauge_file, header=21, sep='\\s+')\r\n data = data.drop(data[(data['Year'] < 1975)].index)\r\n data = data.drop(data[(data['Days'] < 30)].index)\r\n # data = data.loc[data.round(0).sort_values('Year', ascending=False).drop_duplicates(subset=['Lat', 'Lon'], keep='last').sort_index().index]\r\n data.Location = pd.io.parsers.ParserBase({'names': data.Location})._maybe_dedup_names(data.Location)\r\n # print(data.to_string()) # see which detectors are being sorted\r\n return data\r\n\r\n\r\ndef get_detectors(mesh2d):\r\n gauge_data = read_tide_gauge_data_file()\r\n gauge_latlon = gauge_data[['Lat', 'Lon']].values\r\n gauge_names = gauge_data['Location'].values\r\n gauge_xy = []\r\n gauge_locs = []\r\n for loc, (lat, lon) in zip(gauge_names, gauge_latlon):\r\n x, y, zone_num, zone_l = utm.from_latlon(lat, lon)\r\n if zone_num == 30:\r\n gauge_xy.append([x, y])\r\n gauge_locs.append(loc)\r\n gauge_xy = np.array(gauge_xy)\r\n gauge_locs = np.array(gauge_locs)\r\n return select_and_move_detectors(mesh2d, gauge_xy, gauge_locs, maximum_distance=1e2)\r\n\r\n\r\nUTM_ZONE30 = pyproj.Proj(\r\n proj='utm',\r\n zone=30,\r\n datum='WGS84',\r\n units='m',\r\n errcheck=True)\r\n\r\nLL_WGS84 = pyproj.Proj(proj='latlong', datum='WGS84', errcheck=True)\r\n\r\nif __name__ == \"__main__\":\r\n mesh2d = Mesh(input_file_paths.mesh_file)\r\n locations, names = get_detectors(mesh2d)\r\n if mesh2d.comm.rank == 0: # only processor 0\r\n print_output(\"Found detectors: {}\".format(names))\r\n # write out shape-file\r\n import shapely.geometry\r\n import fiona\r\n import fiona.crs\r\n schema = {'geometry': 'Point', 'properties': {'name': 'str'}}\r\n crs = fiona.crs.from_string(UTM_ZONE30.srs)\r\n with fiona.collection(\"mesh_files/detectors.shp\", \"w\", \"ESRI Shapefile\", schema, crs=crs) as output:\r\n for xy, name in zip(locations, names):\r\n point = shapely.geometry.Point(xy[0], xy[1])\r\n output.write({'properties': {'name': name}, 'geometry': shapely.geometry.mapping(point)})\r\n","sub_path":"detectors.py","file_name":"detectors.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"591802880","text":"import argparse\n\n\nclass Parser():\n def __init__(self):\n self.test = False\n self.initialized = False\n\n def initialize(self, parser):\n parser.add_argument('--name', type=str, default='Ludwig', help='Meine Name')\n parser.add_argument('--faction', type=str, default='Nazi', help='Meine Ehre')\n parser.add_argument('--grade', type=int, default=20, help='Nothing Else')\n self.initialized = True\n return parser\n\n def create_parser(self):\n if not self.initialized:\n parser = argparse.ArgumentParser()\n parser = self.initialize(parser)\n return parser\n\n\nif __name__ == '__main__':\n parser = Parser().create_parser()\n opt, _ = parser.parse_known_args()\n print('name = ', opt.name)\n print('faction = ', opt.faction)\n print('grade = ', opt.grade)","sub_path":"Python/argparse/argparse_sample.py","file_name":"argparse_sample.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"498160783","text":"from sys import path\npath.append(\"/mydata/QIK-Videos/APTED/apted\")\npath.append(\"/mydata/QIK-Videos/QIK_Web/util/\")\n\nimport os\nimport threading\nimport json\nimport time\nfrom threading import Thread, Lock\n\nTHREAD_COUNT = 100\nVIDEO_LIST_FILE = 'QIK_Index_Engine_Results_With_Optimized_Times.txt'\nRESULTS_FILE_PREFIX = 'qik_msrvtt_q_testset_d_trainvalset_ted_weighed_ranked_optimized_times'\n\nqueue = []\nlock = Lock()\nthreadLimiter = threading.BoundedSemaphore()\n\n# Producer Thread.\nclass Producer(Thread):\n def run(self):\n global queue\n\n if os.path.exists(VIDEO_LIST_FILE):\n # Iterating over the images mentioned in the file.\n videos = open(VIDEO_LIST_FILE, \"r\")\n for video in videos:\n # Acquiring the lock before adding the to the queue.\n lock.acquire()\n\n # Adding the file to the queue.\n queue.append(os.fsdecode(video.rstrip()))\n\n # Releasing the lock acquired.\n lock.release()\n\n# Consumer Thread.\nclass Consumer(Thread):\n def run(self):\n global queue\n while True:\n if not queue:\n # Nothing in queue, but consumer will try to consume\n continue\n\n # Acquiring the lock before removing from the queue.\n lock.acquire()\n\n # Fetching the files from the queue.\n file = queue.pop(0)\n\n # Releasing the lock acquired.\n lock.release()\n\n # Instantiate a thread with the file name as the thread name.\n process = Process(name=file)\n process.start()\n time.sleep(1)\n\n\nclass Process(threading.Thread):\n def run(self):\n threadLimiter.acquire()\n try:\n self.exec()\n finally:\n threadLimiter.release()\n\n def exec(self):\n # Getting the complete image path\n line = self.getName().split(\"::\")\n\n # Obtaining the video and response\n query = line[0]\n resp = line[1].replace(\"{'\", \"{\\\"\").replace(\"'}\", \"\\\"}\").replace(\", '\", \", \\\"\").replace(\"', \", \"\\\", \").replace(\": '\", \": \\\"\").replace(\"': \", \"\\\": \").replace(\"['\", \"[\\\"\").replace(\"']\", \"\\\"]\")\n\n # Interpreting the response as a json object\n stored_res = json.loads(resp)\n\n # Obtaining the time data\n scene_detect_time = stored_res['sceneDetectTime']\n captioning_time = stored_res[\"captioningTime\"]\n retrieval_time = stored_res[\"dbRetrievalTime\"]\n ranking_time = stored_res[\"rankingTime\"]\n total_time = scene_detect_time + captioning_time + retrieval_time + ranking_time\n\n # Writing results to the file\n with open(RESULTS_FILE_PREFIX + \".csv\", 'a+') as f:\n f.write(query + \",\" + str(scene_detect_time) + \",\" + str(captioning_time) + \",\" + str(retrieval_time) + \",\" + str(ranking_time) + \",\" + str(total_time) + \"\\n\")\n\n\nif __name__ == \"__main__\":\n # Starting the producer process\n Producer().start()\n\n # Starting the consumer process.\n Consumer().start()","sub_path":"QIK-Videos/Evaluate/MSR_VTT/get_time_data_from_json.py","file_name":"get_time_data_from_json.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"315629938","text":"#########################\r\n######## Imports ########\r\n#########################\r\n\r\nimport pandas as pd\r\n\r\nfrom scipy import linalg, mat, dot\r\n\r\nfrom preprocessing import tokenize, stem\r\n\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer \r\n\r\n\r\n#########################\r\n#### Initializisation ###\r\n#########################\r\n\r\nvectorizer = CountVectorizer()\r\n\r\nmetadata = pd.read_csv('allocine_parser_results.csv', sep=';')\r\ndata_titles = metadata['titre']\r\n\r\n\r\n\r\n#########################\r\n######### CODE ##########\r\n#########################\r\n\r\ndef identify_title(filmAsked):\r\n\r\n titles = pd.concat([data_titles, pd.Series([filmAsked])], ignore_index = True)\r\n n = len(titles)\r\n \r\n ''' Step 1 = Preprocessing without StopWords '''\r\n \r\n new_titles = []\r\n \r\n for index, title in titles.iteritems():\r\n new_title = tokenize(title)\r\n for idx, word in enumerate(new_title):\r\n new_title[idx] = stem(word)\r\n new_title = \" \".join(new_title)\r\n new_titles.append(new_title)\r\n \r\n \r\n ''' Step 2 = TF-IDF matrix building '''\r\n \r\n tfidf_vectorizer = TfidfVectorizer(use_idf=True)\r\n tfidf_vectorizer_vectors = tfidf_vectorizer.fit_transform(new_titles)\r\n \r\n tfidf_matrix = pd.DataFrame(columns=tfidf_vectorizer.get_feature_names())\r\n \r\n for i in range(n):\r\n \r\n vector_tfidfvectorizer = tfidf_vectorizer_vectors[i] \r\n row = vector_tfidfvectorizer.T.todense()\r\n \r\n # Place tf-idf values in a pandas data frame \r\n dfNew = pd.DataFrame(row, index=tfidf_vectorizer.get_feature_names())\r\n tfidf_matrix = tfidf_matrix.append(dfNew.T, ignore_index=True)\r\n \r\n \r\n ''' Step 3 = Cos-similarity computation '''\r\n \r\n cos_similarity = []\r\n \r\n tfidf_list = tfidf_matrix.values.tolist()\r\n \r\n a = mat(tfidf_list[-1])\r\n \r\n for i in range(n-1):\r\n \r\n b = mat(tfidf_list[i])\r\n c = (dot(a,b.T)/linalg.norm(a)/linalg.norm(b)).item()\r\n \r\n cos_similarity.append(c)\r\n \r\n \r\n similarities = pd.Series(cos_similarity)\r\n similarities = similarities.sort_values()\r\n indexes = similarities[-3:].index.tolist()\r\n indexes.reverse()\r\n \r\n expectedFilms = []\r\n \r\n for index in indexes:\r\n expectedFilms.append(titles[index])\r\n \r\n return expectedFilms, indexes\r\n\r\n\r\ndef read_result(index, nameClass):\r\n \r\n return metadata[nameClass][index]\r\n\r\n \r\n\r\n","sub_path":"Retrieve_model__TFIDF/title_detection.py","file_name":"title_detection.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584150148","text":"from services import *\n\nSID_DETECTED = False\n\nclass member:\n def __init__(self, one):\n self.one = one\n def getDeclaration(self, addExtern = True):\n return ''\n def getSID(self):\n return ''\n def getTypedef(self):\n return ''\n def isStatic(self):\n return False\n def getAll(self):\n return self.one\n\nclass func(member):\n def __init__(self, one):\n super().__init__(one)\n self.__parse(self.one)\n\n def __parse(self, text):\n #find body\n bodyStart = text.find('{')\n bodyEnd = findEnd(text, '\\n', (findEnd(text, '\\n}', bodyStart)))\n self.body = text[bodyStart:bodyEnd]\n #find parameters\n parametersStart = text.rfind('(', 0, bodyStart)\n parametersEnd = rfindEnd(text, ')', bodyStart)\n self.parameters = text[parametersStart:parametersEnd]\n #find funcName\n funcNameStart = rfindEnd(text, ' ', parametersStart)\n funcNameEnd = parametersStart\n self.funcName = text[funcNameStart:funcNameEnd]\n self.fatFuncName = camel2SnakeSingle(self.funcName)\n #find funcType\n funcTypeStart = rfindEnd(text, '\\n', funcNameStart)\n funcTypeEnd = funcNameStart\n self.funcType = text[funcTypeStart:funcTypeEnd]\n #find hat\n hatStart = 0\n hatEnd = funcTypeStart\n self.hat = text[hatStart:hatEnd]\n #find SID\n self.sid = self.__detectSid(self.hat)\n #find short description\n self.desc = self.__makeShortDescription(self.hat)\n\n def __makeShortDescription(self, text):\n descStart = findEnd(self.hat, '@Description')\n descEnd = self.hat.find('//--', descStart)\n if (descStart < descEnd) and (descStart != -1) and (descEnd != -1):\n desc = ('// ' + self.hat[descStart:descEnd])\n else:\n desc = '// TODO\\n'\n return deleteDoubles(desc)\n\n def __detectSid(self, text):\n global SID_DETECTED\n sidPosition = text.find('SID')\n if sidPosition != -1:\n SID_DETECTED = True\n sidStart = text.find('0x', sidPosition)\n if (sidStart != -1) and (sidStart - sidPosition < 10):\n sidEnd = sidStart + 4\n return text[sidStart:sidEnd]\n else:\n sidEnd = sidPosition + 10\n return text[sidPosition:sidEnd]\n else:\n return ''\n\n def getSID(self):\n if self.sid != '':\n result = ('#define {0:50} ({1}U)\\n'.format(self.fatFuncName + '_SID', self.sid))\n else:\n result = ''\n return result\n\n def getTypedef(self):\n fType = self.funcType\n fType = fType.replace('static', '')\n fType = fType.replace('const', '')\n fName = self.funcName + 'Ptr_t'\n t = deleteDoubles('typedef {0} (*{1})'.format(fType, fName))\n head = self.funcName + self.funcType\n diffNames = max(len(t) - len(head), len(head) - len(t))\n joiner = ('\\n' + ' ' * diffNames)\n return (t + joiner.join(self.parameters.split('\\n'))+ ';\\n')\n\n def getDeclaration(self, addExtern = True):\n head = self.funcType + self.funcName\n if self.isStatic():\n declaration = (self.desc + head + self.parameters + ';\\n')\n else:\n if addExtern:\n add = 'extern '\n else:\n add = ''\n localParams = self.parameters.replace('\\n', '\\n' + ' ' * len(add))\n declaration = (self.desc + add + head + localParams + ';\\n')\n return declaration\n\n def isStatic(self):\n return ('static' in self.funcType)\n\nclass preprocessor(member):\n def getDeclaration(self, addExtern = True):\n return self.one\n\ndef getAllSIDs(functions):\n text = ''\n if (shortDialog('I\\'ve detected SIDs in comments.\\nDo you want to export them?')):\n text = '\\n// SIDs:\\n'\n for f in functions:\n text += f.getSID()\n return text\n\n@benchmark\ndef parsingFunctions(f):\n text = getCleanText(f)\n f_Array = []\n fCounter = 0\n #find first comment\n startPosition = text.rfind('\\n\\n//', 0, text.find('\\n{'))\n while(1):\n #find preprocessor first\n preStart = text.find('#', startPosition)\n fbodyStart = text.find('\\n{', startPosition)\n #add preprocessor if he first\n if (preStart != -1) and ((preStart < fbodyStart) or (fbodyStart == -1)):\n preEnd = findEnd(text, '\\n', preStart)\n f_Array.append(preprocessor(text[preStart:preEnd]))\n startPosition = preEnd\n #add function\n elif (fbodyStart != -1):\n fCounter += 1\n fbodyEnd = findEnd(text, '\\n}', fbodyStart)\n fbodyEnd = findEnd(text, '\\n', fbodyEnd)\n fhatStart = text.find('//', startPosition)\n if fhatStart != -1:\n f_Array.append(func(text[fhatStart:fbodyEnd]))\n startPosition = fbodyEnd\n #if end of members\n else:\n break\n printLog('Total functions detected: ' + str(fCounter))\n return f_Array\n\ndef prepareToExport(func):\n def wrapped():\n inFile = openFile()\n exFile = createFile('export.c')\n functions = parsingFunctions(inFile)\n\n func(functions, exFile)\n\n inFile.close()\n exFile.close()\n\n return wrapped\n\ndef addSpace(text, space = '\\n'):\n addSpace.added = getattr(addSpace, 'added', True)\n\n if (text.find('#if') != -1):\n text = space + text\n addSpace.added = True\n elif text.find('#endif') != -1:\n addSpace.added = False\n elif addSpace.added:\n addSpace.added = False\n else:\n text = space + text\n addSpace.added = False\n return text\n\n@prepareToExport\ndef exportDeclarations(functions, exFile):\n addGlobal = shortDialog('Export global functions?')\n if addGlobal:\n addEx = shortDialog('Add extern to global?')\n else: \n addEx = False\n addStatic = shortDialog('Export static functions?')\n\n for f in functions:\n if (f.isStatic() and addStatic) or (not f.isStatic() and addGlobal) or \\\n (type(f) is type(preprocessor)):\n exFile.write(addSpace(f.getDeclaration(addExtern = addEx)))\n \n if (SID_DETECTED):\n exFile.write(getAllSIDs(functions))\n printLog('Declarations exported in ' + exFile.name)\n\n@prepareToExport\ndef exportStaticPointers(functions, exFile):\n if shortDialog('Array name \\'StaticFs\\'?'):\n arrayName = 'StaticFs'\n else:\n arrayName = input('Enter your array\\'s name: \\n')\n #typedef void-void\n exFile.write('\\n\\n\\n// Put this into your \\'Module.h\\'\\n')\n exFile.write('typedef void(*ptrToFunct_t)(void);\\n')\n #array generation\n exFile.write('\\n\\n\\n// Put this into bottom of your \\'Module.c\\'\\n')\n exFile.write(SPLITTER + '// Array of (void)(*)(void) pointers to static functions\\n' + SPLITTER)\n exFile.write('ptrToFunct_t {0}[] =\\n{1}\\n'.format(arrayName, '{'))\n counter = 0\n for f in functions:\n if f.isStatic():\n exFile.write(' [{0}] = (ptrToFunct_t){1},\\n'.format(counter, f.funcName))\n counter += 1\n exFile.write('};\\n\\n')\n #declaration of the array\n exFile.write('\\n\\n\\n// Put this into your \\'Module_Getters.h\\'\\n')\n exFile.write(SPLITTER + '// Declarations of global (public) variables\\n' + SPLITTER)\n exFile.write('\\nextern ptrToFunct_t {0}[];\\n'.format(arrayName))\n #typedefs\n exFile.write('\\n\\n\\n// Put this into your \\'Module_Tests.c\\'\\n')\n exFile.write(SPLITTER + '// Declarations of global (public) data types\\n' + SPLITTER)\n for f in functions:\n if f.isStatic():\n exFile.write(f.getTypedef() + '\\n')\n #definitions of static vars\n exFile.write(SPLITTER + '// Definitions of static global (private) variables\\n' + SPLITTER)\n for f in functions:\n if f.isStatic():\n exFile.write('{0:40}{1};\\n'.format('static '+ f.funcName + 'Ptr_t', f.funcName))\n\n exFile.write('\\n\\n\\n// Put this into your \\'TestsInitFunction()\\'\\n')\n counter = 0\n for f in functions:\n if f.isStatic():\n exFile.write('{0:40} = ({1}){2}[{3}];\\n'\\\n .format(f.funcName, f.funcName + 'Ptr_t', arrayName, counter))\n counter += 1\n\n@prepareToExport\ndef exportAllFunctions(functions, exFile):\n for f in functions:\n exFile.write(addSpace(f.getAll(), '\\n\\n\\n'))\n printLog('All functions were exported in ' + exFile.name)","sub_path":"functionsGen.py","file_name":"functionsGen.py","file_ext":"py","file_size_in_byte":8506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"499173735","text":"hid = \"4103261995xxxx3197\"\n\nverify_id = str(hid)[-1]\nleft = hid[0:10]\nright = hid[14:18]\n\nmonth = range(1, 13)\nday = range(1, 32)\n\nfakes = []\nfor mon in month:\n for d in day:\n mm = ''\n dd = ''\n if mon < 10:\n mm = '0' + str(mon)\n else:\n mm = str(mon)\n\n if d < 10:\n dd = '0' + str(d)\n else:\n dd = str(d)\n\n mid = mm + dd\n fake = left + mid + right\n fakes.append(fake)\n\narr = []\nfor i in range(0, 17):\n a = (1 << 17 - i) % 11\n arr.append(a)\n\nfor idcard in fakes:\n\n a = str(idcard)[0:-1]\n\n check_sum = 0\n for (inx, z) in enumerate(a):\n num = int(z)\n check_sum += num * arr[inx]\n\n check_digit = (12 - check_sum % 11) % 11\n\n if check_digit == int(verify_id):\n print(idcard[10:14])\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629056041","text":"import numpy as np\nfrom scipy.integrate import ode\n#from matplotlib import pyplot as plt\n#from matplotlib import animation\n#import pickle\n\nclass flow(object):\n def __init__(self, nx=64, ny=64, lx=1.0e6, ly=2.0e6,\n beta=6.0e-10, kappa=10.0, w=4.0e-6, forcing_mode=(6,9),\n method='dopri5', dt=2*3600,\n initial_amp=1.2e5):\n x = np.linspace(-np.pi, np.pi, nx, endpoint=False)\n y = np.linspace(-np.pi, np.pi, ny, endpoint=False)\n self.xx, self.yy = np.meshgrid(x,y, indexing='ij')\n \n kx = np.fft.fftfreq(nx, lx/nx)\n ky = np.fft.rfftfreq(ny, ly/ny)\n self.kkx, self.kky = np.meshgrid(kx,ky, indexing='ij')\n \n self.ksq = self.kkx**2 + self.kky**2\n self.ksq[0,0] += 1.0e-15\n self.kmax = np.min(np.max(kx), np.max(ky))\n self.kxmax = np.max(kx)\n self.kymax = np.max(ky)\n \n self.nx = nx\n self.ny = ny\n self.lx = lx\n self.ly = ly\n self.beta = beta\n self.kappa = kappa\n self.w = w\n \n self.forcing_mode = forcing_mode\n\n self.psihat = np.zeros_like(self.ksq, dtype=complex)\n\n # should we do random noise instead for initial condition?\n# self.psihat[2,4] = nx*ny*4\n# self.psihat[4,2] = nx*ny\n# self.psi = np.fft.irfft2(self.psihat)\n \n# self.qhat = -self.psihat*self.ksq\n# self.q = np.fft.irfft2(self.qhat)\n\n self.qhat = self.forcing(0.0) * initial_amp\n self.q = np.fft.irfft2(self.qhat)\n self.psihat = self.get_psihat_from_qhat(self.qhat)\n self.psi = np.fft.irfft2(self.psihat)\n\n\n self.integrator = ode(self.rhs).set_integrator(method)\n self.results = [ self.qhat ]\n self.dt = dt\n self.t = 0.0\n\n \n def integrate(self, tf):\n \n if tf < self.t + self.dt:\n print(\"won't integrate backward in time from %f to %f\" %(self.t,tf))\n return\n \n y0 = self.munge(self.qhat)\n self.integrator.set_initial_value(y0, self.t)\n while self.integrator.successful() and self.integrator.t < tf:\n self.integrator.integrate(self.integrator.t + self.dt)\n self.results.append(self.unmunge(self.integrator.y))\n \n self.qhat = self.unmunge(self.integrator.y)\n self.psihat = self.get_psihat_from_qhat(self.qhat)\n self.psi = np.fft.irfft2(self.psihat)\n self.q = np.fft.irfft2(self.qhat)\n self.t = self.integrator.t\n \n return\n \n# def plot_psi(self):\n# return plt.contour(self.xx, self.yy, self.psi)\n \n# def plot_q(self):\n# return plt.contour(self.xx, self.yy, self.q)\n \n \n def get_psihat_from_qhat(self, qhat):\n \"\"\"What it says on the tin. \n \"\"\"\n \n psihat = qhat/self.ksq\n return psihat\n \n def waveterm(self, psihat):\n \"\"\"Compute the beta wave term.\n \n Assume that we start and end in Fourier space.\n \"\"\"\n return self.beta*psihat*self.kkx*(0.0+1.0j)\n \n def dissipation(self, qhat):\n \"\"\"Dissipation term, all in Fourier space.\"\"\"\n \n return self.kappa*qhat*self.ksq\n \n def forcing(self, t):\n \"\"\"Forcing term goes here.\n \n This ought to be random phases into a k-space anulus, but I'll use something simple for now.\n \"\"\"\n fzero = 1.0e-4\n thick = 1.0e3\n famp = self.w * fzero/thick\n\n phases = np.random.uniform(-np.pi, np.pi, size=self.ksq.shape)\n \n forcing = np.zeros_like(self.ksq, dtype=complex)\n forcing[np.abs(self.ksq - self.kmax**2/9) < 3e-11] = famp\n forcing *= (np.cos(phases) + np.sin(phases)*(0.0+1.0j))\n \n return forcing\n \n def nlterm(self, qhat, psihat):\n \"\"\"Compute the jacobian determinant.\"\"\"\n \n psihat_x = psihat*self.kkx*(0.0+1.0j)\n psihat_y = psihat*self.kky*(0.0+1.0j)\n qhat_x = qhat*self.kkx*(0.0+1.0j)\n qhat_y = qhat*self.kky*(0.0+1.0j)\n \n psi_x = np.fft.irfft2(psihat_x)\n psi_y = np.fft.irfft2(psihat_y)\n q_x = np.fft.irfft2(qhat_x)\n q_y = np.fft.irfft2(qhat_y)\n \n jac = psi_x*q_y - psi_y*q_x\n \n jachat = np.fft.rfft2(jac)\n \n # dealias\n jachat[self.kkx > 2/3 * self.kxmax] = 0.0\n jachat[self.kky > 2/3 * self.kymax] = 0.0\n \n return jachat\n \n def rhs(self, arg1, arg2):\n \"\"\"The time derivative, ready for the integrator.\"\"\"\n \n # scipy.ode and scipy.odeint use opposite call signatures\n # so we have to figure out which of the arguments is a float\n # and which is an array\n \n if type(arg1) == type(0.0):\n t = arg1\n q_reshaped = arg2\n else:\n t = arg2\n q_reshaped = arg1\n \n qhat = self.unmunge(q_reshaped)\n \n psihat = self.get_psihat_from_qhat(qhat)\n nlterm = self.nlterm(qhat, psihat)\n waveterm = self.waveterm(psihat)\n dissipation = self.dissipation(qhat)\n forcing = self.forcing(t)\n \n return self.munge(forcing - dissipation + waveterm + nlterm)\n \n def calc_energy(self, psihat):\n uhat = psihat*self.kkx*(0.0+1.0j)\n vhat = psihat*self.kky*(0.0+1.0j)\n \n u = np.fft.irfft2(uhat)\n v = np.fft.irfft2(vhat)\n \n efield = u**2 + v**2\n return np.sum(efield)\n \n def calc_enstrophy(self, qhat):\n q = np.fft.irfft2(qhat)\n return np.sum(q**2)\n \n def munge(self, qhat):\n \"\"\"format a complex k-space field for odeint\"\"\"\n \n r = qhat.real\n i = qhat.imag\n z = np.array([r,i])\n return z.reshape(-1)\n \n def unmunge(self, munged):\n \"\"\"Return the 1d real sequence to its 2d complex state\"\"\"\n \n z = munged.reshape((2,self.nx,int(self.ny/2+1)))\n r = z[0]\n i = z[1]\n return r + (0+1.0j)*i\n \n \n# def animate_results(self, filename, stride=1):\n# fig = plt.figure(figsize=(10,10))\n# ax = plt.axes()\n#\n# plt.xlabel(r'x')\n# plt.ylabel(r'y')\n#\n# def animate(i):\n# qhat = self.results[int(i*stride)]\n# psihat = self.get_psihat_from_qhat(qhat)\n# z = np.fft.irfft2(psihat)\n# ax.clear()\n# cont = plt.contour(self.xx, self.yy, z)\n# return cont\n#\n# anim = animation.FuncAnimation(fig, animate, frames=len(self.results)//stride, blit=False)\n# mywriter = animation.FFMpegWriter()\n# anim.save(filename, bitrate=10000)\n","sub_path":"layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":6740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"33808053","text":"from flask import Flask,render_template,redirect\nfrom flask_pymongo import PyMongo\nimport scrape_mars\n\n#create an instance for Flask\napp=Flask(__name__)\n\n#set up Mongo connection \napp.config[\"MONGO_URI\"]=\"mongodb://localhost:27017/mars_app\"\nmongo= PyMongo(app)\n\n@app.route(\"/\")\ndef index():\n\n mars_dic=mongo.db.mars_dic.find_one()\n return render_template(\"index.html\",mars=mars_dic)\n\n\n@app.route(\"/scrape\")\ndef scrape():\n\n mars_dic=mongo.db.mars_dic\n mars_data=scrape_mars.scrape()\n mars_dic.update({},mars_data,upsert=True)\n return redirect(\"/\",code=302)\n\nif __name__==\"__main__\":\n app.run(debug=True)\n ","sub_path":"Mission_to_Mars/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143763292","text":"class Heap:\r\n def __init__(self):\r\n self.distv=[]\r\n self.vertic=[]\r\n self.length=0\r\n def parent(self,i):\r\n if i==0:\r\n return 0\r\n elif i%2==0:\r\n return (i//2)-1\r\n else:\r\n return i//2\r\n def heapify(self,i):\r\n print(self.distv)\r\n left=2*i+1\r\n right=2*(i+1)\r\n if left<self.length and right<self.length:\r\n if self.distv[left]>self.distv[right]:\r\n x=right\r\n else:\r\n x=left\r\n elif left<self.length and right>=self.length:\r\n x=left\r\n elif right<self.length and left>=self.length:\r\n x=right\r\n else:\r\n return\r\n if self.distv[i]>self.distv[x]:\r\n t=self.distv[i]\r\n self.distv[i]=self.distv[x]\r\n self.distv[x]=t\r\n temp=self.vertic[i]\r\n self.vertic[i]=self.vertic[x]\r\n self.vertic[x]=temp\r\n self.heapify(x)\r\n def Min(self):\r\n return self.distv[0]\r\n def Insert(self,index,val):\r\n self.vertic.append(index)\r\n self.distv.append(val)\r\n self.length+=1\r\n i=self.length-1\r\n while i>0:\r\n p=self.parent(i)\r\n if self.distv[i]<self.distv[p]:\r\n t=self.distv[i]\r\n self.distv[i]=self.distv[p]\r\n self.distv[p]=t\r\n temp=self.vertic[i]\r\n self.vertic[i]=self.vertic[p]\r\n self.vertic[p]=temp\r\n i=p\r\n def Extractmin(self):\r\n t=self.vertic[0]\r\n r=self.distv[0]\r\n self.distv[0]=self.distv[self.length-1]\r\n self.distv[self.length-1]=r\r\n self.distv.pop()\r\n self.length=self.length-1\r\n d=self.vertic[0]\r\n self.vertic[0]=self.vertic[self.length-1]\r\n self.vertic[self.length-1]=d\r\n self.heapify(0)\r\n return t\r\n def update(self,x,y):\r\n i=0\r\n for j in range(self.length):\r\n if self.vertic[j]==x:\r\n self.distv[j]=y\r\n i=j\r\n break\r\n #print(self.distv)\r\n # print(self.vertic)\r\n self.heapify(0)\r\nclass Graph:\r\n def __init__(self):\r\n self.sd=100000\r\n self.pred=None\r\ndef Dijsktras(s,graph,weight,n):\r\n h=Heap()\r\n a[s].sd=0\r\n for j in range(n):\r\n h.Insert(j,a[j].sd)\r\n while len(h.distv)!=0:\r\n q=h.Extractmin()\r\n for r in range(len(graph[q])):\r\n if a[graph[q][r]].sd>weight[q][r]+a[q].sd:\r\n t=weight[q][r]+a[q].sd\r\n a[graph[q][r]].sd=t\r\n h.update(graph[q][r],t)\r\n a[r].pred=r\r\n for k in range(n):\r\n print(k,a[k].sd)\r\nn=int(input(\"enter No. of vertices :\"))\r\na=[None]*n\r\ngraph=[None]*n\r\nweight=[None]*n\r\nfor i in range(n):\r\n a[i]=Graph()\r\n graph[i]=[]\r\n weight[i]=[]\r\ne=int(input(\"enter No. of edges: \"))\r\nprint(\"enter edges\")\r\ni=0\r\nwhile(i<e):\r\n x,y,wei=map(int,input().split())\r\n if x<n and y<n:\r\n graph[x].append(y)\r\n graph[y].append(x)\r\n weight[x].append(wei)\r\n weight[y].append(wei)\r\n else:\r\n print(\"INVALID EDGE, input again \")\r\n i-=1\r\n i+=1\r\nprint(\"Enter a source vertex\")\r\ns=int(input())\r\nDijsktras(s,graph,weight,n)\r\n","sub_path":"Data_Structure_Lab/DfsandshortestPath/Dijsktras.py","file_name":"Dijsktras.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609186586","text":"import json\nfrom sys import argv\n\ndef sortKey(elem):\n return elem[\"country\"]\n\n\nwith open(argv[1]) as inFile:\n data = []\n for line in inFile:\n dic = {}\n line.strip(\"\\n\")\n line = line.split(\"\\t\")\n dic[\"area\"] = float(line[2])\n dic[\"country\"] = line[0]\n dic[\"population\"] = int(line[1])\n data.append(dic)\n \n \ndata.sort(key=sortKey)\n\nwith open(argv[2], \"w\") as outFile:\n json.dump(data, outFile, indent=3, sort_keys=True)\n","sub_path":"Round 6/Task 1/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342976622","text":"# Time: O(n^2)\n# Space: O(1)\n\n# Given an array S of n integers,\n# are there elements a, b, c in S such that a + b + c = 0?\n# Find all unique triplets in the array which gives the sum of zero.\n#\n# Note:\n# Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c)\n# The solution set must not contain duplicate triplets.\n# For example, given array S = {-1 0 1 2 -1 -4},\n#\n# A solution set is:\n# (-1, 0, 1)\n\n# NOTE: choose one element and do a bidirectional sweep with two pointers\n\n\ndef threeSum(nums):\n n = len(nums)\n nums.sort()\n result = []\n Finalresult = ''\n\n for i in range(n):\n #result = ''\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n l, r = i + 1, n - 1\n\n while l < r:\n temp = nums[i] + nums[l] + nums[r]\n if temp == 0:\n result.append([nums[i], nums[l], nums[r]])\n # result += '{},'.format(nums[i])\n # result += '{},'.format(nums[l])\n # result += '{}'.format(nums[r])\n # Finalresult += '{} \\n'.format(result)\n #print(result)\n l += 1\n r -= 1\n while l < r and nums[l] == nums[l - 1]:\n l += 1\n while l < r and nums[r] == nums[r + 1]:\n r -= 1\n elif temp < 0:\n l += 1\n else:\n r -= 1\n #Finalresult += '{}'.format(result)\n #print(Finalresult)\n ans = map(lambda x: ','.join([str(a) for a in x]), result)\n for item in ans:\n Finalresult += '{}\\n'.format(item)\n return Finalresult\n\n\nlist1 = [6, 10, 3, -4, 1, -6, 9]\nprint(threeSum(list1))\n","sub_path":"three-sum.py","file_name":"three-sum.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"515277311","text":"# mqtt_as_timeout.py Implementation of a timeout on publication.\n\n# (C) Copyright 2019 Kevin Köck.\n# Released under the MIT licence.\n\n# This solution detects the case where a publication is delayed by lack of\n# connectivity and cancels it if the delay exceeds a timeout.\n\n# Note that it blocks other attempts at publication while waiting for a PUBACK,\n# counter to the normal operation of the module. A solution capable of handling\n# concurrent qos == 1 publications would require a set instance containing coros.\n\n# It incorporates a workround for the bug in uasyncio V2 whereby cancellation\n# is deferred if a task is waiting on a sleep command.\n# For these reasons it was not included in the mqtt_as module.\n\n# The occurrence of a timeout does not guarantee non-reception of the message:\n# connectivity loss may occur between reception by the broker and reception of\n# CONNACK by the client. However in this case the message would be received in\n# a timely fashion.\n\nfrom mqtt_as import MQTTClient as _MQTTClient\nimport time\nimport uasyncio as asyncio\n\nclass MQTTClient(_MQTTClient):\n _pub_coro = None\n\n # Await broker connection. Subclassed to reduce canceling time from 1s to 50ms\n async def _connection(self):\n while not self._isconnected:\n await asyncio.sleep_ms(50)\n\n async def _publishTimeout(self, topic, msg, retain, qos):\n try:\n await super().publish(topic, msg, retain, qos)\n except asyncio.CancelledError:\n pass\n finally:\n self._pub_coro = None\n\n async def publish(self, topic, msg, retain=False, qos=0, timeout=None):\n coro = None\n start = time.ticks_ms()\n while timeout is None or time.ticks_diff(time.ticks_ms(), start) < timeout:\n if self._pub_coro is None and coro is None:\n coro = self._publishTimeout(topic, msg, retain, qos)\n asyncio.get_event_loop().create_task(coro)\n self._pub_coro = coro\n elif coro is not None:\n if self._pub_coro != coro:\n return # published\n await asyncio.sleep_ms(20)\n if coro is not None:\n async with self.lock:\n asyncio.cancel(coro)\n return\n","sub_path":"mqtt_as/mqtt_as_timeout.py","file_name":"mqtt_as_timeout.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"525354185","text":"from models.model_gen import ModelGen\nfrom tensorflow.keras import layers\nfrom datetime import datetime\nimport tensorflow as tf\n\n\nclass CnnModel(ModelGen):\n \n def __init__(self):\n super(CnnModel, self).__init__()\n self.conv1 = layers.Conv2D(filters=16,\n kernel_size=9,\n input_shape=(32, 128, 128, 1),\n data_format='channels_last',\n activation='relu',\n name='conv1'\n )\n self.conv2 = layers.Conv2D(32, 5, data_format='channels_last', activation='relu', name='conv2')\n self.conv3 = layers.Conv2D(64, 7, data_format='channels_last', activation='relu', name='conv3')\n self.conv4 = layers.Conv2D(128, 5, data_format='channels_last', activation='relu', name='conv4')\n self.dropout1 = layers.Dropout(0.2, name='drop1')\n self.dropout2 = layers.Dropout(0.2, name='drop2')\n self.dropout3 = layers.Dropout(0.2, name='drop3')\n self.dropout4 = layers.Dropout(0.2, name='drop4')\n self.max_pooling1 = layers.MaxPool2D(2, name='pooling1')\n self.max_pooling2 = layers.MaxPool2D(2, name='pooling2')\n self.max_pooling3 = layers.MaxPool2D(2, name='pooling3')\n self.max_pooling4 = layers.MaxPool2D(2, name='pooling4')\n self.flatten = layers.Flatten(name='flat')\n self.dense = layers.Dense(4, activation='softmax', name='dense')\n \n def call(self, inputs, training=None, mask=None):\n \n inputs = self.conv1(inputs)\n inputs = self.max_pooling1(inputs)\n inputs = self.dropout1(inputs)\n \n inputs = self.conv2(inputs)\n inputs = self.max_pooling2(inputs)\n inputs = self.dropout2(inputs)\n \n inputs = self.conv3(inputs)\n inputs = self.max_pooling3(inputs)\n inputs = self.dropout3(inputs)\n \n inputs = self.conv4(inputs)\n inputs = self.max_pooling4(inputs)\n inputs = self.dropout4(inputs)\n \n inputs = self.flatten(inputs)\n inputs = self.dense(inputs)\n \n return inputs\n\n @property\n def cbs(self):\n cp_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath='saved_params/cnn/checkpoints/{epoch:04d}_ckpt',\n verbose=1,\n save_weights_only=True,\n )\n tb_callback = tf.keras.callbacks.TensorBoard(\n log_dir='saved_params/cnn/tensorboard/' + datetime.now().strftime(\"%Y%m%d-%H%M%S\"),\n histogram_freq=20,\n write_graph=True,\n update_freq='batch'\n )\n es_callback = tf.keras.callbacks.EarlyStopping(\n monitor='accuracy',\n min_delta=0.01,\n patience=15,\n restore_best_weights=True\n )\n \n cbs = [cp_callback, tb_callback, es_callback]\n return cbs\n","sub_path":"models/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"492906904","text":"from operator import itemgetter, attrgetter\nimport sys\nimport boto3\n\ndef get_latest_ami():\n images = []\n ec2_c = boto3.client('ec2')\n #resp = ec2_c.describe_images(Owners=['amazon'], Filters=[{'Name': 'owner-alias', 'Values': ['amazon']}, {'Name': 'name', 'Values': ['amzn2-ami-hvm*2020*gp2']}, {'Name': 'is-public', 'Values': ['true']}, {'Name': 'virtualization-type', 'Values': ['hvm']}, {'Name': 'architecture', 'Values': ['x86_64']}])\n resp = ec2_c.describe_images(Owners=['amazon'], Filters=[{'Name': 'owner-alias', 'Values': ['amazon']}, {'Name': 'name', 'Values': ['*ecs-hvm*']}, {'Name': 'is-public', 'Values': ['true']}, {'Name': 'virtualization-type', 'Values': ['hvm']}, {'Name': 'architecture', 'Values': ['x86_64']}])\n for i in resp['Images']:\n images.append((i['ImageId'], i['CreationDate']))\n images2 = sorted(images, key=itemgetter(1), reverse=True)\n ami_id = images2[0][0]\n #print(images2[0][0], images2[0][1])\n #print(images2)\n return ami_id\n\ndef lets_createlt(myawsvpc, ami_id, key_name):\n mysg_id = None\n mysubnets = []\n mysubnets_tags = {}\n myroutetables = []\n ec2_c = boto3.client('ec2')\n for s in myawsvpc.security_groups.all():\n mysg_id = s.id\n for s in myawsvpc.subnets.all():\n mysubnets.append(s.id)\n for r in myawsvpc.route_tables.all():\n myroutetables.append(r.route_table_id)\n resp = ec2_c.describe_subnets(SubnetIds=mysubnets)\n for s in resp['Subnets']:\n mysubnets_tags.update({s['SubnetId']: s['Tags']})\n #print(mysubnets_tags[mysubnets[0]][0]['Value'])\n #for i in mysubnets:\n for k, v in mysubnets_tags.items():\n #print(k, v)\n if 'Pri' in v[0]['Value']:\n iam_profile = 'EC2BackEndProfile'\n subnetid = k\n else:\n iam_profile = 'EC2FrontEndProfile'\n subnetid = k\n resp = ec2_c.create_launch_template(\n LaunchTemplateData={\n 'ImageId': ami_id,\n 'InstanceType': 't3.large',\n 'IamInstanceProfile': {\n #'Arn':,\n 'Name': iam_profile\n },\n #'SecurityGroupIds': [mysg_id],\n 'KeyName': key_name,\n 'Monitoring': {'Enabled': True},\n 'NetworkInterfaces': [\n {\n 'DeviceIndex': 0,\n 'Groups': [mysg_id],\n 'SubnetId': subnetid\n }\n ],\n 'TagSpecifications': [\n {\n 'ResourceType': 'instance',\n 'Tags': [\n {\n 'Key': 'Name',\n 'Value': 'I-'+v[0]['Value'][8:len(v[0]['Value'])]\n #'Value': 'Instance'+mysubnets_tags[i][0]['Value'][9:len(mysubnets_tags[i][0]['Value'])]\n }\n ]\n }\n ]\n },\n LaunchTemplateName='MyECS' + v[0]['Value'] + 'LaunchTemplate',\n VersionDescription='MyECS' + v[0]['Value'] + 'LaunchTemplateV1',\n #LaunchTemplateName=mysubnets_tags[i][0]['Value'] + 'LaunchTemplate',\n #VersionDescription=mysubnets_tags[i][0]['Value'] + 'LaunchTemplateV1',\n )\n launch_template_id = resp['LaunchTemplate']['LaunchTemplateId']\n print(launch_template_id)\n\ndef main():\n myvpcid = sys.argv[1]\n ec2 = boto3.resource('ec2')\n ami_id = get_latest_ami()\n print(ami_id)\n key_name = 'gregkey'\n myawsvpc = ec2.Vpc(myvpcid)\n lets_createlt(myawsvpc, ami_id, key_name)\n\nif __name__ == '__main__':\n main()\n","sub_path":"myaws_ec2_launch_template.py","file_name":"myaws_ec2_launch_template.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"466276137","text":"#!/usr/bin/env python3\n\r\nimport json\r\nimport os\r\nimport time\r\nimport re\r\nimport sys\r\nimport socket\r\nfrom datetime import datetime\r\nstate = 0\r\npre_state = 0\r\n\r\ndef is_connected():\r\n try:\r\n # connect to the host -- tells us if the host is actually\r\n # reachable\r\n socket.create_connection((\"www.google.com\", 80))\r\n return True\r\n except OSError:\r\n pass\r\n return False\r\n \r\n\r\ntime.sleep(10)\r\n \r\nwhile(1):\r\n if(is_connected()):\r\n state = 1\r\n else:\r\n state = 0\r\n \r\n if state != pre_state:\r\n pre_state = state\r\n time.sleep(0.5)\r\n #restart python server\r\n print(\"[WARN] Restart TFiServer at :: \", datetime.now(),flush=True)\r\n os.system('sudo systemctl stop TFiServer.service')\r\n time.sleep(0.5)\r\n os.system('sudo systemctl start TFiServer.service')\r\n time.sleep(2)","sub_path":"Diag_system.py","file_name":"Diag_system.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397681180","text":"import boto3\nimport time\nfrom botocore.client import ClientError\nfrom datetime import datetime, timedelta, tzinfo\n\nrds = boto3.client('rds')\n\nclass JST(tzinfo):\n def utcoffset(self, dt):\n return timedelta(hours=9)\n def dst(self, dt):\n return timedelta(0)\n def tzname(self, dt):\n return 'JST'\n\ndef create_snapshot(prefix, instanceid):\n snapshotid = \"-\".join([prefix, datetime.now(tz=JST()).strftime(\"%Y-%m-%dT%H%M\")])\n \n for i in range(0, 5):\n try:\n snapshot = rds.create_db_snapshot(\n DBSnapshotIdentifier=snapshotid,\n DBInstanceIdentifier=instanceid\n )\n return\n except ClientError as e:\n print(str(e))\n time.sleep(1)\n\ndef delete_snapshots(prefix, days):\n snapshots = rds.describe_db_snapshots()\n now = datetime.utcnow().replace(tzinfo=None)\n for snapshot in snapshots['DBSnapshots']:\n # creating snapshot\n if not snapshot.has_key('SnapshotCreateTime'):\n continue\n \n delta = now - snapshot['SnapshotCreateTime'].replace(tzinfo=None)\n if snapshot['DBSnapshotIdentifier'].startswith(prefix) and delta.days >= days:\n rds.delete_db_snapshot(DBSnapshotIdentifier=snapshot['DBSnapshotIdentifier'])\n\ndef lambda_handler(event, context):\n delete_days = 1\n snapshot_prefix = \"manually-snapshot-xxx\"\n instances = [\"xxx-db\"]\n \n for instance in instances:\n create_snapshot(snapshot_prefix, instance)\n \n delete_snapshots(snapshot_prefix, delete_days)\n","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641081106","text":"# coding: utf-8\nfrom datetime import datetime\nfrom flask import Blueprint, render_template, request, json, get_template_attribute, g, redirect, url_for, abort, \\\n current_app\nfrom ..models import db, Topic, Question, QuestionTopic, FollowTopic, TopicWikiContributor, UserTopicStatistic, \\\n PublicEditLog, TOPIC_EDIT_KIND, Answer, TopicSynonym, UserFeed, ApplyTopicDeletion, HomeFeed, HOME_FEED_KIND\nfrom ..utils.permissions import UserPermission, AdminPermission\nfrom ..utils.helpers import absolute_url_for, text_diff\nfrom ..utils._qiniu import qiniu\nfrom ..utils.decorators import jsonify\nfrom ..forms import AdminTopicForm\n\nbp = Blueprint('topic', __name__)\n\nTOPICS_PER = 45\n\n\n@bp.route('/topic/square')\ndef square():\n \"\"\"话题广场\"\"\"\n config = current_app.config\n\n product_topic = Topic.query.get_or_404(config.get('PRODUCT_TOPIC_ID'))\n product_descendant_topics = product_topic.descendant_topics.order_by(Topic.avg.desc())\n product_total = product_descendant_topics.count()\n\n organization_topic = Topic.query.get_or_404(config.get('ORGANIZATION_TOPIC_ID'))\n organization_descendant_topics = organization_topic.descendant_topics.order_by(Topic.avg.desc())\n organization_total = organization_descendant_topics.count()\n\n position_topic = Topic.query.get_or_404(config.get('POSITION_TOPIC_ID'))\n position_descendant_topics = position_topic.descendant_topics.order_by(Topic.avg.desc())\n position_total = position_descendant_topics.count()\n\n skill_topic = Topic.query.get_or_404(config.get('SKILL_TOPIC_ID'))\n skill_descendant_topics = skill_topic.descendant_topics.order_by(Topic.avg.desc())\n skill_total = skill_descendant_topics.count()\n\n other_descendant_topics = Topic.other_topics()\n other_total = other_descendant_topics.count()\n\n return render_template('topic/square.html', per=TOPICS_PER,\n product_topic=product_topic,\n product_descendant_topics=product_descendant_topics.limit(TOPICS_PER),\n product_total=product_total,\n organization_topic=organization_topic,\n organization_descendant_topics=organization_descendant_topics.limit(TOPICS_PER),\n organization_total=organization_total,\n position_topic=position_topic,\n position_descendant_topics=position_descendant_topics.limit(TOPICS_PER),\n position_total=position_total,\n skill_topic=skill_topic,\n skill_descendant_topics=skill_descendant_topics.limit(TOPICS_PER),\n skill_total=skill_total,\n other_descendant_topics=other_descendant_topics.limit(TOPICS_PER),\n other_total=other_total)\n\n\n@bp.route('/topic/loading_topics_in_square', methods=['POST'])\n@jsonify\ndef loading_topics_in_square():\n \"\"\"在话题广场\"\"\"\n config = current_app.config\n offset = request.args.get('offset', type=int)\n _type = request.args.get('type', 'product')\n\n if not offset:\n return {'result': False}\n\n if _type == 'product':\n descendant_topics = Topic.query.get_or_404(config.get('PRODUCT_TOPIC_ID')).descendant_topics\n elif _type == 'organization':\n descendant_topics = Topic.query.get_or_404(config.get('ORGANIZATION_TOPIC_ID')).descendant_topics\n elif _type == 'position':\n descendant_topics = Topic.query.get_or_404(config.get('POSITION_TOPIC_ID')).descendant_topics\n elif _type == 'skill':\n descendant_topics = Topic.query.get_or_404(config.get('SKILL_TOPIC_ID')).descendant_topics\n else:\n descendant_topics = Topic.other_topics()\n\n descendant_topics = descendant_topics.order_by(Topic.avg.desc()).limit(TOPICS_PER).offset(offset)\n count = descendant_topics.count()\n macro = get_template_attribute(\"macros/_topic.html\", \"render_topics\")\n return {'result': True, 'html': macro(descendant_topics), 'count': count}\n\n\n@bp.route('/topic/query', methods=['POST'])\n@UserPermission()\n@jsonify\ndef query():\n \"\"\"查询话题\"\"\"\n q = request.form.get('q')\n limit = request.form.get('limit', type=int) # 话题个数限制\n with_create = request.form.get('create') == 'true' # 当找不到名称完全匹配的topic时,是否返回创建选项\n if q:\n topics, _, _ = Topic.query_from_es(q, page=1, per_page=10)\n topics = [topic for topic in topics if topic.merge_to_topic_id is None] # 不显示被合并的话题\n if limit:\n topics = topics[:limit]\n topics_data = [{'name': topic.name, 'id': topic.id, 'avatar_url': topic.avatar_url,\n 'followers_count': topic.followers_count} for topic in topics]\n if with_create:\n exact_topic = Topic.query.filter(Topic.name == q).first() is not None\n if not exact_topic:\n topics_data.insert(0, {'name': q, 'create': True})\n return topics_data\n else:\n return {[]}\n\n\nTOPIC_FANTASTIC_ANSWERS_PER = 15\n\n\n@bp.route('/topic/<int:uid>')\ndef view(uid):\n \"\"\"话题详情页\"\"\"\n topic = Topic.query.get_or_404(uid)\n need_redirect = request.args.get('redirect', type=int)\n from_id = request.args.get('from_id', type=int)\n if from_id:\n from_topic = Topic.query.get_or_404(from_id)\n else:\n from_topic = None\n if topic.merge_to_topic_id and need_redirect != 0:\n return redirect(url_for('.view', uid=topic.merge_to_topic_id, from_id=topic.id))\n answers = topic.all_answers.order_by(Answer.score.desc())\n total = answers.count()\n return render_template('topic/view.html', topic=topic, answers=answers.limit(TOPIC_FANTASTIC_ANSWERS_PER),\n from_topic=from_topic, total=total, per=TOPIC_FANTASTIC_ANSWERS_PER)\n\n\n@bp.route('/topic/<int:uid>/loading_fantastic_answers', methods=['POST'])\n@UserPermission()\n@jsonify\ndef loading_fantastic_answers(uid):\n \"\"\"加载话题下的精彩回答\"\"\"\n topic = Topic.query.get_or_404(uid)\n offset = request.args.get('offset', type=int)\n if not offset:\n return {'result': False}\n\n answers = topic.all_answers.order_by(Answer.score.desc()).limit(TOPIC_FANTASTIC_ANSWERS_PER).offset(offset)\n count = answers.count()\n macro = get_template_attribute(\"macros/_topic.html\", \"render_topic_fantastic_answers\")\n return {'result': True, 'html': macro(answers, topic), 'count': count}\n\n\n@bp.route('/topic/<int:uid>/rank')\ndef rank(uid):\n \"\"\"话题榜单\"\"\"\n topic = Topic.query.get_or_404(uid)\n page = request.args.get('page', 1, int)\n experts = UserTopicStatistic.query. \\\n filter(UserTopicStatistic.topic_id == uid,\n UserTopicStatistic.score != 0). \\\n order_by(UserTopicStatistic.week_score.desc()).paginate(page, 15)\n return render_template('topic/rank.html', topic=topic, experts=experts)\n\n\n@bp.route('/topic/<int:uid>/wiki')\ndef wiki(uid):\n \"\"\"话题wiki\"\"\"\n topic = Topic.query.get_or_404(uid)\n return render_template('topic/wiki.html', topic=topic)\n\n\n@bp.route('/topic/<int:uid>/admin', methods=['POST', 'GET'])\n@UserPermission()\ndef admin(uid):\n \"\"\"话题管理\"\"\"\n topic = Topic.query.get_or_404(uid)\n merged_topics = Topic.query.filter(Topic.merge_to_topic_id == uid)\n uptoken = qiniu.generate_token(policy={\n 'callbackUrl': absolute_url_for('.update_avatar'),\n 'callbackBody': \"id=%d&key=$(key)\" % uid\n })\n return render_template('topic/admin.html', topic=topic, uptoken=uptoken, merged_topics=merged_topics)\n\n\nALL_QUESTIONS_PER = 15\n\n\n@bp.route('/topic/<int:uid>/questions')\ndef questions(uid):\n \"\"\"话题下的全部问题\"\"\"\n topic = Topic.query.get_or_404(uid)\n questions = topic.all_questions\n total = questions.count()\n return render_template('topic/questions.html', topic=topic, questions=questions.limit(ALL_QUESTIONS_PER),\n total=total, per=ALL_QUESTIONS_PER)\n\n\n@bp.route('/topic/<int:uid>/loading_all_questions', methods=['POST'])\n@UserPermission()\n@jsonify\ndef loading_all_questions(uid):\n \"\"\"加载话题下的全部问题\"\"\"\n topic = Topic.query.get_or_404(uid)\n offset = request.args.get('offset', type=int)\n if not offset:\n return {'result': False}\n\n questions = topic.all_questions.limit(ALL_QUESTIONS_PER).offset(offset)\n count = questions.count()\n macro = get_template_attribute(\"macros/_topic.html\", \"render_all_questions\")\n return {'result': True, 'html': macro(questions, topic), 'count': count}\n\n\nWAITING_FOR_ANSWER_QUESTIONS_PER = 15\n\n\n@bp.route('/topic/<int:uid>/waiting')\ndef waiting_for_answer(uid):\n \"\"\"话题下等待回答的问题\"\"\"\n topic = Topic.query.get_or_404(uid)\n questions = topic.all_questions.filter(Question.answers_count == 0)\n total = questions.count()\n\n return render_template('topic/waiting_for_answer.html', topic=topic,\n questions=questions.limit(WAITING_FOR_ANSWER_QUESTIONS_PER),\n total=total, per=WAITING_FOR_ANSWER_QUESTIONS_PER)\n\n\n@bp.route('/topic/<int:uid>/loading_waiting_for_answer_questions', methods=['POST'])\n@UserPermission()\n@jsonify\ndef loading_waiting_for_answer_questions(uid):\n \"\"\"加载话题下的待回答问题\"\"\"\n topic = Topic.query.get_or_404(uid)\n offset = request.args.get('offset', type=int)\n if not offset:\n return {'result': False}\n\n questions = topic.all_questions.filter(Question.answers_count == 0). \\\n limit(WAITING_FOR_ANSWER_QUESTIONS_PER).offset(offset)\n count = questions.count()\n macro = get_template_attribute(\"macros/_topic.html\", \"render_topic_waiting_for_answer_questions\")\n return {'result': True, 'html': macro(questions, topic), 'count': count}\n\n\n@bp.route('/topic/<int:uid>/logs')\ndef logs(uid):\n \"\"\"话题日志\"\"\"\n topic = Topic.query.get_or_404(uid)\n return render_template('topic/logs.html', topic=topic)\n\n\n@bp.route('/topic/<int:uid>/add_parent_topic', methods=['POST'])\n@UserPermission()\n@jsonify\ndef add_parent_topic(uid):\n \"\"\"添加直接父话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n parent_topic_id = request.form.get('parent_topic_id', type=int)\n name = request.form.get('name', '').strip()\n config = current_app.config\n NC_TOPIC_ID = config.get('NC_TOPIC_ID')\n\n if topic.parent_topics_locked or (parent_topic_id is None and name == ''):\n return {'result': False}\n\n if parent_topic_id:\n parent_topic = Topic.query.get_or_404(parent_topic_id)\n else:\n parent_topic = Topic.get_by_name(name, g.user.id, create_if_not_exist=True)\n\n if parent_topic.child_topics_locked:\n return {'result': False}\n\n # 不允许添加以下话题为该话题的直接父话题:\n # 1. 自己\n # 2. 直接父话题\n # 3. 子孙话题\n if parent_topic.id == topic.id \\\n or parent_topic.id in topic.descendant_topics_id_list \\\n or parent_topic.id in topic.parent_topics:\n return {'result': False}\n\n # 若该话题只有一个父话题“未分类”,则将其移除\n parent_topics_id_list = topic.parent_topics_id_list\n if len(parent_topics_id_list) == 1 and parent_topics_id_list[0] == NC_TOPIC_ID and parent_topic.id != NC_TOPIC_ID:\n topic.remove_parent_topic(NC_TOPIC_ID)\n\n topic.add_parent_topic(parent_topic.id)\n\n # MERGE: 若父话题被合并到其他话题,则也将此话题作为子话题添加\n if parent_topic.merge_to_topic_id:\n parent_topic.merge_to_topic.add_child_topic(topic.id, from_merge=True)\n\n # 子话题 log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_PARENT_TOPIC, topic_id=uid, user_id=g.user.id,\n after=parent_topic.name, after_id=parent_topic.id)\n db.session.add(log)\n\n # 父话题 log\n parent_topic_log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_CHILD_TOPIC, topic_id=parent_topic.id,\n user_id=g.user.id, after=topic.name, after_id=uid)\n db.session.add(parent_topic_log)\n\n db.session.commit()\n\n macro = get_template_attribute('macros/_topic.html', 'parent_topic_edit_wap')\n return {'result': True, 'html': macro(parent_topic)}\n\n\n@bp.route('/topic/<int:uid>/remove_parent_topic/<int:parent_topic_id>', methods=['POST'])\n@UserPermission()\n@jsonify\ndef remove_parent_topic(uid, parent_topic_id):\n \"\"\"删除直接父话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n parent_topic = Topic.query.get_or_404(parent_topic_id)\n\n if topic.parent_topics_locked or parent_topic.child_topics_locked:\n return {'result': False}\n\n topic.remove_parent_topic(parent_topic_id)\n\n # MERGE: 若父话题被合并到其他话题,则也将此话题作为子话题添加\n if parent_topic.merge_to_topic_id:\n parent_topic.merge_to_topic.remove_child_topic(topic.id, from_merge=True)\n\n # 子话题 log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_PARENT_TOPIC, topic_id=uid, user_id=g.user.id,\n before=parent_topic.name, before_id=parent_topic_id)\n db.session.add(log)\n\n # 父话题 log\n parent_topic_log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_CHILD_TOPIC, topic_id=parent_topic.id,\n user_id=g.user.id, before=topic.name, before_id=uid)\n db.session.add(parent_topic_log)\n\n db.session.commit()\n\n return {'result': True}\n\n\n@bp.route('/topic/<int:uid>/add_child_topic', methods=['POST'])\n@UserPermission()\n@jsonify\ndef add_child_topic(uid):\n \"\"\"添加直接子话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n child_topic_id = request.form.get('child_topic_id', type=int)\n name = request.form.get('name', '').strip()\n config = current_app.config\n NC_TOPIC_ID = config.get('NC_TOPIC_ID')\n\n if topic.child_topics_locked or (child_topic_id is None and name == ''):\n return {'result': False}\n\n if child_topic_id:\n child_topic = Topic.query.get_or_404(child_topic_id)\n else:\n child_topic = Topic.get_by_name(name, g.user.id, create_if_not_exist=True)\n\n if child_topic.parent_topics_locked:\n return {'result': False}\n\n # 不允许以下的话题添加为该话题的直接子话题\n # 1. 自己\n # 2. 直接子话题\n # 3. 祖先话题\n if child_topic_id == uid \\\n or child_topic_id in topic.ancestor_topics_id_list \\\n or child_topic_id in topic.child_topics_id_list:\n return {'result': False}\n\n # 若子话题只有一个父话题“未分类”,则将其移除\n parent_topics_id_list = child_topic_id.parent_topics_id_list\n if len(parent_topics_id_list) == 1 and parent_topics_id_list[0] == NC_TOPIC_ID and topic.id != NC_TOPIC_ID:\n child_topic.remove_parent_topic(NC_TOPIC_ID)\n\n topic.add_child_topic(child_topic.id)\n\n # MERGE: 若该话题被合并到其他话题,则也进行子话题添加\n if topic.merge_to_topic_id:\n topic.merge_to_topic.add_child_topic(child_topic.id, from_merge=True)\n\n # 父话题 log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_CHILD_TOPIC, topic_id=uid, user_id=g.user.id,\n after=child_topic.name, after_id=child_topic.id)\n db.session.add(log)\n\n # 子话题 log\n child_topic_log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_PARENT_TOPIC, topic_id=child_topic.id, user_id=g.user.id,\n after=topic.name, after_id=uid)\n db.session.add(child_topic_log)\n\n db.session.commit()\n\n macro = get_template_attribute('macros/_topic.html', 'child_topic_edit_wap')\n return {'result': True, 'html': macro(child_topic)}\n\n\n@bp.route('/topic/<int:uid>/remove_child_topic/<int:child_topic_id>', methods=['POST'])\n@UserPermission()\n@jsonify\ndef remove_child_topic(uid, child_topic_id):\n \"\"\"删除直接子话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n child_topic = Topic.query.get_or_404(child_topic_id)\n\n if topic.child_topics_locked or child_topic.parent_topics_locked:\n return {'result': False}\n\n topic.remove_child_topic(child_topic_id)\n\n # MERGE: 若该话题被合并到其他话题,则也进行子话题添加\n if topic.merge_to_topic_id:\n topic.merge_to_topic.remove_child_topic(child_topic.id, from_merge=True)\n\n # 父话题 log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_CHILD_TOPIC, topic_id=uid, user_id=g.user.id,\n before=child_topic.name, before_id=child_topic_id)\n db.session.add(log)\n\n # 子话题 log\n child_topic_log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_PARENT_TOPIC, topic_id=child_topic.id,\n user_id=g.user.id, before=topic.name, before_id=uid)\n db.session.add(child_topic_log)\n\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/get_by_name/<string:name>', methods=['POST'])\n@UserPermission()\n@jsonify\ndef get_by_name(name):\n \"\"\"通过name获取话题,若不存在则创建\"\"\"\n topic = Topic.get_by_name(name, g.user.id, create_if_not_exist=True)\n return {'id': topic.id, 'name': topic.name, 'followers_count': topic.followers_count}\n\n\n@bp.route('/topic/<int:uid>/follow', methods=['POST'])\n@UserPermission()\n@jsonify\ndef follow(uid):\n \"\"\"关注 & 取消关注话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n follow_topic = FollowTopic.query.filter(FollowTopic.topic_id == uid,\n FollowTopic.user_id == g.user.id).first()\n # 取消关注\n if follow_topic:\n db.session.delete(follow_topic)\n topic.followers_count -= 1\n db.session.add(topic)\n\n # MERGE: 若该话题合并到其他话题,则也同时取消关注\n if topic.merge_to_topic_id:\n follow_merge_to_topic = topic.merge_to_topic.followers.filter(FollowTopic.user_id == g.user.id,\n FollowTopic.from_merge).first()\n db.session.delete(follow_merge_to_topic)\n topic.merge_to_topic.followers_count -= 1\n db.session.add(topic.merge_to_topic)\n\n # HOME FEED: 从首页 feed 中删除与此话题相关的条目\n for feed in g.user.home_feeds.filter(HomeFeed.topic_id == uid,\n HomeFeed.kind == HOME_FEED_KIND.FANTASTIC_ANSWER_FROM_FOLLOWED_TOPIC):\n db.session.delete(feed)\n\n db.session.commit()\n\n return {'result': True, 'followed': False, 'followers_count': topic.followers_count}\n else:\n # 关注\n follow_topic = FollowTopic(topic_id=uid, user_id=g.user.id)\n db.session.add(follow_topic)\n\n topic.followers_count += 1\n db.session.add(topic)\n\n # MERGE: 若该话题合并到其他话题,则也同时关注\n if topic.merge_to_topic_id:\n follow_merge_to_topic = topic.merge_to_topic.followers.filter(FollowTopic.user_id == g.user.id).first()\n if not follow_merge_to_topic:\n follow_merge_to_topic = FollowTopic(topic_id=topic.merge_to_topic_id, user_id=g.user.id,\n from_merge=True)\n db.session.add(follow_merge_to_topic)\n topic.merge_to_topic.followers_count += 1\n db.session.add(topic.merge_to_topic)\n\n # USER FEED: 关注话题\n UserFeed.follow_topic(g.user, topic)\n\n # HOME FEED: 向首页 feed 中插入该话题的精彩回答 10 条\n for answer in topic.all_answers.filter(Answer.fantastic).order_by(Answer.created_at.desc()).limit(5):\n home_feed = g.user.home_feeds.filter(HomeFeed.kind == HOME_FEED_KIND.FANTASTIC_ANSWER_FROM_FOLLOWED_TOPIC,\n HomeFeed.answer_id == answer.id).first()\n if not home_feed:\n home_feed = HomeFeed(kind=HOME_FEED_KIND.FANTASTIC_ANSWER_FROM_FOLLOWED_TOPIC, answer_id=answer.id,\n user_id=g.user.id, topic_id=topic.id)\n db.session.add(home_feed)\n\n db.session.commit()\n\n return {'result': True, 'followed': True, 'followers_count': topic.followers_count}\n\n\n@bp.route('/topic/<int:uid>/add_synonym', methods=['POST'])\n@jsonify\ndef add_synonym(uid):\n \"\"\"添加话题同义词\"\"\"\n topic = Topic.query.get_or_404(uid)\n synonym = request.form.get('synonym')\n if synonym:\n topic_synonym = topic.synonyms.filter(TopicSynonym.synonym == synonym).first()\n if not topic_synonym:\n topic_synonym = TopicSynonym(synonym=synonym)\n topic.synonyms.append(topic_synonym)\n db.session.add(topic)\n\n # log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_SYNONYM, after=synonym,\n user_id=g.user.id, topic_id=uid)\n db.session.add(log)\n db.session.commit()\n topic.save_to_es()\n macro = get_template_attribute('macros/_topic.html', 'topic_synonym_edit_wap')\n return {'result': True, 'html': macro(topic_synonym)}\n else:\n return {'result': False}\n else:\n return {'result': False}\n\n\n@bp.route('/topic/synonym/<int:uid>/remove', methods=['POST'])\n@jsonify\ndef remove_synonym(uid):\n \"\"\"移除话题同义词\"\"\"\n topic_synonym = TopicSynonym.query.get_or_404(uid)\n\n # log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_SYNONYM, before=topic_synonym.synonym,\n user_id=g.user.id, topic_id=topic_synonym.topic_id)\n db.session.add(log)\n db.session.delete(topic_synonym)\n topic_synonym.topic.save_to_es()\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/<int:uid>/update_experience', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_experience(uid):\n \"\"\"更新当前用户在该话题下的话题经验\"\"\"\n topic = Topic.query.get_or_404(uid)\n experience = request.form.get('experience', '')\n from_compose = request.form.get('compose', type=int) == 1\n\n statistic = UserTopicStatistic.query.filter(UserTopicStatistic.topic_id == uid,\n UserTopicStatistic.user_id == g.user.id).first()\n if statistic:\n statistic.experience = experience\n else:\n statistic = UserTopicStatistic(topic_id=uid, user_id=g.user.id, experience=experience)\n db.session.add(statistic)\n\n if not g.user.has_selected_expert_topics:\n for expert in g.user.expert_topics:\n expert.selected = True\n db.session.add(expert)\n g.user.has_selected_expert_topics = True\n db.session.add(g.user)\n\n db.session.commit()\n\n return {'result': True}\n\n\n@bp.route('/topic/<int:uid>/apply_for_deletion', methods=['POST'])\n@UserPermission()\n@jsonify\ndef apply_for_deletion(uid):\n \"\"\"申请删除话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n apply = ApplyTopicDeletion(user_id=g.user.id, topic_id=uid)\n db.session.add(apply)\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/expert/<int:uid>/remove', methods=['POST'])\n@UserPermission()\n@jsonify\ndef remove_expert(uid):\n \"\"\"移除擅长话题\"\"\"\n expert_topic = UserTopicStatistic.query.get_or_404(uid)\n if not g.user.has_selected_expert_topics:\n for expert in g.user.expert_topics:\n expert.selected = True\n db.session.add(expert)\n g.user.has_selected_expert_topics = True\n db.session.add(g.user)\n db.session.commit()\n expert_topic.selected = False\n db.session.add(expert_topic)\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/add_expert', methods=['POST'])\n@UserPermission()\n@jsonify\ndef add_expert():\n \"\"\"添加擅长话题\"\"\"\n # 最多设置 8 个擅长话题\n if g.user.expert_topics.count() == 8:\n return {'result': True}\n\n id = request.form.get('id', type=int)\n name = request.form.get('name', '').strip()\n\n if id:\n topic = Topic.query.get_or_404(id)\n else:\n topic = Topic.get_by_name(name, g.user.id, create_if_not_exist=True)\n\n new_expert_topic = UserTopicStatistic.query.filter(UserTopicStatistic.topic_id == topic.id,\n UserTopicStatistic.user_id == g.user.id).first()\n if not new_expert_topic:\n new_expert_topic = UserTopicStatistic(topic_id=topic.id, user_id=g.user.id, selected=True)\n db.session.add(new_expert_topic)\n else:\n if new_expert_topic.selected:\n return {'result': True}\n else:\n new_expert_topic.selected = True\n\n if not g.user.has_selected_expert_topics:\n max_show_order_topic = 0\n for index, expert_topic in enumerate(g.user.expert_topics):\n expert_topic.show_order = index\n expert_topic.selected = True\n db.session.add(expert_topic)\n max_show_order_topic = index\n new_expert_topic.show_order = max_show_order_topic + 1\n g.user.has_selected_expert_topics = True\n db.session.add(g.user)\n db.session.add(new_expert_topic)\n else:\n max_show_order_topic = g.user.expert_topics.from_self().order_by(UserTopicStatistic.show_order.desc()).first()\n if max_show_order_topic:\n new_expert_topic.show_order = max_show_order_topic.show_order + 1\n\n db.session.commit()\n\n macro = get_template_attribute(\"macros/_topic.html\", \"render_expert_topic\")\n return {\n 'result': True,\n 'html': macro(new_expert_topic, myself=True),\n 'full': g.user.expert_topics.count() == 8\n }\n\n\n@bp.route('/topic/update_show_order', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_show_order():\n show_orders = request.form.get('show_orders')\n if not show_orders:\n return {'result': True}\n\n # 若从未编辑过擅长话题,则首先赋予 show_order\n if not g.user.has_selected_expert_topics:\n for index, expert_topic in enumerate(g.user.expert_topics):\n expert_topic.show_order = index\n expert_topic.selected = True\n db.session.add(expert_topic)\n\n g.user.has_selected_expert_topics = True\n db.session.add(g.user)\n\n show_orders = json.loads(show_orders)\n for item in show_orders:\n id = item['id']\n show_order = item['show_order']\n expert_topic = UserTopicStatistic.query.get(id)\n if expert_topic:\n expert_topic.show_order = show_order\n db.session.add(expert_topic)\n\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/<int:uid>/get_data_for_card', methods=['POST'])\n@jsonify\ndef get_data_for_card(uid):\n \"\"\"获取话题卡片\"\"\"\n topic = Topic.query.get_or_404(uid)\n return {\n 'result': True,\n 'topic': {\n 'id': uid,\n 'name': topic.name,\n 'url': url_for('.view', uid=uid),\n 'avatar_url': topic.avatar_url,\n 'followers_count': topic.followers_count,\n 'followed': bool(g.user and topic.followed_by_user(g.user.id)),\n 'wiki_preview': topic.wiki_preview\n }\n }\n\n\n@bp.route('/topic/update_avatar', methods=['POST'])\n@jsonify\ndef update_avatar():\n \"\"\"更新话题头像\"\"\"\n id = request.form.get('id', type=int)\n topic = Topic.query.get_or_404(id)\n\n if topic.avatar_locked:\n return {'result': False}\n\n avatar = request.form.get('key')\n topic.avatar = avatar\n db.session.add(topic)\n db.session.commit()\n return {'result': True, 'url': topic.avatar_url, 'id': topic.id}\n\n\n@bp.route('/topic/<int:uid>/edit_wiki', methods=['GET', 'POST'])\ndef edit_wiki(uid):\n \"\"\"编辑话题百科\"\"\"\n topic = Topic.query.get_or_404(uid)\n\n if topic.wiki_locked:\n abort(403)\n\n form = AdminTopicForm()\n if form.validate_on_submit():\n # Update wiki log\n if (topic.wiki or \"\") != form.wiki.data:\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.UPDATE_WIKI, user_id=g.user.id, topic_id=uid,\n before=topic.wiki, after=form.wiki.data,\n compare=text_diff(topic.wiki, form.wiki.data))\n db.session.add(log)\n\n # 记录wiki贡献者\n contributor = topic.wiki_contributors.filter(TopicWikiContributor.user_id == g.user.id).first()\n if contributor:\n contributor.count += 1\n contributor.last_contributed_at = datetime.now()\n db.session.add(contributor)\n else:\n contributor = TopicWikiContributor(topic_id=uid, user_id=g.user.id, count=1)\n db.session.add(contributor)\n\n form.populate_obj(topic)\n db.session.add(topic)\n db.session.commit()\n topic.save_to_es()\n return redirect(url_for('.view', uid=uid))\n return render_template('topic/edit_wiki.html', topic=topic)\n\n\n@bp.route('/topic/<int:uid>/update_name', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_name(uid):\n \"\"\"更新话题名称\"\"\"\n topic = Topic.query.get_or_404(uid)\n name = request.form.get('name', '').strip()\n\n if topic.name_locked or not name:\n return {'result': False}\n\n # 话题名称不可重复\n if Topic.query.filter(Topic.name == name, Topic.id != uid).first():\n return {'result': False}\n\n # Update name log\n if topic.name != name:\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.UPDATE_NAME, user_id=g.user.id, topic_id=uid, before=topic.name,\n after=name)\n db.session.add(log)\n\n topic.name = name\n topic.save_to_es()\n db.session.add(topic)\n db.session.commit()\n\n return {'result': True}\n\n\n@bp.route('/topic/<int:uid>/lock', methods=['POST'])\n@AdminPermission()\n@jsonify\ndef lock(uid):\n \"\"\"锁定话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n target = request.form.get('target')\n\n if not target:\n return {'result': True}\n\n attr = '%s_locked' % target\n\n if not hasattr(topic, attr):\n return {'result': True}\n\n locked = bool(getattr(topic, attr))\n setattr(topic, attr, not locked)\n\n # log\n log = PublicEditLog(user_id=g.user.id, topic_id=uid)\n if locked:\n log.kind = TOPIC_EDIT_KIND.UNLOCK\n log.before = attr\n else:\n log.kind = TOPIC_EDIT_KIND.LOCK\n log.after = attr\n db.session.add(log)\n\n if target == 'all':\n if topic.all_locked:\n topic.avatar_locked = True\n topic.name_locked = True\n topic.wiki_locked = True\n topic.parent_topics_locked = True\n topic.child_topics_locked = True\n topic.merge_topic_locked = True\n topic.topic_kind_locked = True\n else:\n topic.avatar_locked = False\n topic.name_locked = False\n topic.wiki_locked = False\n topic.parent_topics_locked = False\n topic.child_topics_locked = False\n topic.merge_topic_locked = False\n topic.topic_kind_locked = False\n\n if topic.avatar_locked and topic.name_locked and topic.wiki_locked and topic.parent_topics_locked \\\n and topic.child_topics_locked and topic.merge_topic_locked and topic.topic_kind_locked:\n topic.all_locked = True\n else:\n topic.all_locked = False\n\n db.session.add(topic)\n db.session.commit()\n\n return {'result': True, 'locked': not locked}\n\n\n@bp.route('/topic/<int:uid>/update_kind', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_kind(uid):\n \"\"\"更新话题类型\"\"\"\n topic = Topic.query.get_or_404(uid)\n kind = request.form.get('kind', type=int)\n\n if topic.topic_kind_locked or not kind or kind < 1 or kind > 6:\n return {'result': False}\n\n # log\n if topic.kind != kind:\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.UPDATE_KIND, user_id=g.user.id, before=topic.kind,\n after=kind, topic_id=uid)\n db.session.add(log)\n\n topic.kind = kind\n db.session.add(topic)\n db.session.commit()\n\n return {'result': True}\n\n\n@bp.route('/topic/<int:uid>/update_other_kind', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_other_kind(uid):\n \"\"\"更新话题其他类型\"\"\"\n topic = Topic.query.get_or_404(uid)\n kind = request.form.get('kind', '').strip()\n topic.other_kind = kind\n db.session.add(topic)\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/<int:uid>/merge_to', methods=['POST'])\n@AdminPermission()\n@jsonify\ndef merge_to(uid):\n \"\"\"将本话题合并至另一话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n\n if topic.merge_topic_locked or topic.merge_to_topic_id:\n return {'result': False}\n\n merge_to_topic_id = request.form.get('merge_to_topic_id', type=int)\n name = request.form.get('name', '').strip()\n\n if merge_to_topic_id:\n if uid == merge_to_topic_id:\n return {'result': False}\n merge_to_topic = Topic.query.get_or_404(merge_to_topic_id)\n else:\n merge_to_topic = Topic.get_by_name(name)\n if not merge_to_topic:\n return {'result': False}\n\n topic.merge_to_topic_id = merge_to_topic.id\n\n # 话题类型统一为与 merge_to_topic 一致,并锁定\n topic.kind = merge_to_topic.kind\n topic.other_kind = merge_to_topic.other_kind\n topic.topic_kind_locked = True\n db.session.add(topic)\n\n # 将该话题的名称设为 merge_to_topic 的同义词\n topic_synonym = merge_to_topic.synonyms.filter(TopicSynonym.synonym == topic.name).first()\n if not topic_synonym:\n topic_synonym = TopicSynonym(synonym=topic.name, topic_id=merge_to_topic.id, from_merge=True)\n db.session.add(topic_synonym)\n merge_to_topic.save_to_es()\n\n # 迁移问题\n for question_topic in topic.questions:\n _question_topic = merge_to_topic.questions.filter(\n QuestionTopic.question_id == question_topic.question_id).first()\n if not _question_topic:\n _question_topic = QuestionTopic(question_id=question_topic.question_id, topic_id=merge_to_topic.id,\n from_merge=True)\n db.session.add(_question_topic)\n\n # 迁移子话题\n for child_topic_id in topic.child_topics_id_list:\n merge_to_topic.add_child_topic(child_topic_id, from_merge=True)\n\n # 迁移关注者\n for follow_topic in topic.followers:\n _topic_follower = merge_to_topic.followers.filter(FollowTopic.user_id == follow_topic.user_id).first()\n if not _topic_follower:\n _topic_follower = FollowTopic(topic_id=merge_to_topic.id, user_id=follow_topic.user_id,\n from_merge=True)\n db.session.add(_topic_follower)\n merge_to_topic.followers_count += 1\n db.session.add(merge_to_topic)\n\n # 被合并的话题 Log\n merge_to_log = PublicEditLog(kind=TOPIC_EDIT_KIND.MERGE_TO, user_id=g.user.id, topic_id=uid,\n after_id=merge_to_topic.id, after=merge_to_topic.name)\n db.session.add(merge_to_log)\n\n # 合并至的话题 Log\n merge_in_log = PublicEditLog(kind=TOPIC_EDIT_KIND.MERGE_IN, user_id=g.user.id, topic_id=merge_to_topic.id,\n after_id=uid, after=topic.name)\n db.session.add(merge_in_log)\n\n db.session.commit()\n return {'id': merge_to_topic.id, 'name': merge_to_topic.name, 'result': True}\n\n\n@bp.route('/topic/<int:uid>/unmerge_from/<int:unmerge_from_topic_id>', methods=['POST'])\n@AdminPermission()\n@jsonify\ndef unmerge_from(uid, unmerge_from_topic_id):\n \"\"\"取消话题合并\"\"\"\n topic = Topic.query.get_or_404(uid)\n unmerge_from_topic = Topic.query.get_or_404(unmerge_from_topic_id)\n\n if topic.merge_topic_locked or topic.merge_to_topic_id != unmerge_from_topic_id:\n return {'result': False}\n\n topic.merge_to_topic_id = None\n\n # 解锁话题类型\n topic.topic_kind_locked = False\n\n # 移除同义词\n topic_synonym = unmerge_from_topic.synonyms.filter(TopicSynonym.synonym == topic.name,\n TopicSynonym.from_merge).first()\n unmerge_from_topic.save_to_es()\n\n db.session.delete(topic_synonym)\n\n # 迁回问题\n for question_topic in topic.questions:\n _question_topic = unmerge_from_topic.questions.filter(QuestionTopic.question_id == question_topic.question_id,\n QuestionTopic.from_merge).first()\n db.session.delete(_question_topic)\n\n # 迁回子话题\n for child_topic_id in topic.child_topics_id_list:\n unmerge_from_topic.remove_child_topic(child_topic_id, from_merge=True)\n\n # 迁回关注者\n for follow_topic in topic.followers:\n _topic_follower = unmerge_from_topic.followers.filter(FollowTopic.user_id == follow_topic.user_id,\n FollowTopic.from_merge).first()\n if _topic_follower:\n db.session.delete(_topic_follower)\n unmerge_from_topic.followers_count -= 1\n db.session.add(unmerge_from_topic)\n\n db.session.add(topic)\n\n # 取消合并至话题 log\n unmerge_from_log = PublicEditLog(kind=TOPIC_EDIT_KIND.UNMERGE_FROM, user_id=g.user.id,\n topic_id=uid, before=unmerge_from_topic.name,\n before_id=unmerge_from_topic.id)\n db.session.add(unmerge_from_log)\n\n # 从话题中移出 log\n unmerge_out_log = PublicEditLog(kind=TOPIC_EDIT_KIND.UNMERGE_OUT, user_id=g.user.id,\n topic_id=unmerge_from_topic.id, before=topic.name,\n before_id=topic.id)\n db.session.add(unmerge_out_log)\n\n db.session.commit()\n\n return {'result': True}\n","sub_path":"application/controllers/topic.py","file_name":"topic.py","file_ext":"py","file_size_in_byte":37834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"133921397","text":"class Solution(object):\n def flipAndInvertImage(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n results = []\n for i in range(len(A)):\n row = []\n for j in range(len(A[i])-1, -1, -1):\n row.append(0 if A[i][j] == 1 else 1)\n results.append(row)\n return results\n","sub_path":"Python/832. Flipping an Image.py","file_name":"832. Flipping an Image.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384010443","text":"#\n# Pyserini: Python interface to the Anserini IR toolkit built on Lucene\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 os\nimport filecmp\nimport unittest\nfrom tqdm import tqdm\nfrom pyserini.fusion import FusionMethod\nfrom pyserini.trectools import TrecRun\nfrom pyserini.search import get_topics, SimpleFusionSearcher, SimpleSearcher\n\n\nclass TestSearchIntegration(unittest.TestCase):\n def setUp(self):\n if not os.path.exists('lucene-index-cord19-abstract-2020-05-01/'):\n os.system('wget -nc https://www.dropbox.com/s/wxjoe4g71zt5za2/lucene-index-cord19-abstract-2020-05-01.tar.gz')\n os.system('tar -xvzf lucene-index-cord19-abstract-2020-05-01.tar.gz')\n os.system('rm lucene-index-cord19-abstract-2020-05-01.tar.gz')\n\n if not os.path.exists('lucene-index-cord19-full-text-2020-05-01/'):\n os.system('wget -nc https://www.dropbox.com/s/di27r5o2g5kat5k/lucene-index-cord19-full-text-2020-05-01.tar.gz')\n os.system('tar -xvzf lucene-index-cord19-full-text-2020-05-01.tar.gz')\n os.system('rm lucene-index-cord19-full-text-2020-05-01.tar.gz')\n\n if not os.path.exists('lucene-index-cord19-paragraph-2020-05-01/'):\n os.system('wget -nc https://www.dropbox.com/s/6ib71scm925mclk/lucene-index-cord19-paragraph-2020-05-01.tar.gz')\n os.system('tar -xvzf lucene-index-cord19-paragraph-2020-05-01.tar.gz')\n os.system('rm lucene-index-cord19-paragraph-2020-05-01.tar.gz')\n\n if not os.path.exists('anserini.covid-r2.fusion1.txt'):\n os.system('wget -q -nc https://www.dropbox.com/s/wqb0vhxp98g7dxh/anserini.covid-r2.fusion1.txt.gz')\n os.system('gunzip -f anserini.covid-r2.fusion1.txt.gz')\n\n def test_simple_fusion_searcher(self):\n index_dirs = ['lucene-index-cord19-abstract-2020-05-01/',\n 'lucene-index-cord19-full-text-2020-05-01/',\n 'lucene-index-cord19-paragraph-2020-05-01/']\n\n searcher = SimpleFusionSearcher(index_dirs, method=FusionMethod.RRF)\n\n runs, topics = [], get_topics('covid_round2')\n for topic in tqdm(sorted(topics.keys())):\n query = topics[topic]['question'] + ' ' + topics[topic]['query']\n hits = searcher.search(query, k=10000, query_generator=None, strip_segment_id=True, remove_dups=True)\n docid_score_pair = [(hit.docid, hit.score) for hit in hits]\n run = TrecRun.from_search_results(docid_score_pair, topic=topic)\n runs.append(run)\n\n all_topics_run = TrecRun.concat(runs)\n all_topics_run.save_to_txt(output_path='fused.txt', tag='reciprocal_rank_fusion_k=60')\n\n # Only keep topic, docid and rank. Scores have different floating point precisions.\n os.system(\"\"\"awk '{print $1\" \"$3\" \"$4}' fused.txt > this.txt\"\"\")\n os.system(\"\"\"awk '{print $1\" \"$3\" \"$4}' anserini.covid-r2.fusion1.txt > that.txt\"\"\")\n\n self.assertTrue(filecmp.cmp('this.txt', 'that.txt'))\n\n def tearDown(self):\n os.system('rm anserini.covid-r2.fusion1.txt fused.txt this.txt that.txt')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"integrations/test_search_integration.py","file_name":"test_search_integration.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81147933","text":"__author__ = 'loliveira'\n\nfrom flask import g, jsonify\nfrom flask_restful import Resource\n\nfrom app import db\nfrom conf.auth import auth\nfrom app.resources import parser\nfrom app.models.UserModel import Task\nfrom datetime import date\n\n\nclass TaskResource(Resource):\n\n @staticmethod\n @auth.login_required\n def get():\n parser.add_argument('done', type=int)\n args = parser.parse_args() \n done = args['done']\n response = []\n\n for task in g.user.tasks:\n add = False \n if done is not None:\n if task.done == done:\n add = True\n else:\n add = True\n\n if add:\n task_json = dict(id=task.id, title=task.title, description=task.description,difficulty=task.difficulty,priority=task.priority,done=task.done,end_date=str(task.end_date),start_date=str(task.start_date))\n response.extend([task_json])\n return jsonify(tasks=response)\n\n @staticmethod\n @auth.login_required\n def put():\n parser.add_argument('title', type=str)\n parser.add_argument('description', type=str)\n parser.add_argument('difficulty', type=int)\n parser.add_argument('priority', type=int)\n parser.add_argument('done', type=bool)\n parser.add_argument('end_date', type=str)\n parser.add_argument('start_date', type=str)\n args = parser.parse_args()\n task = Task(args['title'], args['description'], args['priority'], args['done'], args['difficulty'],args['end_date'],args['start_date'])\n task.user = g.user.id\n db.session.add(task)\n db.session.commit()\n\n return jsonify({'task': task.id})\n pass\n\n\n\nclass SingleTaskResource(Resource):\n\n @staticmethod\n @auth.login_required\n def get(task_id):\n task = Task.query.get(task_id)\n if task is None:\n return {}, 404\n if task.user == g.user.id:\n return jsonify(dict(id=task.id, title=task.title, description=task.description,difficulty=task.difficulty,priority=task.priority,done=task.done,end_date=str(task.end_date)),start_date=str(task.start_date))\n else:\n return {}, 404\n\n @staticmethod\n @auth.login_required\n def delete(task_id):\n task = Task.query.get(task_id)\n if task.user == g.user.id:\n db.session.delete(task)\n db.session.commit()\n return jsonify({'operation_status': 'SUCCESS'})\n else:\n return {}\n\n @staticmethod\n @auth.login_required\n def post(task_id):\n parser.add_argument('title', type=str)\n parser.add_argument('description', type=str)\n parser.add_argument('priority', type=int)\n parser.add_argument('done', type=str)\n parser.add_argument('difficulty', type=int)\n parser.add_argument('start_date', type=str)\n parser.add_argument('end_date', type=str)\n args = parser.parse_args()\n\n task = Task.query.get(task_id)\n updated = []\n title = args['title']\n if title is not None:\n updated.append('title')\n task.title = args['title']\n\n description = args['description']\n if description is not None:\n updated.append('description')\n task.description = description\n\n priority = args['priority']\n if priority is not None:\n updated.append('priority')\n task.priority = priority\n\n done = args['done']\n if done is not None:\n updated.append('done')\n task.done = done\n\n difficulty = args['difficulty']\n if difficulty is not None:\n updated.append('difficulty')\n task.difficulty = difficulty\n\n start_date = args['start_date']\n if start_date is not None:\n updated.append('start_date')\n task.start_date = start_date\n\n end_date = args['end_date']\n if end_date is not None:\n updated.append('end_date')\n task.end_date = end_date\n\n db.session.add(task)\n db.session.commit()\n\n return jsonify({'operation_status': 'SUCCESS', 'updated_values': updated})\n\n","sub_path":"app/resources/task_resource.py","file_name":"task_resource.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"283297734","text":"import cv2 as cv\n\n\nclass StereoParams:\n def __init__(self, intrinsic_filepath, extrinsic_filepath, image_size=None):\n if image_size is None:\n self._image_size = (752, 480)\n else:\n self._image_size = (image_size[0], image_size[1])\n\n intrinsic_file = cv.FileStorage(intrinsic_filepath, cv.FileStorage_READ)\n if not intrinsic_file.isOpened():\n raise ValueError('Cannot open intrinsic file')\n\n extrinsic_file = cv.FileStorage(extrinsic_filepath, cv.FileStorage_READ)\n if not extrinsic_file.isOpened():\n raise ValueError('Cannot open extrinsic file')\n\n self._M1 = intrinsic_file.getNode('M1').mat()\n self._D1 = intrinsic_file.getNode('D1').mat()\n self._M2 = intrinsic_file.getNode('M2').mat()\n self._D2 = intrinsic_file.getNode('D2').mat()\n\n self._R = extrinsic_file.getNode('R').mat()\n self._T = extrinsic_file.getNode('T').mat()\n\n r = cv.stereoRectify(self._M1, self._D1, self._M2, self._D2, self._image_size,\n self._R, self._T, flags=cv.CALIB_ZERO_DISPARITY)\n self._R1, self._R2, self._P1, self._P2, _, _, _ = r\n\n self._map11, self._map12 = cv.initUndistortRectifyMap(\n self._M1, self._D1, self._R1, self._P1, self._image_size, cv.CV_16SC2)\n self._map21, self._map22 = cv.initUndistortRectifyMap(\n self._M2, self._D2, self._R2, self._P2, self._image_size, cv.CV_16SC2)\n\n def _remap(self, image, map1, map2):\n resized = False\n orig_size = (image.shape[1], image.shape[0])\n if orig_size != self._image_size:\n image = cv.resize(image, self._image_size)\n resized = True\n\n image = cv.remap(image, map1, map2, cv.INTER_LINEAR)\n\n if resized:\n image = cv.resize(image, orig_size)\n\n return image\n\n def remap_left(self, image):\n return self._remap(image, self._map11, self._map12)\n\n def remap_right(self, image):\n return self._remap(image, self._map21, self._map22)\n","sub_path":"stereo/_stereo_params.py","file_name":"_stereo_params.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"564392169","text":"from gevent import monkey # isort:skip\nmonkey.patch_all() # isort:skip\n\nimport timeit # noqa: E402\n\nfrom gevent import sleep # noqa: E402\nfrom simple_amqp import AmqpParameters # noqa: E402\n\nfrom simple_amqp_pubsub import Event, Pipe, Source, Subscriber # noqa: E402\nfrom simple_amqp_pubsub.gevent import GeventAmqpPubSub # noqa: E402\n\npubsub_conn = GeventAmqpPubSub(\n params=AmqpParameters(),\n)\n\nLOGS_SOURCE = Source(name='logs')\nLOGS_PIPE = Pipe(\n name='logs.worker',\n retries=['5s', '10s', '30s'],\n)\n\n\nclass LogService:\n sub = Subscriber(LOGS_PIPE)\n\n def __init__(self):\n self._last_dt = timeit.default_timer()\n\n @sub.listen(LOGS_SOURCE, 'logs')\n def logs(self, event: Event):\n log_line = event.payload\n\n print('## log line: ', log_line)\n time = timeit.default_timer()\n print('## dt {0:.2f}ms'.format((time - self._last_dt) * 1000))\n self._last_dt = time\n\n\nlogs_service = LogService()\npubsub_conn \\\n .add_subscriber(logs_service.sub, logs_service)\n\npubsub_conn.configure()\npubsub_conn.start()\n\nwhile True:\n sleep(1)\n","sub_path":"examples/gevent/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"611878969","text":"import unittest\n\n\nclass TestExercise(unittest.TestCase):\n MESSAGE_FMT = 'Đầu vào: {0!r} - Kết quả đúng là {1!r}, nhận được {2!r}'\n\n def _test_all(self, func, cases):\n for input_, expect in cases:\n output = func(input_)\n msg = self.MESSAGE_FMT.format(input_, expect, output)\n self.assertEqual(output, expect, msg)\n","sub_path":"pyfml/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"536652356","text":"# Copyright 2013 IBM Corp.\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 __future__ import print_function\n\nimport os\nimport os.path\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport testtools\n\n\ndef _file_to_list(fname):\n with open(fname) as f:\n content = list(map(lambda x: x.rstrip(), f.readlines()))\n print(content)\n return content\n\n\nclass UpdateTest(testtools.TestCase):\n\n def setUp(self):\n super(UpdateTest, self).setUp()\n self.dir = tempfile.mkdtemp()\n self.project_dir = os.path.join(self.dir, \"project\")\n self.bad_project_dir = os.path.join(self.dir, \"bad_project\")\n self.oslo_dir = os.path.join(self.dir, \"project_with_oslo\")\n\n self.req_file = os.path.join(self.dir, \"global-requirements.txt\")\n self.dev_req_file = os.path.join(self.dir, \"dev-requirements.txt\")\n self.proj_file = os.path.join(self.project_dir, \"requirements.txt\")\n self.oslo_file = os.path.join(self.oslo_dir, \"requirements.txt\")\n self.bad_proj_file = os.path.join(self.bad_project_dir,\n \"requirements.txt\")\n self.proj_test_file = os.path.join(self.project_dir,\n \"test-requirements.txt\")\n self.setup_file = os.path.join(self.project_dir, \"setup.py\")\n self.old_setup_file = os.path.join(self.oslo_dir, \"setup.py\")\n self.bad_setup_file = os.path.join(self.bad_project_dir, \"setup.py\")\n self.setup_cfg_file = os.path.join(self.project_dir, \"setup.cfg\")\n self.bad_setup_cfg_file = os.path.join(self.bad_project_dir,\n \"setup.cfg\")\n self.oslo_setup_cfg_file = os.path.join(self.oslo_dir, \"setup.cfg\")\n os.mkdir(self.project_dir)\n os.mkdir(self.oslo_dir)\n os.mkdir(self.bad_project_dir)\n\n shutil.copy(\"tests/files/gr-base.txt\", self.req_file)\n shutil.copy(\"tests/files/dev-req.txt\", self.dev_req_file)\n shutil.copy(\"tests/files/project-with-oslo-tar.txt\", self.oslo_file)\n shutil.copy(\"tests/files/project.txt\", self.proj_file)\n shutil.copy(\"tests/files/project-with-bad-requirement.txt\",\n self.bad_proj_file)\n shutil.copy(\"tests/files/test-project.txt\", self.proj_test_file)\n shutil.copy(\"tests/files/setup.py\", self.setup_file)\n shutil.copy(\"tests/files/setup.py\", self.bad_setup_file)\n shutil.copy(\"tests/files/old-setup.py\", self.old_setup_file)\n shutil.copy(\"tests/files/setup.cfg\", self.setup_cfg_file)\n shutil.copy(\"tests/files/setup.cfg\", self.bad_setup_cfg_file)\n shutil.copy(\"tests/files/setup.cfg\", self.oslo_setup_cfg_file)\n shutil.copy(\"update.py\", os.path.join(self.dir, \"update.py\"))\n\n # now go call update and see what happens\n self.addCleanup(os.chdir, os.path.abspath(os.curdir))\n os.chdir(self.dir)\n returncode = subprocess.call([sys.executable, \"update.py\", \"project\"])\n self.assertEqual(returncode, 0)\n returncode = subprocess.call([sys.executable, \"update.py\",\n \"project_with_oslo\"])\n self.assertEqual(returncode, 0)\n\n def test_requirements(self):\n reqs = _file_to_list(self.req_file)\n self.assertIn(\"jsonschema>=1.0.0,!=1.4.0,<2\", reqs)\n\n def test_project(self):\n reqs = _file_to_list(self.proj_file)\n # ensure various updates take\n self.assertIn(\"jsonschema>=1.0.0,!=1.4.0,<2\", reqs)\n self.assertIn(\"python-keystoneclient>=0.4.1\", reqs)\n self.assertIn(\"SQLAlchemy>=0.7,<=0.7.99\", reqs)\n\n def test_project_with_oslo(self):\n reqs = _file_to_list(self.oslo_file)\n oslo_tar = (\"-f http://tarballs.openstack.org/oslo.config/\"\n \"oslo.config-1.2.0a3.tar.gz#egg=oslo.config-1.2.0a3\")\n self.assertIn(oslo_tar, reqs)\n self.assertIn(\"oslo.config>=1.2.0a3\", reqs)\n self.assertNotIn(\"oslo.config>=1.1.0\", reqs)\n\n def test_test_project(self):\n reqs = _file_to_list(self.proj_test_file)\n self.assertIn(\"testtools>=0.9.32\", reqs)\n self.assertIn(\"testrepository>=0.0.17\", reqs)\n # make sure we didn't add something we shouldn't\n self.assertNotIn(\"sphinxcontrib-pecanwsme>=0.2\", reqs)\n\n def test_install_setup(self):\n setup_contents = _file_to_list(self.setup_file)\n self.assertIn(\"# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO\"\n \" - DO NOT EDIT\", setup_contents)\n\n def test_no_install_setup(self):\n setup_contents = _file_to_list(self.old_setup_file)\n self.assertNotIn(\n \"# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO\"\n \" - DO NOT EDIT\", setup_contents)\n\n def test_requirment_not_in_global(self):\n returncode = subprocess.call([sys.executable, \"update.py\",\n \"bad_project\"])\n self.assertEqual(returncode, 1)\n\n def test_requirment_not_in_global_non_fatal(self):\n env = os.environ.copy()\n env['NON_STANDARD_REQS'] = '1'\n returncode = subprocess.call(\n [sys.executable, \"update.py\", \"bad_project\"],\n env=env)\n self.assertEqual(returncode, 0)\n","sub_path":"tests/test_update.py","file_name":"test_update.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558112041","text":"# -*- coding: utf-8 -*-\nimport json\nimport logging\nfrom io import StringIO\nfrom os.path import join\nfrom urllib.parse import quote\n\nimport diterator\nimport unicodecsv\nfrom hdx.location.currency import Currency\n\nfrom iati import checks\nfrom iati.activity import Activity\nfrom iati.calculatesplits import CalculateSplits\nfrom iati.lookups import Lookups\n\nlogger = logging.getLogger(__name__)\n\n\ndef retrieve_dportal(configuration, retriever, dportal_params, whattorun):\n \"\"\"\n Downloads activity data from D-Portal. Filters them and returns a\n list of activities.\n \"\"\"\n dportal_configuration = configuration['dportal']\n base_filename = dportal_configuration['filename']\n dportal_limit = dportal_configuration['limit']\n n = 0\n dont_exit = True\n while dont_exit:\n if dportal_params:\n params = dportal_params\n dont_exit = False\n else:\n offset = n * dportal_limit\n params = f'LIMIT {dportal_limit} OFFSET {offset}'\n logger.info(f'OFFSET {offset}')\n url = dportal_configuration['url'] % quote(dportal_configuration[f'{whattorun}_query'].format(params))\n filename = base_filename.format(n)\n text = retriever.retrieve_text(url, filename, 'D-Portal activities', False)\n if '<iati-activity' in text:\n n += 1\n yield text\n else:\n # If the result doesn't contain any IATI activities, we're done\n dont_exit = False\n\n\ndef write(today, output_dir, configuration, configuration_key, rows, skipped=None):\n logger.info(f'Writing {configuration_key} files to {output_dir}')\n file_configuration = configuration[configuration_key]\n headers = file_configuration['headers']\n hxltags = file_configuration['hxltags']\n process_cols = file_configuration.get('process_cols', dict())\n csv_configuration = file_configuration['csv']\n json_configuration = file_configuration['json']\n csv_hxltags = csv_configuration.get('hxltags', hxltags)\n json_hxltags = json_configuration.get('hxltags', hxltags)\n hxltag_to_header = dict(zip(hxltags, headers))\n csv_headers = [hxltag_to_header[hxltag] for hxltag in csv_hxltags]\n metadata = {'#date+run': today, f'#meta+{configuration_key}+num': len(rows)}\n if skipped is not None:\n metadata[f'#meta+{configuration_key}+skipped+num'] = skipped\n metadata_json = json.dumps(metadata, indent=None, separators=(',', ':'))\n with open(join(output_dir, csv_configuration['filename']), 'wb') as output_csv:\n writer = unicodecsv.writer(output_csv, encoding='utf-8', lineterminator='\\n')\n writer.writerow(csv_headers)\n writer.writerow(csv_hxltags)\n with open(join(output_dir, json_configuration['filename']), 'w') as output_json:\n output_json.write(f'{{\"metadata\":{metadata_json},\"data\":[\\n')\n\n def write_row(inrow, ending):\n def get_outrow(file_hxltags):\n outrow = dict()\n for file_hxltag in file_hxltags:\n expression = process_cols.get(file_hxltag)\n if expression:\n for i, hxltag in enumerate(hxltags):\n expression = expression.replace(hxltag, f'inrow[{i}]')\n outrow[file_hxltag] = eval(expression)\n else:\n outrow[file_hxltag] = inrow[hxltags.index(file_hxltag)]\n return outrow\n writer.writerow(get_outrow(csv_hxltags).values())\n row = get_outrow(json_hxltags)\n output_json.write(json.dumps(row, indent=None, separators=(',', ':')) + ending)\n\n [write_row(row, ',\\n') for row in rows[:-1]]\n write_row(rows[-1], ']')\n output_json.write('}')\n\n\ndef start(configuration, today, retriever, output_dir, dportal_params, whattorun, filterdate):\n if filterdate:\n text = f'removing transactions before {filterdate}'\n else:\n text = 'without removing transactions before a certain date'\n logger.info(f'Running {whattorun} {text}')\n Lookups.checks = checks[whattorun]\n Lookups.filter_transaction_date = filterdate\n generator = retrieve_dportal(configuration, retriever, dportal_params, whattorun)\n Lookups.setup(configuration['lookups'])\n Currency.setup(retriever=retriever, fallback_historic_to_current=True, fallback_current_to_static=True)\n CalculateSplits.setup(configuration['calculate_splits'])\n\n # Build org name lookup\n dactivities = list()\n for text in generator:\n for dactivity in diterator.XMLIterator(StringIO(text)):\n dactivities.append(dactivity)\n# Lookups.build_reporting_org_blocklist(dactivities)\n Lookups.add_reporting_orgs(dactivities)\n Lookups.add_participating_orgs(dactivities)\n\n # Build the accumulators from the IATI activities and transactions\n flows = dict()\n transactions = list()\n all_skipped = 0\n for i, dactivity in enumerate(dactivities):\n activity, skipped = Activity.get_activity(configuration, dactivity)\n all_skipped += skipped\n if activity:\n all_skipped += activity.process(today[:7], flows, transactions)\n if i % 1000 == 0:\n logger.info(f'Processed {i} activities')\n\n logger.info(f'Processed {len(flows)} flows')\n logger.info(f'Processed {len(transactions)} transactions')\n logger.info(f'Skipped {all_skipped} transactions')\n\n outputs_configuration = configuration['outputs']\n\n # Prepare and write flows\n write(today, output_dir, outputs_configuration, 'flows',\n [flows[key]['row']+[int(round(flows[key]['value']))] for key in sorted(flows)])\n\n # Write transactions\n write(today, output_dir, outputs_configuration, 'transactions',\n sorted(transactions, key=lambda x: (x[0], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10])), all_skipped)\n\n # Write orgs\n write(today, output_dir, outputs_configuration, 'orgs', sorted(Lookups.orgs_lookedup, key=lambda x: (x[1], x[0])))\n","sub_path":"iati/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"607831007","text":"# -*- coding: utf-8 -*-\n\n'''\nKth Smallest Element in a BST\n=============================\n\nGiven a binary search tree, write a function kthSmallest to find the kth\nsmallest element in it.\n\nNote:\nYou may assume k is always valid, 1 ≤ k ≤ BST's total elements.\n\nFollow up:\nWhat if the BST is modified (insert/delete operations) often and you need to\nfind the kth smallest frequently? How would you optimize the kthSmallest\nroutine?\n'''\n\n\nclass Solution(object):\n '''算法思路:\n\n 中序遍历\n\n Time: O(n)\n '''\n def search(self, root):\n if self.r is not None or not root:\n return\n\n self.search(root.left)\n\n self.k -= 1\n if not self.k:\n self.r = root.val\n\n self.search(root.right)\n\n def kthSmallest(self, root, k):\n self.k = k\n self.r = None\n\n self.search(root)\n return self.r\n\n\nclass Solution(object):\n '''算法思路:\n\n 利用二分\n '''\n def countNode(self, root):\n return root and sum(\n map(self.countNode, (root.left, root.right)), 1) or 0\n\n def kthSmallest(self, root, k):\n count = self.countNode(root.left)\n if count == k - 1:\n return root.val\n\n return self.kthSmallest(\n root.left, k) if count > k - 1 else self.kthSmallest(\n root.right, k - count - 1)\n","sub_path":"LeetCode/230 Kth Smallest Element in a BST.py","file_name":"230 Kth Smallest Element in a BST.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"7467225","text":"import requests\nfrom bs4 import BeautifulSoup\n\nres = requests.get(\n \"https://list.tmall.com/search_product.htm?q=u%C5%CC&type=p&vmarket=&spm=875.7931836%2FB.a2227oh.d100&xl=U_1&from=mallfp..pc_1_suggest\")\n# print(res.text)\nsoup = BeautifulSoup(res.text, \"html.parser\")\nfor item in soup.select('.product-iWrap'):\n print(item.select('em')[0].text, item.select('.productShop-name')[0].text,\n item.select('.productStatus')[0].text.strip(), \"\\n\")\n","sub_path":"practice/tmall.py","file_name":"tmall.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289898654","text":"\n\nimport numpy as np\n\nfrom typing import Union\nfrom gym.spaces import Box\n\nfrom actions import ActionStrategy, TradeActionUnion, DTypeString\nfrom trades import Trade, TradeType\n\n\nclass ContinuousActionStrategy(ActionStrategy):\n \"\"\"Simple continuous strategy, which calculates the trade amount as a fraction of the total balance.\"\"\"\n\n def __init__(self, instrument_symbol: str = 'BTC', max_allowed_slippage_percent: float = 1.0, dtype: DTypeString = np.float16):\n \"\"\"\n Arguments:\n instrument_symbol: The exchange symbol of the instrument being traded. Defaults to 'BTC'.\n max_allowed_slippage: The maximum amount above the current price the strategy will pay for an instrument. Defaults to 1.0 (i.e. 1%).\n dtype: A type or str corresponding to the dtype of the `action_space`. Defaults to `np.float16`.\n \"\"\"\n\n super().__init__(action_space=Box(0, 1, shape=(1, 1), dtype=dtype), dtype=dtype)\n\n self.instrument_symbol = instrument_symbol\n self.max_allowed_slippage_percent = max_allowed_slippage_percent\n\n def get_trade(self, action: TradeActionUnion) -> Trade:\n action_type, trade_amount = action\n trade_type = TradeType(int(action_type * len(TradeType)))\n\n current_price = self._exchange.current_price(symbol=self.instrument_symbol)\n base_precision = self._exchange.base_precision\n instrument_precision = self._exchange.instrument_precision\n\n amount = self._exchange.balance_of_instrument(self.instrument_symbol)\n price = current_price\n\n if trade_type is TradeType.MARKET_BUY or trade_type is TradeType.LIMIT_BUY:\n price_adjustment = 1 + (self.max_allowed_slippage_percent / 100)\n price = round(current_price * price_adjustment, base_precision)\n amount = round(self._exchange.balance * 0.99 * trade_amount / price, instrument_precision)\n\n elif trade_type is TradeType.MARKET_SELL or trade_type is TradeType.LIMIT_SELL:\n price_adjustment = 1 - (self.max_allowed_slippage_percent / 100)\n price = round(current_price * price_adjustment, base_precision)\n amount_held = self._exchange.portfolio.get(self.instrument_symbol, 0)\n amount = round(amount_held * trade_amount, instrument_precision)\n\n return Trade(self.instrument_symbol, trade_type, amount, price)\n","sub_path":"actions/continuous_action_strategy.py","file_name":"continuous_action_strategy.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"535313306","text":"# _*_ coding: utf-8 _*_\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport csv\r\nimport os\r\nimport time\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nimport numba\r\nimport itertools\r\n# =========== global parameters ===========\r\n\r\nT = 5 # iteration\r\nN = 2 # embedding_depth\r\nD = 8 # dimensional\r\nP = 64 # embedding_size\r\nB = 10 # mini-batch\r\nlr = 0.0001 # learning_rate\r\n# MAX_SIZE = 0 # record the max number of a function's block\r\nepochs = 100\r\nis_debug = True\r\n\r\ndata_folder=\"./features/\"\r\nmydata_folder=\"./data/\"\r\n# INDEX = mydata_folder + \"index_mydata.csv\"\r\nINDEX = data_folder + \"index.csv\"\r\nPREFIX = \"\"\r\n\r\ntest_file = os.path.join(mydata_folder, \"test\"+PREFIX+\".csv\")\r\n\r\nTEST_TFRECORD=\"data/TFrecord/test_gemini_data_\"+\"5430\"+PREFIX+\".tfrecord\"\r\n\r\nprint (TEST_TFRECORD)\r\n\r\n# ==================== load the function pairs list ===================\r\n# 1. load_dataset() load the pairs list for learning, which are\r\n# in train.csv, valid.csv, test.csv .\r\n# 1-1. load_csv_as_pair() process each csv file.\r\n# =====================================================================\r\ndef load_dataset():\r\n \"\"\" load the pairs list for training, testing, validing\r\n \"\"\"\r\n test_pair, test_label = load_csv_as_pair(test_file)\r\n\r\n return test_pair, test_label\r\n\r\ndef load_csv_as_pair(pair_label_file):\r\n \"\"\" load each csv file, which record the pairs list for learning and its label ( 1 or -1 )\r\n csv file : uid, uid, 1/-1 eg: 1.1.128, 1.4.789, -1\r\n pair_dict = {(uid, uid) : -1/1}\r\n \"\"\"\r\n pair_list = []\r\n label_list = []\r\n with open(pair_label_file, \"r\") as fp:\r\n pair_label = csv.reader(fp)\r\n for line in pair_label:\r\n pair_list.append([line[0], line[1]])\r\n label_list.append(int(line[2]))\r\n\r\n return pair_list, label_list\r\n\r\n\r\n# ====================== load block info and cfg ======================\r\n# 1. load_all_data() load the pairs list for learning, which are\r\n# in train.csv, valid.csv, test.csv .\r\n# 1-1. load_block_info()\r\n# 1-2. load_graph()\r\n# =====================================================================\r\ndef load_all_data():\r\n \"\"\" load all the real data, including blocks' featrue & functions' cfg using networkx\r\n uid_graph = {uid: nx_graph}\r\n feature_dict = {identifier : [[feature_vector]...]}, following the block orders\r\n \"\"\"\r\n uid_graph = {} #保存cfg图,id为版本号+基快地址\r\n feature_dict = {} #各个版本的所有block特征,id的版本号,值为block集合{基地址:特征}\r\n # read the direcory list and its ID\r\n # traversal each record to load every folder's data\r\n with open(INDEX, \"r\") as fp:\r\n for line in csv.reader(fp):\r\n # index.csv : folder name, identifier\r\n # eg: openssl-1.0.1a_gcc_4.6_dir, 1.1\r\n\r\n # load_block_info: save all the blocks' feature vector into feature_dict;\r\n # return current file's block number saved into block_num;\r\n # return each function's block id list saved into cur_func_block_dict.\r\n # 函数地址、 函数地址->函数调用地址\r\n block_num, cur_func_block_dict = load_block_info(os.path.join(data_folder, line[0], \"block_info.csv\"),\r\n feature_dict, line[1])\r\n\r\n if is_debug:\r\n print (\"load cfg ...\")\r\n # load every function's cfg\r\n load_graph(os.path.join(data_folder, line[0], \"adj_info.txt\"), block_num, cur_func_block_dict, line[1],\r\n uid_graph)\r\n\r\n return uid_graph, feature_dict\r\n\r\n\r\ndef load_my_data():\r\n \"\"\" load all the real data, including blocks' featrue & functions' cfg using networkx\r\n uid_graph = {uid: nx_graph}\r\n feature_dict = {identifier : [[feature_vector]...]}, following the block orders\r\n \"\"\"\r\n uid_graph = {} #保存cfg图,id为版本号+基快地址\r\n feature_dict = {} #各个版本的所有block特征,id的版本号,值为block集合{基地址:特征}\r\n # read the direcory list and its ID\r\n # traversal each record to load every folder's data\r\n\r\n # 函数地址、 函数地址->函数调用地址\r\n block_num, cur_func_block_dict = load_block_info(os.path.join(mydata_folder, \"block_info.csv\"), feature_dict , 'mydata')\r\n\r\n if is_debug:\r\n print (\"load cfg ...\")\r\n # load every function's cfg\r\n load_graph(os.path.join(mydata_folder, \"adj_info.txt\"), block_num, cur_func_block_dict,'mydata',\r\n uid_graph)\r\n\r\n return uid_graph, feature_dict\r\n\r\n\r\ndef load_block_info(feature_file, feature_dict, uid_prefix):\r\n \"\"\" load all the blocks' feature vector into feature dictionary.\r\n the two returned values are for next step, loading graph.\r\n return the block numbers —— using to add the single node of the graph\r\n return cur_func_blocks_dict —— using to generate every function's cfg(subgraph)\r\n \"\"\"\r\n feature_dict[str(uid_prefix)] = []#版本号:特征矩阵\r\n cur_func_blocks_dict = {}#函数地址->函数调用地址\r\n\r\n block_uuid = []#函数地址\r\n line_num = 0\r\n block_feature_dic = {}#函数地址:[特征矩阵(指令数量)]\r\n with open(feature_file, \"r\") as fp:\r\n if is_debug:\r\n print (feature_file)\r\n for line in csv.reader(fp):\r\n line_num += 1\r\n # skip the topic line\r\n #if line_num == 1:\r\n # continue\r\n if line[0] == \"\":\r\n continue\r\n block_uuid.append(str(line[0]))\r\n # read every bolck's features\r\n block_feature = [float(x) for x in (line[4:13])]\r\n del block_feature[6]\r\n block_feature_dic.setdefault(str(line[0]),block_feature)\r\n\r\n # record each function's block id.\r\n # for next step to generate the control flow graph\r\n # so the root block need be add.\r\n if str(line[2].strip()) not in cur_func_blocks_dict:\r\n cur_func_blocks_dict[str(line[2].strip())] = [str(line[0])]\r\n else:\r\n cur_func_blocks_dict[str(line[2].strip())].append(str(line[0]))\r\n feature_dict[str(uid_prefix)].append(block_feature_dic)\r\n\r\n return block_uuid, cur_func_blocks_dict\r\n\r\n\r\n\r\n#@numba.jit\r\ndef load_graph(graph_file, block_number, cur_func_blocks_dict, uid_prefix, uid_graph):\r\n \"\"\" load all the graph as networkx\r\n \"\"\"\r\n graph = nx.read_edgelist(graph_file, create_using=nx.DiGraph(), nodetype=str)\r\n\r\n # add the missing vertexs which are not in edge_list\r\n for i in block_number:\r\n if i not in graph.nodes():\r\n graph.add_node(i)\r\n\r\n for func_id in cur_func_blocks_dict:\r\n graph_sub = graph.subgraph(cur_func_blocks_dict[func_id])\r\n uid = uid_prefix + \".\" + str(func_id)\r\n uid_graph[uid] = graph_sub\r\n # -----------------------可视化cfg图----------------------\r\n # print('输出网络中的节点...')\r\n # print(graph_sub.nodes())\r\n # print('输出网络中的边...')\r\n # print(graph_sub.edges())\r\n # print('输出网络中边的数目...')\r\n # print(graph_sub.number_of_edges())\r\n # print('输出网络中节点的数目...')\r\n # print(graph_sub.number_of_nodes())\r\n # print('给网路设置布局...')\r\n # pos = nx.shell_layout(graph_sub)\r\n # nx.draw(graph_sub, pos, with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5)\r\n # plt.show()\r\n\r\n\r\n#@numba.jit\r\ndef construct_learning_dataset(uid_pair_list):\r\n \"\"\" Construct pairs dataset to train the model.\r\n attributes:\r\n adj_matrix_all store each pairs functions' graph info, (i,j)=1 present i--》j, others (i,j)=0\r\n features_all store each pairs functions' feature map\r\n \"\"\"\r\n print (\" start generate adj matrix pairs...\")\r\n adj_matrix_all_1, adj_matrix_all_2 = generate_adj_matrix_pairs(uid_pair_list)\r\n\r\n print (\" start generate features pairs...\")\r\n ### !!! record the max number of a function's block\r\n features_all_1, features_all_2, max_size, num1, num2 = generate_features_pair(uid_pair_list)\r\n\r\n return adj_matrix_all_1, adj_matrix_all_2, features_all_1, features_all_2, num1, num2, max_size\r\n\r\n\r\n#@numba.jit\r\ndef generate_adj_matrix_pairs(uid_pair_list):\r\n \"\"\" construct all the function pairs' cfg matrix.\r\n \"\"\"\r\n adj_matrix_all_1 = []\r\n adj_matrix_all_2 = []\r\n # traversal all the pairs\r\n count = 0\r\n for uid_pair in uid_pair_list:\r\n if is_debug:\r\n count += 1\r\n print (\" %04d martix, [ %s , %s ]\"%(count, uid_pair[0], uid_pair[1]))\r\n adj_matrix_pair = []\r\n # each pair process two function\r\n key_0= 'mydata' + \".\" + str(uid_pair[0])\r\n for eachKey in uid_graph_1.keys():\r\n print(eachKey)\r\n graph = uid_graph_1[key_0]\r\n\r\n # pos = nx.shell_layout(graph)\r\n # nx.draw(graph, pos, with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5)\r\n # plt.show()\r\n # origion_adj_1 = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\r\n # origion_adj_1.resize(size, size, refcheck=False)\r\n # adj_matrix_all_1.append(origion_adj_1.tolist())\r\n adj_arr = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\r\n adj_str = adj_arr.astype(np.string_)\r\n #扁平化列表\r\n adj_matrix_all_1.append(\",\".join(list(itertools.chain.from_iterable(adj_str))))\r\n\r\n select_list = uid_pair[1].split('.')\r\n if (len(select_list) >= 2):\r\n graph = uid_graph[uid_pair[1]] #解决标签为1的情况\r\n else:\r\n key_1 = \"mydata\" + \".\" + uid_pair[1] #标签为-1的情况\r\n graph = uid_graph_1[key_1]\r\n # origion_adj_2 = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\r\n # origion_adj_2.resize(size, size, refcheck=False)\r\n # adj_matrix_all_2.append(origion_adj_2.tolist())\r\n adj_arr = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\r\n adj_str = adj_arr.astype(np.string_)\r\n adj_matrix_all_2.append(\",\".join(list(itertools.chain.from_iterable(adj_str))))\r\n\r\n return adj_matrix_all_1, adj_matrix_all_2\r\n\r\n\r\n#@numba.jit\r\ndef convert_graph_to_adj_matrix(graph):\r\n \"\"\" convert the control flow graph as networkx to a adj matrix (v_num * v_num).\r\n 1 present an edge; 0 present no edge\r\n \"\"\"\r\n node_list = graph.nodes()\r\n adj_matrix = []\r\n\r\n # get all the block id in the cfg\r\n # construct a v_num * v_num adj martix\r\n for u in node_list:\r\n # traversal each block's edgd list,to add the\r\n u_n = graph.neighbors(u)\r\n neighbors = []\r\n for tmp in u_n:\r\n neighbors.append(tmp)\r\n node_adj = []\r\n for v in node_list:\r\n if v in neighbors:\r\n node_adj.append(1)\r\n else:\r\n node_adj.append(0)\r\n adj_matrix.append(node_adj)\r\n # print adj_matrix\r\n return adj_matrix\r\n\r\n\r\n#@numba.jit\r\ndef generate_features_pair(uid_pair_list):\r\n \"\"\" Construct each function pairs' block feature map.\r\n \"\"\"\r\n node_vector_all_1 = []\r\n node_vector_all_2 = []\r\n num1 = []\r\n num2 = []\r\n node_length = []\r\n # traversal all the pairs\r\n count = 0\r\n for uid_pair in uid_pair_list:\r\n if is_debug:\r\n count += 1\r\n print (\" %04d feature, [ %s , %s ]\"%(count, uid_pair[0], uid_pair[1]))\r\n node_vector_pair = []\r\n # each pair process two function\r\n uid = 'mydata' + \".\" + str(uid_pair[0])\r\n\r\n node_list = uid_graph_1[uid].nodes()\r\n uid_prefix = uid.rsplit('.', 1)[0] # 从右边第一个'.'分界,分成两个字符串 即 identifier, function_id\r\n node_vector = []\r\n for node in node_list:\r\n node_vector.append(feature_dict_1[str(uid_prefix)][0][node])\r\n node_length.append(len(node_vector))\r\n num1.append(len(node_vector))\r\n node_arr = np.array(node_vector)\r\n node_str = node_arr.astype(np.string_)\r\n node_vector_all_1.append(\",\".join(list(itertools.chain.from_iterable(node_str))))\r\n\r\n select_list = uid_pair[1].split('.')\r\n node_vector = []\r\n if (len(select_list) >= 2):\r\n uid = uid_pair[1]\r\n node_list = uid_graph[uid].nodes()\r\n uid_prefix = uid.rsplit('.', 1)[0]\r\n for node in node_list:\r\n node_vector.append(feature_dict[str(uid_prefix)][0][node])\r\n else:\r\n uid = \"mydata\" + \".\" + uid_pair[1] #标签为-1的情况\r\n node_list = uid_graph_1[uid].nodes()\r\n uid_prefix = uid.rsplit('.', 1)[0] # 从右边第一个'.'分界,分成两个字符串 即 identifier, function_id\r\n for node in node_list:\r\n node_vector.append(feature_dict_1[str(uid_prefix)][0][node])\r\n node_length.append(len(node_vector))\r\n num2.append(len(node_vector))\r\n node_arr = np.array(node_vector)\r\n node_str = node_arr.astype(np.string_)\r\n node_vector_all_2.append(\",\".join(list(itertools.chain.from_iterable(node_str))))\r\n\r\n num1_re = np.array(num1)\r\n num2_re = np.array(num2)\r\n #num1_re = num1_arr.astype(np.string_)\r\n #num2_re = num2_arr.astype(np.string_)\r\n #(100000)(100000)()(100000,)(100000,)\r\n return node_vector_all_1, node_vector_all_2, np.max(node_length),num1_re,num2_re\r\n\r\n # =============== convert the real data to training data ==============\r\n # 1. construct_learning_dataset() combine the dataset list & real data\r\n # 1-1. generate_adj_matrix_pairs() traversal list and construct all the matrixs\r\n # 1-1-1. convert_graph_to_adj_matrix() process each cfg\r\n # 1-2. generate_features_pair() traversal list and construct all functions' feature map\r\n # =====================================================================\r\n \"\"\" Parameter P = 64, D = 8, T = 7, N = 2, B = 10\r\n X_v = D * 1 <---> 8 * v_num * 10\r\n W_1 = P * D <---> 64* 8 W_1 * X_v = 64*1\r\n mu_0 = P * 1 <---> 64* 1\r\n P_1 = P * P <---> 64*64\r\n P_2 = P * P <---> 64*64\r\n mu_2/3/4/5 = P * P <---> 64*1\r\n W_2 = P * P <---> 64*64\r\n \"\"\"\r\n\r\n\r\n\r\n# ========================== the main function ========================\r\n# 1. load_dataset() load the train, valid, test csv file.\r\n# 2. load_all_data() load the origion data, including block info, cfg by networkx.\r\n# 3. construct_learning_dataset() combine the csv file and real data, construct training dataset.\r\n# =====================================================================\r\n# 1. load the train, valid, test csv file.\r\ndata_time = time.time()\r\ntest_pair, test_label = load_dataset()\r\nprint (\"1. loading pairs list time\", time.time() - data_time, \"(s)\")\r\n\r\n# 2. load the origion data, including block info, cfg by networkx.\r\ngraph_time = time.time()\r\nuid_graph_1, feature_dict_1 = load_my_data()\r\nuid_graph, feature_dict = load_all_data()\r\nprint (\"2. loading graph data time\", time.time() - graph_time, \"(s)\")\r\n\r\n# 3. construct training dataset.\r\ncons_time = time.time()\r\n\r\n\r\n# ========================== clean memory ========================\r\n# del train_pair, train_adj_matrix_1,train_adj_matrix_2,train_feature_map_1,train_feature_map_2,train_max\r\n\r\n# ========================== clean memory ========================\r\n# del valid_pair, valid_adj_matrix_1,valid_adj_matrix_2,valid_feature_map_1,valid_feature_map_2,valid_max\r\n\r\n# ======================= construct test data =====================\r\ntest_adj_matrix_1, test_adj_matrix_2, test_feature_map_1, test_feature_map_2,test_num1, test_num2, test_max \\\r\n = construct_learning_dataset(test_pair)\r\n# ========================== store in pickle ========================\r\nnode_list = np.linspace(test_max,test_max, len(test_label),dtype=int)\r\nwriter = tf.python_io.TFRecordWriter(TEST_TFRECORD)\r\nfor item1,item2,item3,item4,item5,item6, item7, item8 in itertools.izip(\r\n test_label, test_adj_matrix_1, test_adj_matrix_2, test_feature_map_1, test_feature_map_2,\r\n test_num1, test_num2, node_list):\r\n example = tf.train.Example(\r\n features = tf.train.Features(\r\n feature = {\r\n 'label':tf.train.Feature(int64_list = tf.train.Int64List(value=[item1])),\r\n 'adj_matrix_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item2])),\r\n 'adj_matrix_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item3])),\r\n 'feature_map_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item4])),\r\n 'feature_map_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item5])),\r\n 'num1':tf.train.Feature(int64_list = tf.train.Int64List(value=[item6])),\r\n 'num2':tf.train.Feature(int64_list = tf.train.Int64List(value=[item7])),\r\n 'max': tf.train.Feature(int64_list=tf.train.Int64List(value=[item8]))}))\r\n serialized = example.SerializeToString()\r\n writer.write(serialized)\r\nwriter.close()\r\n","sub_path":"py/toTFrecord_mydata.py","file_name":"toTFrecord_mydata.py","file_ext":"py","file_size_in_byte":17465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"202983047","text":"# -*- coding: utf-8 -*-\n# @Author : Jing\n# @FileName: 108. Convert Sorted Array to Binary Search Tree.py\n# @IDE: PyCharm\n# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/\nfrom base import TreeNode, PrintTree\n\n\nclass Solution(object):\n def sortedArrayToBST(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n if not nums:\n return None\n mid = (len(nums)-1) >> 1\n root = TreeNode(nums[mid])\n root.left = self.sortedArrayToBST(nums[:mid])\n root.right = self.sortedArrayToBST(nums[mid+1:])\n return root\n\n\nif __name__ == '__main__':\n nums = [-10, -3, 0, 5, 9]\n s = Solution()\n root = s.sortedArrayToBST(nums)\n p = PrintTree()\n p.in_order(root)\n p.print_tree()\n","sub_path":"Tree/108. Convert Sorted Array to Binary Search Tree.py","file_name":"108. Convert Sorted Array to Binary Search Tree.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"443845995","text":"# Kata 4th Kyu \"Square into Squares. Protect trees!\" \r\n# https://www.codewars.com/kata/54eb33e5bc1a25440d000891\r\n\r\ndef decompose (n):\r\n objetivo=0\r\n #Defino un valor objetivo que es el que voy a reducir\r\n resultado=[n]\r\n #Genero un vector resultado\r\n while resultado:\r\n actual=resultado.pop(-1)\r\n #Obtengo el último valor de resultado como \"actual\". En principio va a ser el número ingresado.\r\n objetivo+=actual**2\r\n #defino al objetivo como el cuadrado de \"actual\" es decir el número que debería anular\r\n for i in range (actual-1,0,-1):\r\n #defino una lista que va entre el valor que ingresé menos 1 y cero, yendo del mayor al menor.\r\n if objetivo-(i**2)>=0:\r\n #si la resta entre el valor al que tengo que llegar y el propuesto es mayor a cero (es decir si es factible) avanzo y agrego al número.\r\n resultado.append(i)\r\n objetivo-=i**2\r\n if objetivo==0:\r\n resultado.sort()\r\n #Si el resto es cero, ordeno los resultados y lo devuelvo.\r\n return (resultado)\r\n #Si no se cumplen las condiciones anteriores se sigue con el while, restándole 1 al último número que no funcionó.\r\n ","sub_path":"4th Kyu/Square into Squares. Protect trees!.py","file_name":"Square into Squares. Protect trees!.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"198897854","text":"# slicer imports\nfrom __main__ import vtk, slicer\n\n# python includes\nimport sys\nimport time\n\nclass Helper(object):\n\n @staticmethod\n def ConvertRAStoIJK(volumeNode,rasCoordinates):\n '''\n '''\n rasToIjkMatrix = vtk.vtkMatrix4x4()\n volumeNode.GetRASToIJKMatrix(rasToIjkMatrix)\n\n # the RAS coordinates need to be 4\n if len(rasCoordinates) < 4:\n rasCoordinates.append(1)\n\n ijkCoordinates = rasToIjkMatrix.MultiplyPoint(rasCoordinates)\n\n return ijkCoordinates\n","sub_path":"PythonModules/SlicerVmtkCommonLib/Helper.py","file_name":"Helper.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"400906604","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 22 12:28:00 2020\n\n@author: marco\n\"\"\"\nnumbers = [\n [34, 63, 88, 71, 29],\n [90, 78, 51, 27, 45],\n [63, 37, 85, 46, 22],\n [51, 22, 34, 11, 18]\n ]\n\nmean = lambda x : sum(x)/len(x)\n#def mean(num_list):\n# return sum(num_list) / len(num_list)\n\naverages = list(map(mean, numbers))\nprint(averages)\n","sub_path":"22_06_20_lambda_functions.py","file_name":"22_06_20_lambda_functions.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327741072","text":"import math\nimport sys\nimport numpy as np\nfrom numpy.linalg import norm\nimport matplotlib.pyplot as plt\nimport convexset as conv\nfrom convexset import Square\nimport time\nimport numba\nfrom numba import jit\nfrom numba import jitclass\n\nclass RRTreeBasis:\n r_expand = 0.2\n r_eps = 0.5\n def __init__(self, X, x_init, x_goal, obstacle):\n self.ndim = x_init.shape[0]\n self.x_goal = x_goal\n self.obs_set = obstacle\n self.X = X\n self.G = {'node': x_init, 'parent': [0]}# a decent tree structure is not necessary\n self.randInX = lambda N:X.min_bound + np.random.rand(2, N)*np.asarray(X.max_bound-X.min_bound)\n #self.randInU = lambda N:U.min_bound + np.random.rand(2, N)*np.asarray(U.max_bound-U.min_bound)\n\n def show_obstacles(self):\n self.X.show_convex(lcolor = 'b')\n for obs in self.obs_set:\n obs.show_convex(lcolor = 'r')\n\n def show_tree(self):\n global idx\n pos = self.G['node']\n idx = self.G['parent']\n for i in range(len(idx)):\n plt.plot([pos[0, i], pos[0, idx[i]]], [pos[1, i], pos[1, idx[i]]], 'go')\n plt.plot([pos[0, i], pos[0, idx[i]]], [pos[1, i], pos[1, idx[i]]], 'k-')\n\n def _sample(self):\n while(True):\n x_rand = self.randInX(1)\n logic = any(self._isCollide(x_rand))\n if logic==False:\n break\n return x_rand\n\n def _nearest(self, G, x_querry):\n dist_set = np.linalg.norm(G['node'] - x_querry, axis=0)\n return np.argmin(dist_set)\n\n def _near(self, G, x_pivot, r):\n dist_pivot = np.linalg.norm(G['node'] - x_pivot, axis=0)\n return np.nonzero(dist_pivot<r)[0]\n\n def _steer(self, x_start, x_target):\n return x_start + (x_target-x_start)*self.r_expand\n\n def _isCollide(self, point):\n logic_tmp = np.zeros(([point.shape[0], point.shape[1]]), dtype='int8')\n for obs in self.obs_set:\n logic_tmp = logic_tmp + obs.isInside(point)\n logic_tmp += np.logical_not(self.X.isInside(point))\n\n logic = (logic_tmp!=False)\n return logic\n \n def _isIntersect(self, p1, p2):\n logic = 0\n for obs in self.obs_set:\n if obs.isCrossing(p1, p2):\n logic = 1\n break\n return logic\n\n\nclass rrt_star(RRTreeBasis):# for the test purpose, ingnored the dynamics\n def __init__(self, X, x_init, x_goal, obstacle):\n super().__init__(X, x_init, x_goal, obstacle)\n self.G['cost'] = np.array([0])\n\n #dirty code\n def solve(self, Nitr):\n Nnode = lambda :len(self.G['parent'])\n while(Nnode()<Nitr):\n self.expand()\n if Nnode()%1000==0:\n print(\"Nnode=\"+str(Nnode()))\n\n normset = norm(self.G['node']-self.x_goal, axis=0)\n idx = np.argmin(normset)\n path_tmp = self.G['node'][:,idx]\n while True:\n idx_next = self.G['parent'][idx]\n if idx_next == 0:\n path_tmp = np.append(path_tmp, self.G['node'][:,idx_next], axis=1)\n break\n else:\n path_tmp = np.append(path_tmp, self.G['node'][:, idx_next], axis=1)\n idx = idx_next\n path = np.fliplr(path_tmp)\n return path, self.G\n\n def show_tree(self):\n Nnode = lambda :len(self.G['parent'])\n fuck =lambda x:np.array(x).flatten()\n\n parent =self.G['parent']\n pos = self.G['node'][:, parent]\n vec = self.G['node'] - pos\n plt.plot(fuck(pos[0,:]),fuck(pos[1,:]), 'ko', markersize=2)\n plt.quiver(fuck(pos[0,:]), fuck(pos[1, :]),\\\n fuck(vec[0,:]), fuck(vec[1,:]),\\\n color='limegreen',\\\n angles='xy',\\\n scale_units='xy',\\\n scale=1,\n width=0.001)\n self.show_obstacles()\n plt.title('Nnode='+str(Nnode()-1))\n\n def solve_with_mergin(self, Nitr, mergin):\n Xadd = Square([0, 0], mergin)\n obs_original = self.obs_set\n lst_obs = []\n for obs in self.obs_set:\n obs_new = obs+Xadd\n lst_obs.append(obs_new)\n self.obs_set = lst_obs\n [path, G]=self.solve(Nitr)\n self.obs = obs_original\n return path, G\n\n def split_path(self, step, path):\n len_total = 0\n for i in range(path.shape[1]-1):\n len_total += norm(path[:, i]-path[:,i+1])\n\n waypoint = np.mat(path[:, 0])\n p_start = np.mat(path[:, 0])\n p_end = np.mat(path[:, 1])\n len_edge = norm(p_end-p_start)\n vec = (p_end-p_start)/len_edge\n\n mileage = 0\n idx = 0\n while idx<path.shape[1]-2:\n if mileage+step<len_edge:\n mileage += step\n p_new = waypoint[:, -1] + vec*step\n waypoint = np.append(waypoint, p_new, axis=1)\n else:\n remain = (mileage+step)-len_edge\n while True:\n idx+=1\n if idx == path.shape[1]-1:\n vec_tmp = (path[:, -1]-path[:, -2])\n vec = vec_tmp/norm(vec_tmp)\n p_new = path[:, -2]+vec*remain\n waypoint = np.append(waypoint, p_new, axis=1)\n break\n p_start = np.mat(path[:,idx])\n p_end = np.mat(path[:, idx+1])\n len_edge = norm(p_end-p_start)\n vec = (p_end-p_start)/len_edge\n if remain<len_edge:\n p_new = p_start+vec*remain\n mileage = remain\n waypoint = np.append(waypoint, p_new, axis=1)\n break\n else:\n remain = remain-len_edge\n return waypoint\n\n def expand(self):\n # generic extension procedure\n nnode = len(self.G['parent'])\n radi = 0.6*(math.log10(nnode+1)/nnode+1)**(1/self.ndim)\n x_rand = self._sample()\n idx_nearest = self._nearest(self.G, x_rand)\n x_nearest = self.G[\"node\"][:, idx_nearest]\n x_new = self._steer(x_nearest, x_rand)\n\n if any(self._isCollide(x_new))==False:\n # compute cost and parent of new node\n idx_Xnear = self._near(self.G, x_new, radi)\n if len(idx_Xnear)==0:\n return\n self._connect_and_rewire(x_new, idx_Xnear)\n \n\n def _connect_and_rewire(self, x_new, idx_Xnear):\n [parent_new, cost_new] = self._SmallestCost(self.G, idx_Xnear, x_new)\n nnode = len(self.G['parent'])\n \n if self._isIntersect(x_new, self.G['node'][:, parent_new])==False:\n self.G['node'] = np.append(self.G['node'], x_new, axis=1)\n self.G['cost'] = np.append(self.G['cost'], cost_new) \n self.G['parent'].append(parent_new)\n\n # rewiring process\n for idx in idx_Xnear:\n node_child = self.G[\"node\"][:,idx]\n node_parent = self.G[\"node\"][:,self.G[\"parent\"][idx]]\n cost_current = self.G[\"cost\"][idx]\n cost_rewire = cost_new + np.linalg.norm(x_new-node_child)\n if cost_rewire < cost_current:\n if self._isIntersect(x_new, node_child)==False:\n self.G[\"parent\"][idx] = nnode # node-idx is starting from 0!\n self.G[\"cost\"][idx] = cost_rewire\n\n def _SmallestCost(self, G, idx_set, x_querry):\n cost_lst = G[\"cost\"][idx_set]\n node_lst = G[\"node\"][:, idx_set]\n costadd_lst = np.linalg.norm(node_lst - x_querry, axis=0)\n costnew_lst = cost_lst + costadd_lst\n\n idxidx_smallest = np.argmin(costnew_lst)\n parent_new = idx_set[idxidx_smallest]\n cost_new = costnew_lst[idxidx_smallest]\n\n return parent_new, cost_new\nif __name__=='__main__':\n x_init = np.matrix(\"0; 0\")\n x_init = np.matrix(\"0.3; 0.3\")\n x_goal = np.matrix(\"4.5; 4.5\")\n \n X = conv.Convex(np.mat([[0, 0, 5, 5], [0, 5, 5, 0]]))\n Mrot = lambda theta: np.mat([[math.cos(theta), -math.sin(theta)],\\\n [math.sin(theta), math.cos(theta)]])\n\n\n obs1 = 1.5*Mrot(0.8)*conv.Convex(np.mat([[0, 0],[0, 1], [0.5, 1.5], [1, 1], [0.5, 0]]).transpose())+np.array([[1.9],[2]])\n obs2 = 1.1*Mrot(0.3)*conv.Convex(np.mat([[0, 0], [2, 0], [2, 2], [0, 2]]).transpose())+np.mat([[3.5], [0]])\n obs3 = 1.0*Mrot(0.2)*conv.Convex(np.mat([[0, 0], [0, 2.0], [1, 1.5], [1, 0]]).transpose())+np.array([[2.8],[2.4]])\n obs4 = conv.Convex(np.mat([[0, 0],[0,1],[1, 1],[1,0]]).transpose())+np.mat([[0],[0.8]])\n obs_set = [obs1, obs2, obs3, obs4]\n\n rrt = rrt_star(X, x_init, x_goal, obs_set)\n [path, G]=rrt.solve_with_mergin(1000, 0.1)\n wp = rrt.split_path(0.3, path)\n fuck =lambda x:np.array(x).flatten()\n rrt.show_tree()\n plt.plot(fuck(wp[0, :]),fuck(wp[1,:]), 'bo-')\n plt.pause()\n \n\n","sub_path":"motion_planner.py","file_name":"motion_planner.py","file_ext":"py","file_size_in_byte":8964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222665528","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''Test for WAVECAR class'''\nimport os\n\nimport numpy as np\n# import tempfile\nfrom nose.tools import assert_almost_equal, eq_, ok_, with_setup\n\nimport vaspy.poscar as poscar\nimport vaspy.wavecar as wavecar\n\n\nclass TestHatomWavecar(object):\n '''Class for Test WAVECAR module by using H_gamma.wavecar'''\n\n def setup(self):\n datadir = os.path.abspath(os.path.dirname(__file__)) + \"/data/\"\n data_file = datadir + 'H_gamma.wavecar'\n self.h = wavecar.WAVECAR(data_file)\n\n @with_setup(setup=setup)\n def test_wavecar_header_and_band(self):\n '''Test for H atom WAVECAR header'''\n ok_(self.h.gamma)\n ok_(self.h.check_DwNGZHalf())\n eq_(1, self.h.nspin)\n eq_(np.complex64, self.h.prec)\n eq_(1, self.h.numk)\n eq_(27, self.h.nbands)\n eq_(600, self.h.encut)\n np.testing.assert_array_equal(\n [[25., 0., 0.], [0., 25., 0.], [0., 0., 25.]], self.h.realcell)\n assert_almost_equal(25**3, self.h.volume)\n np.testing.assert_array_almost_equal([101, 101, 101], self.h.ngrid)\n #\n eq_(260834, self.h.nplwvs[0])\n np.testing.assert_array_equal((260834, 3), self.h.gvectors().shape)\n np.testing.assert_array_almost_equal([0, 0, 0, 0, 0],\n self.h.realspace_wfc()[0][0][:5])\n\n\nclass TestCOWavecar(object):\n '''Class for Test WAVECAR module by using WAVECAR.CO.wavecar'''\n\n def setup(self):\n datadir = os.path.abspath(os.path.dirname(__file__)) + \"/data/\"\n data_file = datadir + 'WAVECAR.CO.wavecar'\n self.co = wavecar.WAVECAR(data_file)\n\n @with_setup(setup=setup)\n def test_wavecar_header(self):\n '''Test for CO molecule WAVECAR property\n\n rtag, wfprec\n '''\n eq_(711680, self.co.recl) # record length\n eq_(2, self.co.nspin) # spin\n eq_(45200, self.co.rtag) # precision flag\n eq_(np.complex64, self.co.prec)\n\n eq_(1, self.co.numk)\n eq_(54, self.co.nbands)\n eq_(400, self.co.encut)\n assert_almost_equal(-8.05748789, self.co.efermi)\n np.testing.assert_array_equal(\n [[17., 0., 0.], [0., 17., 0.], [0., 0., 17.]], self.co.realcell)\n assert_almost_equal(4913, self.co.volume)\n np.testing.assert_array_almost_equal([57, 57, 57], self.co.ngrid)\n\n @with_setup(setup=setup)\n def test_wavecar_band(self):\n '''test for CO WAVECAR band'''\n kpath, kbands = self.co.band()\n eq_(None, kpath)\n eq_((self.co.nspin, self.co.numk, self.co.nbands), kbands.shape)\n np.testing.assert_array_almost_equal([\n -29.49120151, -14.03737717, -11.88106463, -11.88106223, -9.00976389\n ], kbands[0, 0, 0:5]) # The value can be taken from EIGENVAL\n\n @with_setup(setup=setup)\n def test_wavecar_str(self):\n \"\"\"Test for __str__ special method.\"\"\"\n output = self.co.__str__()\n teststr = \"record length = 711680 spins = 2 \"\n teststr += \"prec flag 45200\\nno. k points = 1\"\n teststr += \"\\nno. bands = 54\\nreal space lattice vectors:\\n\"\n teststr += \"a1 = 17.0 0.0 0.0\\na2 = 0.0 17.0 0.0\\n\"\n teststr += \"a3 = 0.0 0.0 17.0\\n\\nvolume unit cell = \"\n teststr += \"4913.0000000000055\\nReciprocal lattice vectors:\\n\"\n teststr += \"b1 = 0.058823529411764705 0.0 0.0\"\n teststr += \"\\nb2 = 0.0 0.058823529411764705\"\n teststr += \" 0.0\\nb3 = 0.0 0.0 0.058823529411764705\"\n eq_(teststr, output)\n\n\nclass TestGrapheneWavecar(object):\n '''Class for Test WAVECAR module by using Graphene.wavecar'''\n\n def setup(self):\n datadir = os.path.abspath(os.path.dirname(__file__)) + \"/data/\"\n data_file = datadir + 'Graphene.wavecar'\n self.gr = wavecar.WAVECAR(data_file)\n self.gr_poscar = poscar.POSCAR(datadir + 'POSCAR.Graphene')\n\n def test_wavecar_header(self):\n '''Test for Graphene WAVECAR property'''\n eq_(30864, self.gr.recl) # record length\n eq_(1, self.gr.nspin) # spin\n eq_(45200, self.gr.rtag) # precision flag\n eq_(np.complex64, self.gr.prec)\n #\n eq_(240, self.gr.numk)\n eq_(27, self.gr.nbands)\n eq_(550, self.gr.encut)\n assert_almost_equal(-2.9500542715, self.gr.efermi)\n np.testing.assert_array_almost_equal(\n [[2.139081750, -1.235000000, 0.], [2.139081750, 1.235000000, 0.],\n [0., 0., 24.7]], self.gr.realcell)\n # volume of cell in OUTCAR is not enough\n assert_almost_equal(130.50323848575005, self.gr.volume)\n # FIXME!!: Where these value come from ?\n np.testing.assert_array_almost_equal([11, 11, 97], self.gr.ngrid)\n\n @with_setup(setup=setup)\n def test_wavecar_band(self):\n '''Test for Graphene wavecar band'''\n kpath, kbands = self.gr.band()\n # from OUTCAR\n # maximum and minimum number of plane-waves per node : 3857 3785\n eq_(3857, self.gr.nplwvs.max())\n eq_(3785, self.gr.nplwvs.min())\n eq_((self.gr.numk, ), kpath.shape) # gr.numk = 240\n eq_((self.gr.nspin, self.gr.numk, self.gr.nbands), kbands.shape)\n np.testing.assert_array_almost_equal(\n [-22.516876, -10.623282, -6.106901, -6.094072, 0.245639, 1.006991],\n kbands[0, 0, 0:6]) # The value can be taken from EIGENVAL\n\n @with_setup(setup=setup)\n def test_realsapece_wfc(self):\n '''Test for generation real space wfc (Graphene)'''\n np.testing.assert_array_almost_equal([\n 0.00013770 + 0.0001743j, 0.00014605 + 0.00018611j, 0.00017262 +\n 0.00022051j, 0.00021561 + 0.00027499j, 0.00026360 + 0.00033486j\n ],\n self.gr.realspace_wfc()[0][0][:5])\n vaspgrid = self.gr.realspace_wfc(poscar=self.gr_poscar)\n np.testing.assert_array_almost_equal(\n [0.00013770, 0.00014605, 0.00017262, 0.00021561, 0.00026360],\n vaspgrid.grid.data[:5])\n eq_(2, vaspgrid.grid.nframe)\n\n\nclass test_RestoreGammaGrid(object):\n #\n def test_check_symmetry(self):\n '''Test for check_symmetry'''\n ok_(not wavecar.check_symmetry(\n np.arange(3 * 3 * 3).reshape((3, 3, 3))))\n okgrid = np.array([[[0, 1, 1], [3, 4, 7], [3, 7, 4]],\n [[9, 10, 11], [12, 13, 14], [15, 16, 17]],\n [[9, 11, 10], [15, 17, 16], [12, 14, 13]]])\n ok_(wavecar.check_symmetry(okgrid))\n\n def test_RestorGammaGrid(self):\n '''Test for RestoreGammaGrid function'''\n grid332 = np.arange(3 * 3 * 3).reshape((3, 3, 3))[:, :, :2]\n grid332[2][0][0] = np.conjugate(grid332[1][0][0])\n grid332[2][2][0] = np.conjugate(grid332[1][1][0])\n grid332[1][2][0] = np.conjugate(grid332[2][1][0])\n grid332[0][2][0] = np.conjugate(grid332[0][1][0])\n result = wavecar.restore_gamma_grid(grid332, para=True)\n ok_(wavecar.check_symmetry(result))\n #\n grid553 = np.arange(5 * 5 * 5).reshape((5, 5, 5))[:, :, :3]\n #\n grid553[3, 0, 0] = np.conjugate(grid553[2, 0, 0])\n grid553[4, 0, 0] = np.conjugate(grid553[1, 0, 0])\n #\n grid553[0, 3, 0] = np.conjugate(grid553[0, 2, 0])\n grid553[1, 3, 0] = np.conjugate(grid553[4, 2, 0])\n grid553[2, 3, 0] = np.conjugate(grid553[3, 2, 0])\n grid553[3, 3, 0] = np.conjugate(grid553[2, 2, 0])\n grid553[4, 3, 0] = np.conjugate(grid553[1, 2, 0])\n #\n grid553[0, 4, 0] = np.conjugate(grid553[0, 1, 0])\n grid553[1, 4, 0] = np.conjugate(grid553[4, 1, 0])\n grid553[2, 4, 0] = np.conjugate(grid553[3, 1, 0])\n grid553[3, 4, 0] = np.conjugate(grid553[2, 1, 0])\n grid553[4, 4, 0] = np.conjugate(grid553[1, 1, 0])\n result = wavecar.restore_gamma_grid(grid553, para=True)\n ok_(wavecar.check_symmetry(result))\n #\n grid355 = np.arange(5 * 5 * 5).reshape((5, 5, 5))[:3, :, :]\n #\n grid355[0, 0, 3] = np.conjugate(grid355[0, 0, 2])\n grid355[0, 0, 4] = np.conjugate(grid355[0, 0, 1])\n #\n grid355[0, 3, 0] = np.conjugate(grid355[0, 2, 0])\n grid355[0, 3, 1] = np.conjugate(grid355[0, 2, 4])\n grid355[0, 3, 2] = np.conjugate(grid355[0, 2, 3])\n grid355[0, 3, 3] = np.conjugate(grid355[0, 2, 2])\n grid355[0, 3, 4] = np.conjugate(grid355[0, 2, 1])\n #\n grid355[0, 4, 0] = np.conjugate(grid355[0, 1, 0])\n grid355[0, 4, 1] = np.conjugate(grid355[0, 1, 4])\n grid355[0, 4, 2] = np.conjugate(grid355[0, 1, 3])\n grid355[0, 4, 3] = np.conjugate(grid355[0, 1, 2])\n grid355[0, 4, 4] = np.conjugate(grid355[0, 1, 1])\n result = wavecar.restore_gamma_grid(grid355, para=False)\n ok_(wavecar.check_symmetry(result))\n\n\nclass TestCobaltWavecar(object):\n '''Class for Test WAVECAR module by using Co.wavecar (SOI)'''\n\n def setup(self):\n datadir = os.path.abspath(os.path.dirname(__file__)) + \"/data/\"\n data_file = datadir + 'Co.wavecar'\n self.co = wavecar.WAVECAR(data_file)\n self.co_poscar = poscar.POSCAR(datadir + 'Co.POSCAR')\n\n @with_setup(setup=setup)\n def test_wavecar_header(self):\n '''Test for Cobalt property'''\n eq_(7968, self.co.recl) # record length\n eq_(1, self.co.nspin) # spin\n eq_(45200, self.co.rtag) # precision flag\n eq_(np.complex64, self.co.prec)\n #\n eq_(9, self.co.numk)\n eq_(54, self.co.nbands)\n eq_(400, self.co.encut)\n assert_almost_equal(-0.84118407515959326, self.co.efermi)\n np.testing.assert_array_almost_equal(\n np.array([[1.0, 0.0, 0.], [0.5, 0.8660254, 0.], [0., 0., 2.0]]) *\n 2.501, self.co.realcell)\n # volume of cell in OUTCAR is not enough\n assert_almost_equal(27.095782694613046, self.co.volume)\n # FIXME!!: Where these value come from ?\n # Maximum number of reciprocal cells 2x 2x 4 (in OUTCAR)\n np.testing.assert_array_almost_equal([11, 11, 19], self.co.ngrid)\n\n @with_setup(setup=setup)\n def test_wavecar_band(self):\n '''Test for Co wavecar band'''\n kpath, kbands = self.co.band()\n # from OUTCAR\n eq_(996, self.co.nplwvs.max())\n eq_(958, self.co.nplwvs.min())\n eq_((self.co.numk, ), kpath.shape) # co.numk = 240\n eq_((self.co.nspin, self.co.numk, self.co.nbands), kbands.shape)\n np.testing.assert_array_almost_equal(\n [-6.532492, -5.858599, -4.037263, -3.418892, -3.265558, -2.642231],\n kbands[0, 0, 0:6]) # The value can be taken from EIGENVAL\n\n @with_setup(setup=setup)\n def test_realsapece_wfc(self):\n '''Test for generation real space wfc (Cobalt)'''\n np.testing.assert_array_almost_equal(\n [\n -7.84915157e-05 - 5.61362047e-05j, -7.88077954e-05 -\n 5.63624713e-05j, -7.92001487e-05 - 5.66431905e-05j,\n -7.92675956e-05 - 5.66915450e-05j,\n -7.90423140e-05 - 5.65305135e-05j\n ],\n self.co.realspace_wfc()[0][0][0][:5])\n vaspgrid = self.co.realspace_wfc(poscar=self.co_poscar)\n np.testing.assert_array_almost_equal([\n -7.84915157e-05, -7.88077954e-05, -7.92001487e-05, -7.92675956e-05,\n -7.90423140e-05\n ], vaspgrid.grid.data[:5])\n eq_(4, vaspgrid.grid.nframe)\n","sub_path":"test/vaspy/test_wavecar.py","file_name":"test_wavecar.py","file_ext":"py","file_size_in_byte":11528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61664180","text":"#----------------------------------------------------------------\r\n# 第十九章:异常输出try, except and finally\r\n#----------------------------------------------------------------\r\ndef exists(filename):\r\n try:\r\n f = open(filename)\r\n f.close()\r\n return True\r\n except:\r\n return False\r\n\r\ndef get_age():\r\n age = int(input(\"Please enter your age: \"))\r\n if age < 0:\r\n # Create a new instance of an exception\r\n my_error = ValueError(\"{0} is not a valid age\".format(age))\r\n raise my_error\r\n return age\r\n\r\ndef recursion_depth(number):\r\n print(\"Recursion depth number\",number)\r\n try:\r\n recursion_depth(number+1)\r\n except:\r\n print(\"I cannot go any deeper into this wormhole.\")\r\n#recursion_depth(0)\r\n\r\nimport turtle\r\nimport time\r\ndef show_poly():\r\n try:\r\n win = turtle.Screen()\r\n tess = turtle.Turtle()\r\n n = int(input(\"How many sides do you want in your polygon?\\n\"))\r\n angle = 369 / n\r\n for i in range(n):\r\n tess.forward(10)\r\n tess.left(angle)\r\n time.sleep(3)\r\n finally:\r\n win.bye() #不管try是否成功,最后程序都将自己关闭图画窗口\r\nshow_poly()\r\n","sub_path":"Books/How to think like a computer scientist/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"486445068","text":"import cv2\nimport argparse\nimport math\nimport progressbar\nfrom pointillism import *\n\ndef pointillism(img_path, colors):\n img = cv2.imread(img_path)\n print(\"image path\", img_path)\n \n stroke_scale = int(math.ceil(max(img.shape) / 1000))\n print(\"Automatically chosen stroke scale: %d\" % stroke_scale)\n\n\n gradient_smoothing_radius = int(round(max(img.shape) / 50))\n print(\"Automatically chosen gradient smoothing radius: %d\" % gradient_smoothing_radius)\n\n\n # convert the image to grayscale to compute the gradient\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n palette_size = 20\n print(\"Computing color palette...\")\n palette = ColorPalette(colors)\n\n print(\"Extending color palette...\")\n# palette = palette.extend([(0, 50, 0), (15, 30, 0), (-15, 30, 0)])\n\n # display the color palette\n # cv2.imshow(\"palette\", palette.to_image())\n # cv2.waitKey(200)\n\n print(\"Computing gradient...\")\n gradient = VectorField.from_gradient(gray)\n\n print(\"Smoothing gradient...\")\n gradient.smooth(gradient_smoothing_radius)\n\n print(\"Drawing image...\")\n # create a \"cartonized\" version of the image to use as a base for the painting\n res = cv2.medianBlur(img, 11)\n # define a randomized grid of locations for the brush strokes\n grid = randomized_grid(img.shape[0], img.shape[1], scale=3)\n batch_size = 10000\n\n bar = progressbar.ProgressBar()\n for h in bar(range(0, len(grid), batch_size)):\n # get the pixel colors at each point of the grid\n pixels = np.array([img[x[0], x[1]] for x in grid[h:min(h + batch_size, len(grid))]])\n # precompute the probabilities for each color in the palette\n # lower values of k means more randomnes\n color_probabilities = compute_color_probabilities(pixels, palette, k=9)\n\n for i, (y, x) in enumerate(grid[h:min(h + batch_size, len(grid))]):\n color = color_select(color_probabilities[i], palette)\n angle = math.degrees(gradient.direction(y, x)) + 90\n length = int(round(stroke_scale + stroke_scale * math.sqrt(gradient.magnitude(y, x))))\n\n # draw the brush stroke\n cv2.ellipse(res, (x, y), (length, stroke_scale), angle, 0, 360, color, -1, cv2.LINE_AA)\n\n\n # cv2.imshow(\"res\", limit_size(res, 1080))\n cv2.imwrite(img_path, res)\n","sub_path":"submission/main_pointillism.py","file_name":"main_pointillism.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398538714","text":"# The quick sort\nfrom random import randint\n\n\nclass QuickSort:\n @staticmethod\n def swap(lst, idx1, idx2):\n # swapping takes constant time\n lst[idx1], lst[idx2] = lst[idx2], lst[idx1]\n\n @staticmethod\n def partition(lst, start, end):\n QuickSort.swap(lst, randint(start, end), end)\n # making all items < pivot to the left of the pivot\n # new_pivot_idx indicates any item on its left is smaller than the pivot\n new_pivot_idx = start\n for i in range(start, end):\n if lst[i] <= lst[end]:\n # it should be move inside the smaller_than_pivot part\n QuickSort.swap(lst, i, new_pivot_idx)\n new_pivot_idx += 1\n # after this swap all items on the left of the pivot is smaller than it in this sub-list\n QuickSort.swap(lst, end, new_pivot_idx)\n return new_pivot_idx\n\n @staticmethod\n def quick_sort_recursive_loop(lst, start, end):\n if start < end:\n new_pivot_idx = QuickSort.partition(lst, start, end)\n QuickSort.quick_sort_recursive_loop(lst, start, new_pivot_idx - 1)\n QuickSort.quick_sort_recursive_loop(lst, new_pivot_idx + 1, end)\n\n @staticmethod\n def quick_sort(lst):\n QuickSort.quick_sort_recursive_loop(lst, 0, len(lst) - 1)\n","sub_path":"sorting/src/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69047627","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nstar_wars = pd.read_csv(\"star_wars.csv\",encoding=\"ISO-8859-1\")\nstar_wars = star_wars[pd.notnull(star_wars['RespondentID'])]\nstar_wars.head(1)\n\n\n# In[2]:\n\n\n#seen_cols = star_wars.iloc[0,3:9].tolist()\n\ndef to_bool(seen):\n if pd.notnull(seen): return True\n else: return False\n \nstar_wars.rename(columns={\n 'Which of the following Star Wars films have you seen? Please select all that apply.':'seen_episode_1',\n 'Unnamed: 4': 'seen_episode_2',\n 'Unnamed: 5': 'seen_episode_3',\n 'Unnamed: 6': 'seen_episode_4',\n 'Unnamed: 7': 'seen_episode_5',\n 'Unnamed: 8': 'seen_episode_6'},inplace=True)\n\nseen_cols = star_wars.iloc[0,3:9].tolist()\n#print(star_wars.columns)\n\nfor i in range(1,9):\n star_wars.iloc[:,i] = star_wars.iloc[:,i].map(to_bool)\n \nprint(star_wars['seen_episode_1'].value_counts(dropna=False))\nprint([star_wars[col].value_counts(dropna=False) for col in list(star_wars.columns[3:9])])\nstar_wars.head()\n\n\n# In[3]:\n\n\nstar_wars.columns\nstar_wars.rename(columns={\n 'Please rank the Star Wars films in order of preference with 1 being your favorite film' \n ' in the franchise and 6 being your least favorite film.':'rank_episode_1',\n 'Unnamed: 10': 'rank_episode_2',\n 'Unnamed: 11': 'rank_episode_3',\n 'Unnamed: 12': 'rank_episode_4',\n 'Unnamed: 13': 'rank_episode_5',\n 'Unnamed: 14': 'rank_episode_6'},inplace=True)\nrank_list = [col for col in star_wars if \"rank\" in col]\nstar_wars[rank_list] = star_wars[rank_list].astype(float)\nstar_wars[rank_list]\n\n\n# ## Most popular installment\n# Now that those are cleaned up, we can look at some of the numbers. Let's start by looking at the rankings of each film. It's important to rememeber that lower-rank==better film.\n\n# In[4]:\n\n\nget_ipython().magic('matplotlib inline')\nimport matplotlib.pyplot as plt\nimport numpy as np\ndef clean_graph(graph,title=\"\",x_label=\"\",y_label=\"\",remove_spines=False):\n \"A short function to automate graph presentation\"\n if title != \"\": graph.set_title(title)\n if x_label != \"\": graph.set_xlabel(x_label)\n if y_label != \"\": graph.set_ylabel(y_label)\n graph.tick_params(top=False,bottom=False,left=False,right=False)\n if remove_spines == True:\n for axis in [\"right\", \"left\", \"top\", \"bottom\"]:\n graph.spines[axis].set_visible(False)\n\nfig = plt.figure(figsize=(8,6))\nmean_ranking = fig.add_subplot(1,2,1)\nempire_ranking = fig.add_subplot(1,2,2)\n\nbar_positions = np.arange(6) + 1\nbar_heights = star_wars[rank_list].mean().values\n#print(star_wars[rank_list].mean().values)\nmean_ranking.bar(bar_positions,bar_heights,align='center')\nmean_ranking.set_xlim(0,6.5)\nclean_graph(mean_ranking,title=\"Film ratings\",x_label=\"Episode\",y_label=\"Rank\",remove_spines=True)\nmean_ranking.set_ylim(0.5,6)\n\nbar_positions = np.arange(6) + 1\nbar_heights = star_wars['rank_episode_5'].value_counts()\nempire_ranking.bar(bar_positions,bar_heights,align='center')\nempire_ranking.set_xlim(0.5,6.5)\nclean_graph(empire_ranking,title=\"Empire Ranking\",x_label=\"Rank\",y_label=\"Count\",remove_spines=True)\nplt.show()\n\n# mean_rank = star_wars[rank_list].mean().plot.bar(rot=45)\n# clean_graph(mean_rank,title=\"Film ratings\",x_label=\"Episode\",y_label=\"Rank\",remove_spines=True)\n# mean_rank.set_ylim(0,6)\n# plt.show()\n# empire_rank = star_wars['rank_episode_5'].value_counts().plot.bar(rot=0)\n# clean_graph(empire_rank,title=\"Empire Ranking\",x_label=\"Rank\",y_label=\"Count\",remove_spines=True)\n# plt.show()\n\n\n# Most respondents ranked *Empire* as their number-one Star Wars film; 289 of the 835 respondents. *Jedi* was a colse second, with 146 ranking it first. Of those who didn't rank *Empire* at \\#1, most chose it as their second favourite. \n# The prequles ranked worse than the originals, with Episode 1 > Episode 2 > Episode 3.\n\n# ## How many respondents have actually watched all the films?\n\n# In[5]:\n\n\nseen_list = [col for col in star_wars.columns if \"seen_\" in col]\n#print(seen_list)\n#star_wars[seen_list]\nseen_count_graph = star_wars[seen_list].sum().plot.bar(rot=0)\nclean_graph(seen_count_graph,title=\"Movies watched by respondents\",x_label=\"Episode\",y_label=\"Count\",remove_spines=True)\nseen_count_graph.set_xticklabels([1,2,3,4,5,6])\nplt.show()\n\n\n# In[6]:\n\n\nseen_sum = star_wars[seen_list].sum().reset_index()\nrank_mean = star_wars[rank_list].mean().reset_index()\nrank_mean\ncorrelation = pd.concat([seen_sum.iloc[:,1],rank_mean.iloc[:,1]],ignore_index=True,axis=1)\n#corrolation = \n#corr = pd.merge([seen_sum,rank_mean],axis=1)\n#corr['seen'] = \n#corr['seen'] = seen_sum\ncorrelation.rename(index={0:'Episode_1',\n 1:'Episode_2',\n 2:'Episode_3',\n 3:'Episode_4',\n 4:'Episode_5',\n 5:'Episode_6',},\n columns={0:\"seen\",\n 1:\"ranking\"}\n ,inplace=True)\nclean_graph(correlation.plot.scatter('seen','ranking'),\n title=\"A not very interesting graph for quick identification of points\",\n remove_spines=True)\nplt.show()\ncorrelation\n#fig.text(.5, .05, txt, ha='center')\n\n\n# More respondents had seen *Empire* and *Jedi* than any other films, so there may be some bias in this dataset. In general, th more people that had seen a film, the higher the ranking. This makes sense, since a respondent can only rank a film that they've seen. The exception is *Episode 1: The Phantom Menace*, which, depsite having been watched by more people than *Episode 4: A New Hope*, was ranked lower. This follows from our earlier observation that the prequils ranked lower than the origional series.\n\n# ## Demographics\n# There are a few ways we can divide the dataset to see how different people rate the movies. Three ways we can do this are ny looking at \n# \n# * Self-described Star Wars fans vs. non-fans;\n# * Trekkies vs. non-Trekkies;\n# * Men vs. women.\n# \n# We'll need to do a bit of cleaning first. First thing is to sort out the titles of these columns. Next, all three fields include null-values; we don't want to drop these from the dataset, since, for example, the ratings by Star Wars fans isn't voided by not knowing their sex or if they're also Trekkies. What will becoome the `Trekkie` column also needs the `Yes/No` values to be converted using the `to_bool` function above.\n\n# In[7]:\n\n\nstar_wars.rename(columns={\"Do you consider yourself to be a fan of the Star Wars film franchise?\": \"fan\",\n \"Do you consider yourself to be a fan of the Star Trek franchise?\": \"Trekkie\"},\n inplace=True)\nstar_wars['Trekkie'] = star_wars['Trekkie'].map(to_bool)\n\n\n# Before we get started, let's be super lazy and convert the code for the above into functions so that we don't have to type out the whole analysis each time:\n\n# In[8]:\n\n\ndef construct_rankings(respondents,subset):\n fig = plt.figure(figsize=(9,6))\n mean_ranking = fig.add_subplot(1,2,1)\n empire_ranking = fig.add_subplot(1,2,2)\n\n bar_positions = np.arange(6) + 1\n bar_heights = respondents[rank_list].mean().values\n mean_ranking.bar(bar_positions,bar_heights,width=-0.4,align='edge',color='red',label=subset)\n \n bar_heights = star_wars[rank_list].mean().values\n mean_ranking.bar(bar_positions,bar_heights,width=0.4,align='edge',color='blue',label=\"combined\")\n \n mean_ranking.set_xlim(0,6.5)\n clean_graph(mean_ranking,title=\"Film ratings\",x_label=\"Episode\",y_label=\"Rank\",remove_spines=True)\n mean_ranking.set_ylim(0.5,6)\n #mean_ranking.legend()\n \n bar_positions = np.arange(6) + 1\n bar_heights = respondents['rank_episode_5'].value_counts()/respondents.shape[0]\n empire_ranking.bar(bar_positions,bar_heights,width=-0.4,align='edge',color=\"red\",label=subset)\n \n bar_heights = star_wars['rank_episode_5'].value_counts()/star_wars.shape[0]\n empire_ranking.bar(bar_positions,bar_heights,width=0.4,align='edge',color=\"blue\",label=\"combined\")\n \n empire_ranking.set_xlim(0.5,6.5)\n clean_graph(empire_ranking,title=\"Empire Ranking\",x_label=\"Rank\",y_label=\"Proportional Rank\",remove_spines=True)\n empire_ranking.legend()\n plt.show()\n\ndef construct_viewings(respondents, subset):\n seen_prop = respondents[seen_list].sum()/respondents.shape[0]\n all_prop = star_wars[seen_list].sum()/star_wars.shape[0]\n seen_count_graph = seen_prop.plot.bar(rot=0,width=-0.4,align='edge',color=\"red\",label=subset)\n seen_count_graph = all_prop.plot.bar(rot=0,width=0.4,align='edge',color=\"blue\",label=\"combined\")\n clean_graph(seen_count_graph,\n title=\"Movies watched by {}\".format(subset),\n x_label=\"Episode\",\n y_label=\"Watched by proportion\",\n remove_spines=True)\n seen_count_graph.set_xticklabels([1,2,3,4,5,6])\n seen_count_graph.set_xlim(-0.5,6.5)\n seen_count_graph.set_ylim(0,1)\n #seen_count_graph.legend()\n plt.show()\n \n\n\n# ### Self-proclaimed Star Wars fans\n\n# In[9]:\n\n\nprint('Constructing the fan-only dataframe....')\nfans = star_wars[star_wars['fan']==True]\nprint('Shape of dataframe:', fans.shape)\nprint('checking for missing values...')\nprint(fans[rank_list].count()) #the only null vlaue is one \nprint('One missing value in `rank_episode_1`')\n\nprint('Checking for ratings by non-fans in the main dataframe....')\n\nmask = (star_wars['fan']==False) & (star_wars['rank_episode_5'].notna())\nprint('Number of non-fans who ranked films:', star_wars[mask].shape[0])\n#construct_graphs(fans)\n\n\n# By looking at subsets of the main `star_wars` dataframe, we can see that:\n# \n# * All Star Wars fans ranked all movies, except for one missing value for *Episode 1: The Phantom Menace*;\n# * There were no non-fans who actually submitted rankings.\n# \n# Breaking the respondents down along fanship of the franchise doesn't tell us anything: since there's no data for non-fans, we can't draw any conclusions for them, and the fan-rankings are the same as for the database as a whole.\n\n# ### Trekkies\n# \n# Well, that was dissapointing. But to be fair, why would non-fans bother to fill in the survey? Let's look at Trekkies vs. philistines.\n\n# In[10]:\n\n\ntrekkies = star_wars[star_wars['Trekkie']==True]\nconstruct_rankings(trekkies,\"Trekkies\")\n\n\n# The Trekkies rankings were conistant with the overall average, however, the Trekkies ranked `Empire` slightly higher than the general response. Note that the graph on the right gives the proportion of respondents who ranked the films.\n# \n\n# In[11]:\n\n\nconstruct_viewings(trekkies,\"Trekkies\")\n\n\n# Trekies are slightly more likely than the general population to have seen Star Wars films (by about 5%). Is it true to say that if you're a Star Wars fan then you're also likely to be a Trekkie?\n\n# In[12]:\n\n\nstar_trekkies = star_wars[(star_wars['fan']==True) & (star_wars['Trekkie']==True)]\nprint('Number of Star Wars fans:',fans.shape[0])\nprint('Number of Star Trek fans:',trekkies.shape[0])\nprint('There are {} more Trekkies than Star Wars fans in the dataset'.format(trekkies.shape[0]-fans.shape[0]))\n\nconstruct_rankings(star_trekkies,\"fans of both\")\n\n\n# ### Male vs female rankings\n# One more dempgraphic breakdown which we can look at is the divide along gender lines.\n\n# In[13]:\n\n\nmale = star_wars[star_wars['Gender']=='Male']\nfemale = star_wars[star_wars['Gender']=='Female']\n\nmale_fans = male[male['fan']==True]\nfemale_fans = female[female['fan']==True]\n\nprint('Male fans: {}/{} total'.format(male_fans.shape[0],male.shape[0]))\nprint('Female fans: {}/{} total'.format(female_fans.shape[0],female.shape[0]))\n\n\n# So while more females responded to the survey, the absolute number of males who describe themselves as a Star Wars fan is higher.\n\n# In[14]:\n\n\nconstruct_rankings(male,\"Male respondents\")\nconstruct_rankings(female,\"Female respondents\")\n\n\n# There are some rather unexpected results here. Male respondents ranked *Episode 1* and *Episode 2* slightly lower than the average, and ranked the others slightly higher. About 1/3 men ranked *Empire* as being the best film, while only about 1/4 of the total did so. Conversely, female respondents ranked the *Episode 1* and *Episode 2* slightly higher, and the other films slightly lower than the total. Since there were more male than female respondents, the combined rankings more accurately reflect the opinions of the men. Let's put the male and female rankings on the same axes for easier comparison:\n\n# In[28]:\n\n\nfig = plt.figure(figsize=(9,6))\nmean_ranking = fig.add_subplot(1,2,1)\nempire_ranking = fig.add_subplot(1,2,2)\n\nbar_positions = np.arange(6) + 1\nbar_heights = male[rank_list].mean().values\nmean_ranking.bar(bar_positions,bar_heights,width=-0.4,align='edge',color='red',label=\"Male\")\n\nbar_heights = female[rank_list].mean().values\nmean_ranking.bar(bar_positions,bar_heights,width=0.4,align='edge',color='blue',label=\"Female\")\n\nmean_ranking.set_xlim(0,6.5)\nclean_graph(mean_ranking,title=\"Film ratings\",x_label=\"Episode\",y_label=\"Rank\",remove_spines=True)\nmean_ranking.set_ylim(0.5,6)\n \nbar_positions = np.arange(6) + 1\nbar_heights = male['rank_episode_5'].value_counts()/male.shape[0]\nempire_ranking.bar(bar_positions,bar_heights,width=-0.4,align='edge',color=\"red\",label=\"Male\")\n \nbar_heights = female['rank_episode_5'].value_counts()/female.shape[0]\nempire_ranking.bar(bar_positions,bar_heights,width=0.4,align='edge',color=\"blue\",label=\"Female\")\n \nempire_ranking.set_xlim(0.5,6.5)\nclean_graph(empire_ranking,title=\"Empire Ranking\",x_label=\"Rank\",y_label=\"Proportional Rank\",remove_spines=True)\nempire_ranking.legend()\nplt.show()\n\n\n# While female respondents were less polarised in their ranking choice, both sexes agree on the ranking of the films. But who's seen more films?\n\n# In[16]:\n\n\nconstruct_viewings(male,\"Male respondents\")\nconstruct_viewings(female,\"Female respondents\")\n\n\n# Male respondents were significantly more likely to have seen the *Star Wars* films than the total population, while female respondents were less likely to have watched them. Comparing the two directly:\n\n# In[17]:\n\n\nmale_prop = male[seen_list].sum()/male.shape[0]\nfemale_prop = female[seen_list].sum()/female.shape[0]\nseen_count_graph = male_prop.plot.bar(rot=0,width=-0.4,align='edge',color=\"red\",label=\"Male\")\nseen_count_graph = female_prop.plot.bar(rot=0,width=0.4,align='edge',color=\"blue\",label=\"Female\")\nclean_graph(seen_count_graph,\n title=\"Movies watched by {}\".format(\"Men and Women\"),\n x_label=\"Episode\",\n y_label=\"Watched by proportion\",\n remove_spines=True)\nseen_count_graph.set_xticklabels([1,2,3,4,5,6])\nseen_count_graph.set_xlim(-0.5,6.5)\nseen_count_graph.set_ylim(0,1)\nseen_count_graph.legend()\nplt.show()\n\n\n# Male respondents were much more likely to have watched each *Star Wars* film than female respondents--a difference of about 20%.\n\n# ## Who shot first?\n# Now let's look at something truely controvertial: who shot first? \n# An early scene in *Star Wars Episode 4: A New Hope* shows Han Solo meeting with a bounty Hunter named Greedo in a Canteena on Tatooine. In the origional release, Han shoots Greedo. In the '90s rerelease, the scene was edited to make Greedo shoot first, and for Han to fire back in self-defence. See [this Wikipedia article](https://en.wikipedia.org/wiki/Han_shot_first) on the subject.\n# \n# **Prediction:** it depends on which release of *Episode 4: A New Hope* the respondents saw first: the origional release from the '70s, or the '90s remaster. It's therefore worth including the `Age` of the respondents in the analysis. We'll first have to clean these columns up a bit.\n\n# In[18]:\n\n\n# for col in star_wars.columns:\n# print( col)\nHan_Greedo = star_wars[['Which character shot first?','Age']].copy()\nHan_Greedo.rename(columns={'Which character shot first?': 'shot_first','Age': 'age'},inplace=True)\n\n#take a look at the data and drop null values\nprint(Han_Greedo['shot_first'].value_counts(dropna=False))\nprint()\nprint(Han_Greedo['age'].value_counts(dropna=False))\nprint()\nold_size = Han_Greedo.shape[0]\nprint(\"Size before drop:\", old_size)\nHan_Greedo.dropna(how=\"any\",inplace=True)\nnew_size = Han_Greedo.shape[0]\nprint(\"Size after drop: {}----{} removed\".format(new_size,old_size-new_size))\n\n\n# In[19]:\n\n\ndef age_groups(age):\n if age == \"18-29\": return 1\n elif age == \"30-44\": return 2\n elif age == \"45-60\": return 3\n elif age == \"> 60\": return 4\n \n \nHan_Greedo['age'] = Han_Greedo['age'].map(age_groups)\n\n\n# In[20]:\n\n\nclean_graph(Han_Greedo['shot_first'].value_counts().plot.bar(rot=0),\n title=\"Who shot first?\",\n y_label=\"Count\",\n remove_spines=True)\nplt.show()\nHan_Greedo['shot_first'].value_counts()\n\n\n# Of the respondents who understood the question, most said that Han shot first (322 vs. 193). 37% of respondents didn't understand the question, 39% said Han shot first, and 23% said Greedo shot first. The rest didn't submit an answer. How does this break down by age?\n\n# In[114]:\n\n\nfig = plt.figure(figsize=(9,6))\n# Han = fig.add_subplot(1,3,1)\n# Greedo = fig.add_subplot(1,3,2)\n# dunno = fig.add_subplot(1,3,3)\ni=1\nfor answer in [\"Han\",\"Greedo\",\"I don't understand this question\"]:\n ax = fig.add_subplot(1,3,i)\n bar_positions = np.arange(4)# + 1\n bar_heights = Han_Greedo[Han_Greedo['shot_first']==answer]['age'].value_counts(sort=False)/ Han_Greedo['age'].value_counts(sort=False)\n ax.bar(bar_positions,bar_heights,width=0.4,align='center')\n if answer == \"Han\": title=\"Han shot first\"\n if answer == \"Greedo\": title=\"Greedo shot first\"\n if answer == \"I don't understand this question\": title=\"Don't know\"\n clean_graph(ax,title=title,remove_spines=True)\n ax.set_xticks(range(0,4))\n ax.set_ylim(0,0.6)\n ax.set_xticklabels([\"18-29\",\"30-44\",\"45-60\",\">61\"])\n i += 1\n\n\n# Contrary to expectations, it seems like the younger a respndent was, the more likely they were to say that Han shot first, while the only group that said that Greedo shot first was the 30-44 cohort. This latter observation makes some sense, since most members of this group would have grown up knowing the '90s remastered edition. The former observation is a little more eseorteric in its explaination. The phrase \"Han shot first\" is something of an internet meme; and therefore something that younger audiences are more likely to pick up on. See [this page](https://knowyourmeme.com/memes/han-shot-first) for details. \n# Respondents in the over 61 group were by far the most likely to not understand the question. \n","sub_path":"Star_Wars_Survey/Star_wars.py","file_name":"Star_wars.py","file_ext":"py","file_size_in_byte":18526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"253310455","text":"# -*- coding: utf-8 -*-\nimport Tkinter\nimport tkFileDialog\nimport xlrd\nimport os.path\nimport numpy as np\nimport xlsxwriter\nfrom xlsxwriter.utility import xl_rowcol_to_cell, xl_range_abs\n\n# ファイル選択画面の作成\nroot = Tkinter.Tk()\nroot.title(u\"小テスト得点集計プログラム\")\nroot.geometry(\"500x300\")\n\n# 選択ファイルのファイル形式とパス\nfTyp=[('Excelファイル(複数選択可)','.xlsx')]\niDir='c:/'\n\n# 解答のファイルを取得する関数\ndef DeleteEntryValue1(event):\n\tEditBox1.delete('1.0', 'end')\n\tanspath = tkFileDialog.askopenfilenames(filetypes=fTyp,initialdir=iDir)\n\tglobal anslist\n\tanslist = [[['0' for col in range(22)] for row in range(200)] for row in range(14)]\n\tglobal count\n\tcount = 0\n\t#複数ファイル(.xlsx)から読み取ったデータを3次元配列に格納\n\tfor path in anspath:\n\t\tReader = xlrd.open_workbook(path)\n\t\tsheet_1 = Reader.sheet_by_index(0)\n\t\tfor row in range(sheet_1.nrows):\n\t\t\tfor col in range(sheet_1.ncols):\n\t\t\t\tanslist[count][row][col] = sheet_1.cell(row,col).value\n\t\tfname = os.path.basename(path)\n\t\tglobal outfname\n\t\toutfname, ext = os.path.splitext(fname)\n\t\toutfname = outfname[0:4]\n\t\tEditBox1.insert(Tkinter.END,fname+\"\\n\")\n\t\tcount += 1\n\tEditBox1.insert(Tkinter.END,\"ファイル数:\"+str(count))\n\n# 終了\ndef ChangeText1(event):\n\troot.quit()\n\n# ファイル選択画面のテキストボックスとボタンの生成\nEditBox1 = Tkinter.Text(height=16,width=50)\nEditBox1.insert(Tkinter.END,\"各講義の採点結果ファイル\")\nEditBox1.pack()\nButton1 = Tkinter.Button(text = u'各講義の採点結果ファイルをすべて選んでください')\nButton1.bind(\"<Button-1>\",DeleteEntryValue1)\nButton1.pack()\nButton3 = Tkinter.Button(text = u'OK')\nButton3.bind(\"<Button-1>\",ChangeText1)\nButton3.pack()\n\nroot.mainloop()\n\n#Header削除と最大要素数の決定\ncolnum = 0\nfor i in range (count):\n\tdel anslist[i][0]\n\tif colnum < len(anslist[i]):\n\t\tcolnum = len(anslist[i])\n\n# 得点部分だけの配列を作成\nans=[[0 for j in range(colnum)] for k in range(len(anslist))]\n# 学籍番号部分だけの配列を作成\nstnum=[[0 for j in range(colnum)] for k in range(len(anslist))]\n\n# 学生番号と得点を分割するfor文\nfor i in range(count):\n\tfor row in range(0,len(anslist[i])):\n\t\tstnum [i][row] = anslist[i][row][0]\n\t\tans [i][row] = anslist[i][row][21]\n\n# 学生番号と得点が共に空欄のものを削除\nfor i in range(count):\n\tfor row in range(0,len(ans[i])-1):\n\t\tif stnum[i][row]=='' and ans [i][row]=='' :\n\t\t\tdel ans[i][row]\n\t\t\tdel stnum[i][row]\n\n# 学籍番号を全講義から抽出してリスト化\nstnum_count = [0 for i in range(colnum*len(anslist))]\nplus = 0\nfor i in range(count):\n\tfor j in range(0,len(stnum[i])):\n\t\tstnum_count[plus] = stnum[i][j]\n\t\tplus = plus + 1\nstnum_list = []\nfor i in stnum_count:\n\tif i not in stnum_list:\n\t\tstnum_list.append(i)\nfor i in range(len(stnum_list)):\n\tif stnum_list[i] == 0 :\n\t\tdel stnum_list[i]\n\n# 合計結果をまとめる配列\nresult = [['' for j in range(16)] for k in range(len(stnum_list))]\n\n#学籍番号ごとに各回の得点を配列に格納\nfor i in range(len(result)):\n\tif result[i][0] == '' and stnum_list[i] != '0':\n\t\tresult[i][0] = stnum_list[i]\n\tfor j in range(count):\n\t\tfor k in range(len(stnum[j])):\n\t\t\tif result[i][0] == stnum[j][k]:\n\t\t\t\tresult[i][j+1] = ans[j][k]\n\t\t\t\tbreak\n\nfor i in range(len(result)-2):\n\tif result[i][0] == '' or result[i][0] == '0':\n\t\tdel result[i]\n\n# 全講義の合計得点を配列の最終列に格納\nfor i in range(len(result)):\n\tscore_sum = 0\n\tfor j in range(1,len(result[0])-1):\n\t\tif result[i][j] != '':\n\t\t\tscore_sum = score_sum + int(result[i][j])\n\tresult[i][15] = score_sum\n\n# 学籍番号順でソート\nscoresheet = sorted(result, key=lambda x:(x[0],-int(x[15])))\n\n# 1行目に項目を追加\nheader = [\"StudentNumber\",'No.1','No.2','No.3','No.4','No.5','No.6','No.7','No.8','No.9','No.10','No.11','No.12','No.13','No.14',\"TotalScore\"]\noutput = np.vstack((header, scoresheet))\n\n# ワークブックとワークシートを作成\nwb = xlsxwriter.Workbook(outfname+\"-SmallTests.xlsx\")\nws = wb.add_worksheet(\"TotalScoreSheet\")\n\n# データ入力\nfor i in range(0,len(output)):\n for j in range(0,len(output[0])):\n ws.write(i, j, output[i][j])\n\n# 書き込み\nwb.close()\n\nprint(\"完了\")\n","sub_path":"ISE_SmallTest_Total.py","file_name":"ISE_SmallTest_Total.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641941389","text":"import socket\nimport time\nimport json\nimport datetime\nimport MySQLdb\nfrom random import randint\nfrom decimal import *\nimport subprocess\nimport docker\nfrom rpc_utils import *\nimport os \n\n\n\nif __name__ == '__main__':\n # name of the data base\n\tminer_server=\"localhost\"\n\tdb_list=[]\n\tclient = docker.from_env() \n\tdb = MySQLdb.connect(host=\"localhost\", # your host, usually localhost\n\tuser=\"vicom\", # your username\n\tpasswd=\"vicom\", # your password\n\tdb=\"db\") \n\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ts.connect((\"8.8.8.8\", 80))\n\tip=s.getsockname()[0]\n\ts.close()\n\tend=False\n\tlenght=0\n\tadd=[]\n\tmaxi=120000\n\tcur = db.cursor()\n\twhile(lenght<=maxi):\n\t\ttry:\n\t\t\tnn=rpc_call(client, ip, \"getnewaddress\",\"''\")\n\t\texcept:\n\t\t\tnn=0\n\t\tif(nn!=\"\" and nn!=False and nn!=None and nn!=0):\n\t\t\tadd=[nn,ip]\n\t\t\tquery = ('INSERT INTO destination (address,IP) values (%s,%s)')\n\t\t\tend = True\n\t\t\tcur.execute(query, add)\n\t\t\tdb.commit()\n\t\t\tf = open(\"address.csv\", \"a\")\n\t\t\tf.write(str(nn)+\",\"+str(ip)+\"\\n\")\n\t\t\tf.close()\n\t\t\tlenght=lenght+1\n\t\t#if(lenght>=maxi):\n\t\t#\trpc_call(client,ip,\"dumpwallet\",\"'walletdump'\")\n","sub_path":"btc_testbed/lib/generate_destination.py","file_name":"generate_destination.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"209432408","text":"from __future__ import absolute_import\nimport numpy as np\nfrom lsst.sims.catalogs.generation.db import DBObject\n\n__all__ = ['dbInterface']\n\nclass dbInterface(object):\n\n def __init__(self, database, host, port, driver):\n\n self._dbo = DBObject(database=database, host=host, port=port,\n driver=driver)\n\n def forcedSourceFromId(self, objectId):\n\n dtype = np.dtype([('object_id', np.int),\n ('ccd_visit_id', np.int),\n ('psf_flux', np.float),\n ('psf_flux_err', np.float),\n ('flags', np.int)])\n query = \"\"\"select objectId, ccdVisitId, psFlux, psFlux_Sigma, flags\n from ForcedSource\n where objectId = %i\"\"\" % objectId\n results = self._dbo.execute_arbitrary(query, dtype=dtype)\n return results\n\n def visitFromCcdVisitId(self, visitId):\n\n dtype = np.dtype([('visit_id', np.int),\n ('filter', str, 300),\n ('obs_start', str, 300)])\n\n query = \"\"\"select visitId, filterName, obsStart\n from CcdVisit\n where ccdVisitId = %i\"\"\" % visitId\n results = self._dbo.execute_arbitrary(query, dtype=dtype)\n return results\n\n def objectFromId(self, objectId):\n\n dtype = np.dtype([('object_id', np.int),\n ('parent_object_id', np.int),\n ('ra', np.float),\n ('dec', np.float)])\n query = \"\"\"select objectId, parentObjectId, psRa, psDecl\n from Object\n where objectId = %i\"\"\" % objectId\n results = self._dbo.execute_arbitrary(query, dtype=dtype)\n return results\n\n def objectFromRaDec(self, ra, dec, tol):\n\n dtype = np.dtype([('object_id', np.int),\n ('parent_object_id', np.int),\n ('ra', np.float),\n ('dec', np.float)])\n query = \"\"\"select objectId, parentObjectId, psRa, psDecl\n from Object\n where (psRa > %f) and (psRa < %f)\n and (psDecl > %f) and (psDecl < %f)\"\"\" % (ra - tol,\n ra + tol,\n dec - tol,\n dec + tol)\n results = self._dbo.execute_arbitrary(query, dtype=dtype)\n return results\n","sub_path":"python/desc/monitor/dbConnection.py","file_name":"dbConnection.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"492498331","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 4 14:18:03 2019\r\n\r\n@author: vibinan\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\r\nfrom keras.preprocessing.text import Tokenizer\r\nfrom keras.preprocessing import sequence\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, LSTM, Embedding\r\nfrom keras.backend import clear_session\r\n\r\n\r\n\r\n\r\nimport numpy as np \r\nimport matplotlib.pyplot as plt \r\nimport pandas as pd \r\n\r\nfrom keras.models import Sequential \r\nfrom keras.layers import Dense \r\nfrom keras.layers import LSTM \r\nfrom keras.layers import Dropout \r\n\r\n## Import Dataset\r\n\r\n# Dataset link - https://finance.yahoo.com/quote/AAPL/history?p=AAPL&.tsrc=fin-srch\r\n\r\napple_training_complete = pd.read_csv(r'E:\\Datasets\\apple_training.csv') \r\n\r\napple_training_processed = apple_training_complete.iloc[:, 1:2].values \r\n\r\n\r\n## Data Normalization\r\n\r\nfrom sklearn.preprocessing import MinMaxScaler \r\nscaler = MinMaxScaler(feature_range = (0, 1))\r\n\r\napple_training_scaled = scaler.fit_transform(apple_training_processed)\r\n\r\n## Convert Training Data to Right Shape\r\n\r\nfeatures_set = [] \r\nlabels = [] \r\nfor i in range(60, 1260): \r\n features_set.append(apple_training_scaled[i-60:i, 0])\r\n labels.append(apple_training_scaled[i, 0])\r\n \r\nfeatures_set, labels = np.array(features_set), np.array(labels) \r\n\r\nfeatures_set = np.reshape(features_set, (features_set.shape[0], features_set.shape[1], 1)) \r\n\r\n### Training The LSTM\r\n\r\nmodel = Sequential() \r\n\r\nmodel.add(LSTM(units=50, return_sequences=True, input_shape=(features_set.shape[1], 1))) \r\n\r\nmodel.add(Dropout(0.2)) \r\n\r\nmodel.add(LSTM(units=50, return_sequences=True)) \r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(LSTM(units=50, return_sequences=True)) \r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(LSTM(units=50)) \r\nmodel.add(Dropout(0.2)) \r\n\r\n### Creating Dense Layer\r\n\r\nmodel.add(Dense(units = 1))\r\n\r\n### Model Compilation\r\n\r\nmodel.compile(optimizer = 'adam', loss = 'mean_squared_error') \r\n\r\n### Algorithm Training\r\n\r\nmodel.fit(features_set, labels, epochs = 100, batch_size = 32) \r\n\r\n### Testing our LSTM\r\n\r\napple_testing_complete = pd.read_csv(r'E:\\Datasets\\apple_testing.csv') \r\napple_testing_processed = apple_testing_complete.iloc[:, 1:2].values\r\n\r\n### Converting Test Data to Right Format\r\n\r\napple_total = pd.concat((apple_training_complete['Open'], apple_testing_complete['Open']), axis=0) \r\n\r\ntest_inputs = apple_total[len(apple_total) - len(apple_testing_complete) - 60:].values \r\n\r\n\r\ntest_inputs = test_inputs.reshape(-1,1) \r\ntest_inputs = scaler.transform(test_inputs) \r\n\r\n\r\ntest_features = [] \r\nfor i in range(60, 80): \r\n test_features.append(test_inputs[i-60:i, 0])\r\n \r\ntest_features = np.array(test_features) \r\ntest_features = np.reshape(test_features, (test_features.shape[0], test_features.shape[1], 1)) \r\n\r\n## Making Predictions\r\n\r\npredictions = model.predict(test_features) \r\n\r\npredictions = scaler.inverse_transform(predictions) \r\n\r\n\r\nplt.figure(figsize=(10,6)) \r\nplt.plot(apple_testing_processed, color='blue', label='Actual Apple Stock Price') \r\nplt.plot(predictions , color='red', label='Predicted Apple Stock Price') \r\nplt.title('Apple Stock Price Prediction') \r\nplt.xlabel('Date') \r\nplt.ylabel('Apple Stock Price') \r\nplt.legend() \r\nplt.show() \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\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\r\n\r\n\r\n\r\n","sub_path":"timeseries - lstm.py","file_name":"timeseries - lstm.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354490560","text":"import pandas as pd\nimport numpy as np\nimport datetime\n\n# create some mock data\n\ndata_eye = [(pd.Timestamp(1513393355, unit= 's'), pd.Timestamp(1513393463, unit= 's'), 90),\n (pd.Timestamp(1513393853, unit= 's'), pd.Timestamp(1513393900, unit= 's'), 80),\n (pd.Timestamp(1513394100, unit= 's'), pd.Timestamp(1513394500, unit ='s'), 150),\n (pd.Timestamp(1513394900, unit= 's'), pd.Timestamp(1513395300, unit= 's'), 85)]\ndf_eye = pd.DataFrame(data=data_eye, columns=['start', 'end', 'pixel'])\n\ndata_event = [(pd.Timestamp(1513393300, unit= 's'), pd.Timestamp(1513393450, unit= 's'), 'a'),\n (pd.Timestamp(1513393851, unit= 's'), pd.Timestamp(1513393876, unit= 's'), 'b'),\n (pd.Timestamp(1513393877, unit= 's'), pd.Timestamp(1513394177, unit= 's'), 'c'),\n (pd.Timestamp(1513394178, unit= 's'), pd.Timestamp(1513394580, unit= 's'), 'a')]\ndf_event = pd.DataFrame(data=data_event, columns=['start', 'end', 'event'])\n\n# print (df_eye)\n# print (df_event)\n\ntime_periods = pd.DataFrame({'time': pd.date_range(start = df_eye.start.min(), end = df_eye.end.max(), freq = 'S')}) #create all time-stamps\ndf_eye = time_periods.merge(df_eye, how='left', left_on='time', right_on='start').fillna(method='pad') #merge\n# print (new_eye.iloc[70:150])\nmask_eye = (df_eye['time'] > df_eye['start']) & (df_eye['time'] < df_eye['end'])\ndf_eye = df_eye.where(mask_eye)\ndf_eye = df_eye.dropna()\n# print (fixed_eye.iloc[70:150])\ndf_eye.pop('start')\ndf_eye.pop('end')\n# df_eye.index = df_eye['time']\n# df_eye.pop('time')\ndf_eye['ID'] = 'ID_num'\ndf_eye['design'] = 'design_num'\n\n# df_eye.set_index([df_eye['ID']],[df_eye['design']])\n# df_eye.index = ([df_eye['ID']],[df_eye['design']])\n# df_eye.index = df_eye['design']\n# indexes = [df_eye['ID']],[df_eye['design']]\n\n# df_eye.set_index(['ID', 'design'], inplace = True, \n# append = False, drop = False) \n\nindex = pd.MultiIndex.from_product([['id_num'], ['design_num']],\n names=['ID', 'design']) \n# index = pd.MultiIndex.from_tuples(indexes,names = ['ID','design'])\ncolumns = pd.MultiIndex.from_product([['time', 'condition', 'aveH', 'aveV']],\n names = [None]) \ndf_eye_new = pd.DataFrame(df_eye, index=index, columns=columns)\n\n# df_eye2 = df_eye.reindex (index)\ndf_eye_new.append(df_eye).reset_index().set_index(keys=['ID', 'design'])\n\n\nprint (df_eye)\n# print (df_eye_new)\n\n\ntime_periods_event = pd.DataFrame({'time': pd.date_range(start = df_event.start.min(), end = df_event.end.max(), freq = 'S')}) #create all time-stamps\ndf_event = time_periods_event.merge(df_event, how='left', left_on='time', right_on='start').fillna(method='pad') #merge\nmask_event = (df_event['time'] > df_event['start']) & (df_event['time'] < df_event['end'])\ndf_event = df_event.where(mask_event)\ndf_event = df_event.dropna()\ndf_event.pop('start')\ndf_event.pop('end')\ndf_event.index = df_event['time']\ndf_event.pop('time')\n# print (df_event)\n\ndf_all = pd.concat ([df_event, df_eye], axis=1, sort = True)\ndf_all = df_all.dropna()\n\n# print (df_all.iloc[70:200])\n","sub_path":"old_drafts/Goni/old/concat_df_without_method3.py","file_name":"concat_df_without_method3.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292337586","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nPython Codes for Chapter: \nInsights from MAPs\n\n@author: JoseManuel\n\"\"\"\n#%%\nimport pandas as pd\n\nlink1='https://github.com/resourcesbookvisual/data/'\nlink2='raw/master/contriWA.csv'\ncontriWA=pd.read_csv(link1+link2)\n \n \n\n#%%\nimport geopandas as gpd\n\nmyGit=\"https://github.com/resourcesbookvisual/data/\"\nmyGeo=\"raw/master/WAzipsGeo.json\"\nmapLink=myGit + myGeo\n\nwazipMap = gpd.read_file(mapLink)\n\n#%%\n\nwazipMap.plot()\n\n#%%\nimport geoplot as gplt\ngplt.polyplot(wazipMap)\n\n\n#%%\n\nwazipMap.ZCTA5CE10.describe()\n\n#%%\n\n# Filtering\n#conditions\ncondition1='election_year==2012 and cash_or_in_kind==\"Cash\"'\ncondition2='party.isin([\"DEMOCRAT\",\"REPUBLICAN\"])'\n\n#chained queries\ncontriWASub=contriWA.query(condition1).query(condition2)\n#%%\n# Aggregating\ncontrisum=contriWASub.groupby(['contributor_zip','party'])\ncontrisum=contrisum.agg({'amount':'sum'}).reset_index().fillna(0)\ncontrisum=contrisum.pivot(index='contributor_zip', \n columns='party', \n values='amount').reset_index().fillna(0)\ncontrisum['total']=contrisum.DEMOCRAT + contrisum.REPUBLICAN\n\n\ncontrisum\n#\n\n\n#%%%\n\nwazipMap=wazipMap.loc[:,['ZCTA5CE10','geometry']]\n# contributor_zip as text (it was a number)\ncontrisum.contributor_zip=contrisum.contributor_zip.astype(str)\nallZip=wazipMap.merge(contrisum,\n left_on='ZCTA5CE10',\n right_on='contributor_zip',\n how='left')\n\n#%%\nimport numpy as np\n\ncomparison=allZip.REPUBLICAN>allZip.DEMOCRAT\ncondition=allZip.loc[:,[\"REPUBLICAN\",\"DEMOCRAT\"]].any(axis=1)\nallZip['winnerREP']=condition1\nallZip['winnerREP']=np.where(condition,\n comparison,\n None)\n\n\n#%%\n\nallZip.plot(column='winnerREP', #column to color\n categorical=True,\n edgecolor='black',\n legend=True,\n missing_kwds={'color': 'lightgrey'},\n cmap='gist_gray') # palette for column chosen\n\n\n\n#%%\n\n#missing\nallZip[allZip.winnerREP.isnull()].shape[0]\n\n\n#%%\n\n\n# dissolve\n## a. make copy\nwaBorder=wazipMap.copy()\n## b. Correct map with buffer (may not be needed)\nwaBorder['geometry'] = waBorder.buffer(0.01)\n## c. create a constant column by which to dissolve\nwaBorder['dummy']=1\n## d. dissolving\nwaBorder= waBorder.dissolve(by='dummy')\n## e. plot the dissolved map\nwaBorder.plot(color='white',edgecolor='black')\n\n\n#%%\n\n\n# dissolve\n## a. make copy\nallZipBetter=allZip.copy()\n## a.1 saving missing values\nNAs = allZipBetter[allZipBetter.winnerREP.isna()]\n## b. Correct map with buffer (may not be needed)\nallZipBetter['geometry'] = allZipBetter.buffer(0.01)\n## c. dissolving\nallZipREP= allZipBetter.dissolve(by='winnerREP',as_index=False)\n## d. plotting the dissolved map\nallZipREP.append(NAs).plot(column='winnerREP', #column to color\n edgecolor='black',\n categorical=True,legend=True,\n missing_kwds={'color': 'grey'}, \n cmap='gist_gray') \n\n#%%\n\n\n# turn lon lat into geoDataFrame \nWApoints = gpd.GeoDataFrame(contriWASub, \n geometry=gpd.points_from_xy(contriWASub.Lon,\n contriWASub.Lat))\nWApoints.crs = wazipMap.crs\n\nWApoints.plot()\n\n#%%\n\n## a. make polygons with missing values\nallZipNA=allZip[allZip.total.isnull()].copy()\n## b. Correct map with buffer (may not be needed)\n#allZipNA['geometry'] = allZipNA.buffer(0.01)\n## c. create a constant column by which to dissolve\n#allZipNA['dummy']=1\n## d. dissolving\n#allZipNA= allZipNA.dissolve(by='dummy',as_index=False)\n\n\n#%%\n\n#plot with default projection in geopandas\nlayerBorder= waBorder.plot(edgecolor='grey',color='white')\n\nlayerMissing=allZipNA.plot(edgecolor='grey',color='grey',\n ax=layerBorder)\nWApoints.plot(color='black', \n markersize=0.1,alpha=0.1,\n ax=layerBorder) # on top of!)\n\n\n\n\n\n\n#%%\n\n#plot with default projection in geoplot\nlayerBorder = gplt.polyplot(waBorder,\n edgecolor='grey',\n facecolor='white')\nlayerMissing = gplt.polyplot(allZipNA,\n edgecolor='grey',\n facecolor='grey',\n ax=layerBorder)\ngplt.pointplot(WApoints,\n color='black',\n s=0.1,#size of point\n alpha=0.1,\n ax=layerBorder)# on top of!\n\n\n#%%\n\n#reprojecting with geopandas\nlayerBorder= waBorder.to_crs(\"EPSG:3395\").plot(edgecolor='grey', \n color='white')\n\nlayerMissing=allZipNA.to_crs(\"EPSG:3395\").plot(edgecolor='grey',\n color='grey',\n ax=layerBorder)\n\nWApoints.to_crs(\"EPSG:3395\").plot(color='black',\n markersize=0.1,\n alpha=0.1,\n ax=layerBorder)\n\n\n#%%\n\nimport geoplot.crs as gcrs #activating!\n\nlayerBorder = gplt.polyplot(waBorder, \n projection=gcrs.Mercator(),#HERE!\n edgecolor='grey', \n facecolor='white')\n\nlayerMissing = gplt.polyplot(allZipNA,\n edgecolor='grey',\n facecolor='grey',\n ax=layerBorder)\nlayerPoint= gplt.pointplot(WApoints,\n color='black',\n s=0.1,\n alpha=0.1,\n ax=layerBorder)# on top of!\n\n\n#%%\n\nmyGit=\"https://github.com/resourcesbookvisual/data/\"\nmyGeo2=\"raw/master/waCountiesfromR.geojson\"\nmapLink2=myGit + myGeo2\n\nwaCounties= gpd.read_file(mapLink2)\n\nkingMap=waCounties[waCounties.JURISDIC_2==\"King\"]\n\n#%%\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()#plt.subplots(figsize=(10,6))\n# zooming area:\nax.set_xlim(kingMap.total_bounds[0:4:2]) #recovering indices\nax.set_ylim(kingMap.total_bounds[1:5:2]) #recovering indices\n# maps of WASHINGTON\nBorder= waBorder.plot(edgecolor='grey',color='white',ax=ax)\nZips=wazipMap.plot(edgecolor='silver',color='whitesmoke',ax=Border)\n# ZOOMING IN:\nWApoints.plot(color='black',markersize=0.1,alpha=0.1,ax=Border)\nplt.show()\n\n\n\n\n#%%\n# keeping non-missing data\nallZip=allZip[~allZip.total.isnull()]\n\n#plotting absolute values\n#forDems\nBorder= waBorder.plot(edgecolor='grey',color='red')\nallZip.plot(column='DEMOCRAT',ax=Border)\n\n#forAll\nBorder= waBorder.plot(edgecolor='grey',color='red')\nallZip.plot(column='total',ax=Border)\n\n#plotting relative values\nBorder= waBorder.plot(edgecolor='grey',color='red')\nallZip['DemChoro'] = allZip.DEMOCRAT / allZip.total\nallZip.plot(column='DemChoro',legend=True,ax=Border,\n legend_kwds={'shrink': 0.6}) #shrink legend size\n\n#%%\n\n## geoplot\n#plotting absolute values\n#forDems\nBorder = gplt.polyplot(waBorder,\n edgecolor='grey', \n facecolor='red')\ngplt.choropleth(allZip, hue='DEMOCRAT',ax=Border)\n\n#forAll\nBorder = gplt.polyplot(waBorder,\n edgecolor='grey', \n facecolor='red')\ngplt.choropleth(allZip, hue='total',ax=Border)\n\n#plotting relative values\nBorder = gplt.polyplot(waBorder,\n edgecolor='grey', \n facecolor='red')\ngplt.choropleth(allZip, hue='DemChoro',ax=Border, legend=True)\n\n\n\n#%%\n\n\nlink3='raw/master/covidCountyWA.csv'\nLINK=link1 + link3\n#getting the data TABLE from the file in the cloud:\ncovid=pd.read_csv(LINK)\n\n#%%\n\ncovidMap=pd.merge(waCounties.loc[:,[\"JURISDIC_2\",\"geometry\"]],covid,\n left_on=\"JURISDIC_2\",right_on=\"County\")\n\n\n#%%\n\nimport mapclassify as mc\n\n#well-known styles\n#geopandas for Equal intervals\ncovidMap.plot(column='CasesPer100k',\n scheme='EqualInterval', \n k=5,\n cmap='OrRd',\n legend=True)\n#%%\n#geopandas for Quantiles\ncovidMap.plot(column='CasesPer100k',\n scheme='Quantiles', \n k=5,\n cmap='OrRd',\n legend=True)\n\n#%%\n\n#well-known styles\n#geoplot for Equal intervals\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.EqualInterval(covidMap.CasesPer100k,k=5),\n cmap='OrRd',\n legend=True)\n#%%\n#geoplot for Quantiles\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.Quantiles(covidMap.CasesPer100k, k=5),\n cmap='OrRd',\n legend=True)\n\n#%%\n#optimization styles in geopandas\ncovidMap.plot(column='CasesPer100k',\n scheme='FisherJenks', \n k=5,\n cmap='OrRd',\n legend=True)\n#%%\ncovidMap.plot(column='CasesPer100k',\n scheme='HeadTailBreaks',\n cmap='OrRd',\n legend=True)\n#%%\n#optimization styles in geoplot\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.FisherJenks(covidMap.CasesPer100k, k=5),\n cmap='OrRd',\n legend=True)\n#%%\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.HeadTailBreaks(covidMap.CasesPer100k),\n cmap='OrRd',\n legend=True)\n\n#%%\n#new variable\nvaluesNew=100000*(covidMap.Deaths/covidMap.Population)\ncovidMap['DeathsPer100k']=valuesNew\n\n#%%\nimport geoplot.crs as gcrs #activating!\n\n#border\nborder=gplt.polyplot(df=covidMap,\n projection=gcrs.Mercator(),#reproject\n edgecolor='gray', #border\n facecolor='gainsboro') #fill of polygon\n#area and color\ngplt.cartogram(df=covidMap,#map\n scheme=mc.EqualInterval(covidMap.DeathsPer100k,k=3),\n cmap=plt.get_cmap('YlGnBu',3),#palette\n hue=\"DeathsPer100k\", #var for color \n scale='CasesPer100k',#var for resize\n limits=(0.3, 1), #limits cartogram polygons \n edgecolor='None', #no border\n legend=True,\n legend_var='hue', #legend of what\n legend_kwargs={'bbox_to_anchor': (0.1, 0.4),#location\n 'frameon': True, #with frame?\n 'markeredgecolor':'k',\n 'title':\"DeathsPer100k\"},\n ax=border)\n#%%\n# mapOfPoints\n\nimport geoplot.crs as gcrs #activating!\n\n#borders\ncountyBorders = gplt.polyplot(df=covidMap, \n projection=gcrs.Mercator(),#HERE!\n edgecolor='grey',\n facecolor='gainsboro')\n\n#points scaled\ncovidMap['centroid']=covidMap.centroid #compute centroids\ngplt.pointplot(df=covidMap.set_geometry('centroid'), #set geometry\n scheme=mc.EqualInterval(covidMap.DeathsPer100k,k=3),\n cmap='YlGnBu',#palette\n hue=\"DeathsPer100k\", \n scale='CasesPer100k', #sizes of points \n limits=(4, 40), #range for sizes of points \n legend=True,\n legend_var='hue',\n legend_kwargs={'bbox_to_anchor': (1, 1),\n 'frameon': True,\n 'markeredgecolor':'k',\n 'title':\"DeathsPer100k\"},\n extent = covidMap.total_bounds,\n ax=countyBorders)\nplt.show()\n\n\n#%%\n\ncounties=gplt.polyplot(waCounties,edgecolor= 'silver')\n\ngplt.kdeplot(WApoints,\n shade=False,\n shade_lowest=False,\n ax=counties)\n\n\n#%% for republicans\n\ncounties=gplt.polyplot(waCounties,edgecolor= 'black',\n projection=gcrs.Mercator())#reproject)\n\ngplt.kdeplot(WApoints[WApoints.party=='REPUBLICAN'], #subset\n shade=True, \n cmap='Reds',\n shade_lowest=False,\n ax=counties,\n extent=kingMap.total_bounds)\n\n\n#%% for democrats\n\ncounties=gplt.polyplot(waCounties,edgecolor= 'black',\n projection=gcrs.Mercator())#reproject)\ngplt.kdeplot(WApoints[WApoints.party=='DEMOCRAT'], #subset\n shade=True, \n cmap='Blues',\n shade_lowest=False,\n ax=counties,\n extent=kingMap.total_bounds)\n\n\n#%% \n\nimport matplotlib.pyplot as plt\n#import matplotlib.cbook as cbook\nfrom matplotlib_scalebar.scalebar import ScaleBar\n\nplt.figure()\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.HeadTailBreaks(covidMap.CasesPer100k),\n cmap='OrRd',\n legend=True)\n#image = plt.imread(cbook.get_sample_data('grace_hopper.png'))\n#plt.imshow(image)\nscalebar = ScaleBar(1,'m') # 1 pixel = 0.2 meter\nplt.gca().add_artist(scalebar)\nplt.show()\n\n#%%\n\nfig, ax = plt.subplots(figsize=(10, 10))\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.HeadTailBreaks(covidMap.CasesPer100k),\n cmap='OrRd',\n legend=True,\n legend_kwargs={'bbox_to_anchor': (1, 1),\n 'frameon': True,\n 'markeredgecolor':'k',\n 'title':\"DeathsPer100k\"},\n extent = covidMap.total_bounds,\n ax=ax)\n\nx, y, arrow_length = 0, 0.3, 0.3\nax.annotate('N', xy=(x, y), \n xytext=(x, y-arrow_length),\n arrowprops=dict(facecolor='black',\n width=5,\n headwidth=15),\n ha='center', va='center', fontsize=20,\n xycoords=ax.transAxes)\nplt.show()\n\n","sub_path":"python/geospatial.py","file_name":"geospatial.py","file_ext":"py","file_size_in_byte":13715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181325218","text":"# -*- coding: ISO-8859-1 -*-\nimport localconfig\nimport ConfigParser \nimport tasbot\nfrom tasbot.customlog import Log\n \nclass LoadCFG:\n\tdef __init__ (self, Class):\n\t\tself.Server = Class\n\t\tself.Debug = Class.Debug\n\t\tself.LoadCFG ()\n\t\n\tdef LoadCFG (self):\n\t\tself.Debug (\"Load CFG\")\n\t\ttry:\n\t\t\tself.Server.Config = localconfig.Server\n\t\texcept:\n\t\t\tLog.Error('using default server config')\n\t\t\tself.Server.Config = {\n\t\t\t\t'LobbyServer':{'Host':'springrts.com', 'Port':8200},\n\t\t\t\t'MainAccount':'[pyah]Master',\n\t\t\t\t'UnitsyncPath':'/usr/lib/libunitsync.so',\n\t\t\t\t'SpringExec':'/usr/bin/spring-dedicated'\n\t\t\t}\n\t\ttry:\n\t\t\tself.Server.Groups = localconfig.Groups\n\t\texcept:\n\t\t\tLog.Error('using default server config')\n\t\t\tself.Server.Groups = {\n\t\t\t\t'pyah':{\n\t\t\t\t\t'Mod':'Evolution RTS - v1.5',\n\t\t\t\t\t'Map':'Comet Catcher Redux',\n\t\t\t\t\t'ChannelsReport':[['autohostdev']],\n\t\t\t\t\t'Accounts':[('[pyah]Host_01','PASSWORD',0)]\n\t\t\t\t},\n\t\t\t}\n\t\tself.IP = localconfig.IP\n\t\t\n\t\tself.Server.AccessCommands = {\n\t\t\t'code':['owner', 'admin'],\n\t\t\t'udp':['owner'],\n\t\t\t'start':['owner', 'admin', '%BattlePlayer%'],\n\t\t\t'kick':['owner', 'admin', 'operator'],\n\t\t\t'ring':['admin', 'operator', '%BattlePlayer%', '%GamePlayer%'],\n\t\t}\n\t\tself.Server.AccessRoles = {\n\t\t\t'owner':{\n\t\t\t\t'[CN]Zydox':1,\n\t\t\t\t'_koshi_':1,\n\t\t\t\t'BrainDamage':1,\n\t\t\t},\n\t\t\t'admin':{\n\t\t\t\t'[CN]Zydox':1,\n\t\t\t\t'_koshi_':1,\n\t\t\t\t'BrainDamage':1,\n\t\t\t},\n\t\t\t'operator':{\n\t\t\t},\n\t\t}\n","sub_path":"loadCFG.py","file_name":"loadCFG.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274598891","text":"import io\nimport os\nimport time\nimport re\nimport string\nfrom json import dumps\nfrom PIL import Image, ImageFilter\n\nimport requests\n# import spacy\n# from tesserocr import PyTessBaseAPI\nimport numpy as np\nimport pandas as pd\nfrom keras.preprocessing import image\nfrom keras.applications.inception_v3 \\\n import InceptionV3, decode_predictions, preprocess_input\n\nfrom nk_croc.is_a import isa_dict\nfrom nk_croc.id_mapping import id_mapping_dict\n\nrequests_session = requests.Session() if os.environ.get('USE_REQUESTS_SESSION') == \"True\" else requests\n# GET_IMAGE_TIMEOUT is max number of seconds to wait before triggering timeout error when downloading an image\nget_image_timeout = int(os.environ.get(\"GET_IMAGE_TIMEOUT\", \"10\"))\n\nclass Croc():\n\n def __init__(self):\n self.target_size = (299, 299)\n self.model = InceptionV3(weights='imagenet')\n # self.nlp = spacy.load('en_core_web_md')\n self.n_top_preds = 10\n # self.isa_dict = isa_dict\n # self.id_mapping_dict = id_mapping_dict\n\n def load_image(self, img_path, prep_func=lambda x: x):\n ''' load image given path and convert to an array\n '''\n img = image.load_img(img_path, target_size=self.target_size)\n x = image.img_to_array(img)\n return prep_func(x)\n\n def load_image_from_web(self, image_url):\n ''' load an image from a provided hyperlink\n '''\n # get image with timout\n # More info on using request with timeouts: http://docs.python-requests.org/en/master/user/quickstart/#timeouts\n response = requests_session.get(image_url, timeout=get_image_timeout)\n with Image.open(io.BytesIO(response.content)) as img:\n # fill transparency if needed\n if img.mode in ('RGBA', 'LA'):\n img = self.strip_alpha_channel(img)\n\n # convert to jpeg\n if img.format is not 'jpeg':\n img = img.convert('RGB')\n img.save('target_img.jpg')\n\n def validate_url(self, url):\n url_validator = re.compile(\n r'^(?:http|ftp)s?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' #domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n\n return bool(url_validator.match(url))\n\n def cleanup_text(self, raw_chars):\n ''' use spacy to clean text and find tokens\n '''\n doc = self.nlp(raw_chars, disable=['parser', 'ner'])\n\n # grab raw text while removing any hanging newlines\n text = [t.text for t in doc if t.text.replace(' ', '').replace('\\n', '')]\n\n tokens = [tok.lemma_.strip() for tok in doc\n if self.nlp.vocab.has_vector(str(tok)) and # is_oov currently (v2.0.11) broken\n tok.lemma_ != '-PRON-']\n\n tokens = [tok for tok in tokens\n if tok not in self.nlp.Defaults.stop_words and\n tok not in string.punctuation]\n\n return dict(tokens=list(set(tokens)), text=text)\n\n def classify_objects(self, image_array, decode_func):\n ''' Returns binary array with ones where the model predicts that\n the image contains an instance of one of the target classes\n (specified by wordnet id)\n '''\n predictions = self.model.predict(image_array)\n # decode the results into list of tuples (class, description, probability)\n predictions = decode_func(predictions, top=self.n_top_preds)\n return predictions\n\n def strip_alpha_channel(self, image, fill_color='#ffffff'):\n ''' Strip the alpha channel of an image and fill with fill color\n '''\n background = Image.new(image.mode[:-1], image.size, fill_color)\n background.paste(image, image.split()[-1])\n return background\n\n def char_detect(self, img_path):\n ''' Run tesseract ocr on an image supplied\n as an image path.\n '''\n with PyTessBaseAPI() as ocr_api:\n with Image.open(img_path) as image:\n # fill image alpha channel if it exists\n if image.mode in ('RGBA', 'LA'):\n image = self.strip_alpha_channel(image)\n\n # will need a better preprocessing approach here\n # if we stay with tesseract:\n image = image.convert('L')\n # image = image.filter(ImageFilter.SHARPEN)\n # image = image.filter(ImageFilter.EDGE_ENHANCE)\n\n\n ocr_api.SetImage(image)\n raw_chars = ocr_api.GetUTF8Text()\n # char_confs = ocr_api.AllWordConfidences()\n\n text = self.cleanup_text(raw_chars)\n\n return text\n\n def climb_hierarchy(self, objects):\n\n def climb(self, object_, tree_):\n ''' function to climb the wordnet tree hierarchy and\n return the concepts along the branch.\n '''\n try:\n target_id = self.isa_dict[object_]\n target_label = self.id_mapping_dict[object_]\n tree_.append(dict(id=target_id, labels=target_label))\n climb(self, target_id, tree_)\n\n except Exception as e:\n e\n\n return tree_\n\n # trace branch to root for each object\n object_trees = list()\n for object_ in objects:\n tree_ = list()\n\n complete_tree = climb(self, object_, tree_)\n object_trees.extend(complete_tree)\n\n return object_trees\n\n def predict(self, input_path):\n ''' Produce predictions for objects and text\n '''\n image_path = input_path\n\n if self.validate_url(image_path):\n filename = 'target_img.jpg'\n self.load_image_from_web(image_path)\n else:\n filename = image_path\n\n print('preprocessing image')\n X = np.array(\n [self.load_image(\n filename, prep_func=preprocess_input)])\n\n print('making object predictions')\n object_predictions = self.classify_objects(X, decode_predictions)\n\n object_predictions = pd.DataFrame.from_records(\n object_predictions[0], columns=['id', 'label', 'confidence'])\n\n # object_trees = self.climb_hierarchy(objects=object_predictions['id'])\n\n # print('performing character recognition')\n # char_predictions = self.char_detect(filename)\n\n if filename == 'target_img.jpg':\n os.remove('target_img.jpg')\n\n return dumps(dict(\n objects=object_predictions.to_dict(),\n object_trees='',\n text='',\n tokens=''))\n\n\nif __name__ == '__main__':\n client = Croc()\n image_path = 'http://i0.kym-cdn.com/photos/images/facebook/001/253/011/0b1.jpg'\n result = client.predict(input_path=image_path)\n print(result)\n","sub_path":"nk_croc/nk_croc.py","file_name":"nk_croc.py","file_ext":"py","file_size_in_byte":6996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"627214791","text":"import subprocess\nimport time\n\ncommand = \"ping www.google.com -t\"\nlast_timeout = []\ntimeout_markers = [\"timed out\", \"unreachable\"]\nprocess = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)\nfor line in iter(process.stdout.readline, \"\"):\n time.sleep(1)\n print(\"Current ping: {}\".format(line), end=\"\")\n if any([marker in line for marker in timeout_markers]):\n \tlast_timeout += [time.time()]\n if last_timeout: \n \ttimes = sorted([round(time.time() - timeout) for timeout in last_timeout])\n \tprint(\"Time outs [{}]: {} seconds\".format(len(times), times))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513963689","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 19 18:39:26 2017\n\n@author: vsankar.la\n\"\"\"\nimport time\ntry:\n i=0\n while True:\n print(\"Hello\")\n i+=1\n if i>3:\n print(\"End of the loop\")\n break\n time.sleep(i)\n\n\nexcept Exception as e:\n print(e)","sub_path":"notes/PythonProblems/problem60.py","file_name":"problem60.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"126473586","text":"import pickle\nfrom utils import save_data_with_pickle, load_data_with_pickle\nfrom EntityEmbedder import EntityEmbedder\nfrom CorpusManager import CorpusManager\n\n\n# PATH in which utility files are stored\nPICKLES_PATH = '../../source_files/pickles/'\n\nFILE_ID = '18_3_max2words_100000'\nLENGTH = 100000\n\nOCCURRENCE_OF_ENTITIES_PATH = PICKLES_PATH + FILE_ID + 'word_occurrence_indexes'\nENTITY_DICT_PATH = PICKLES_PATH + FILE_ID + 'found_entity_dict'\n\nCORPUS_PATH = '/datahdd/vmanuel/ELMo/Corpora/shuffled_text_with_words'\n\nDATA_PATH = '../../source_files/vectors/'\nX_PATH = DATA_PATH + FILE_ID + 'X'\nY_PATH = DATA_PATH + FILE_ID + 'Y'\nentities_PATH = DATA_PATH + FILE_ID + 'entities'\n\nif __name__ == \"__main__\":\n entity_dict = load_data_with_pickle(ENTITY_DICT_PATH)\n\n c = CorpusManager()\n c.read_corpus(CORPUS_PATH, LENGTH)\n\n entity_embedder = EntityEmbedder()\n entity_embedder.setup(model_name = entity_embedder.ELMO_NAME,\n extraction_mode = entity_embedder.LAYER_2,\n occurrences_of_entities_path = OCCURRENCE_OF_ENTITIES_PATH,\n aggregation_method = entity_embedder.VECTOR_MEAN,\n corpus = c.corpus\n )\n\n entity_embedder.create_embedding_data_structure()\n entity_embedder.extract_vectors_of_occurrences_in_corpus()\n entity_embedder.create_dataset(entity_dict = entity_dict, \n X_PATH = X_PATH,\n Y_PATH = Y_PATH,\n entities_PATH = entities_PATH)\n\n\n ","sub_path":"preprocessing/generate_embedding_and_dataset_main_flow.py","file_name":"generate_embedding_and_dataset_main_flow.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"225045687","text":"import numpy as np\nfrom matplotlib import gridspec\nfrom IPython.display import display, HTML\nimport copy\nimport math\nimport time\n\n# import custom JS animator\nfrom mlrefined_libraries.JSAnimation_slider_only import IPython_display_slider_only\n \n# import standard plotting and animation\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import clear_output\nfrom matplotlib import gridspec\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n######### centering and contrast-normalizing #########\ndef center(X):\n '''\n A function for normalizing each feaure dimension of an input array, mean-centering\n and division by its standard deviation\n \n '''\n X_means = np.mean(X,axis=0)[np.newaxis,:]\n X_normalized = X - X_means\n\n return X_normalized\n\ndef contrast_normalize(X):\n '''\n A contrast-normalizing function for image data pre-sphereing normalization.\n \n '''\n # compute and subtract off means\n X_means = np.mean(X,axis=0)[np.newaxis,:]\n X = X - X_means\n \n # divide off std of each image - remove any images deemed constant (whose std = 0)\n X_stds = np.std(X,axis=0)[np.newaxis,:]\n ind = np.argwhere(np.abs(X_stds) > 10**(-7))\n ind = np.array([s[1] for s in ind])\n X = X[:,ind]\n X_stds = X_stds[:,ind]\n X_normalized = X/X_stds\n \n # print report to user if any patches deemed constant\n report = np.shape(X_means)[1] - len(ind) \n if report > 0:\n print (str(report) + ' images of ' + str(np.shape(X_means)[1]) + ' imagses found to be constant, and so were removed')\n\n return X_normalized\n\n########## sphereing pre-processing functionality ##########\ndef compute_pcs(X,lam):\n '''\n A function for computing the principal components of an input data matrix. Both\n principal components and variance parameters (eigenvectors and eigenvalues of XX^T)\n are returned\n '''\n # create the correlation matrix\n P = float(X.shape[1])\n Cov = 1/P*np.dot(X,X.T) + lam*np.eye(X.shape[0])\n\n # use numpy function to compute eigenvalues / vectors of correlation matrix\n D,V = np.linalg.eigh(Cov)\n return V, D\n\ndef pca_transform_data(X,**kwargs):\n '''\n A function for producing the full PCA transformation on an input dataset X. \n '''\n # user-determined number of principal components to keep, and regularizer penalty param\n num_components = X.shape[0]\n if 'num_components' in kwargs:\n num_components = kwargs['num_components']\n lam = 10**(-7)\n if 'lam' in kwargs:\n lam = kwargs['lam']\n \n # compute principal components\n V,D = compute_pcs(X,lam)\n V = V[:,-num_components:]\n D = D[-num_components:]\n\n # compute transformed data for PC space: V^T X\n W = np.dot(V.T,X)\n return W,V,D\n \ndef PCA_sphere(X,**kwargs):\n '''\n A function for producing the full PCA sphereing on an input dataset X. \n '''\n # compute principal components\n W,V,D = pca_transform_data(X,**kwargs)\n \n # compute transformed data for PC space: V^T X\n W = np.dot(V.T,X)\n D_ = np.array([1/d**(0.5) for d in D])\n D_ = np.diag(D_)\n S = np.dot(D_,W)\n return W,S\n\ndef ZCA_sphere(X,**kwargs):\n '''\n A function for producing the full PCA sphereing on an input dataset X. \n ''' \n \n # compute principal components\n W,V,D = pca_transform_data(X,**kwargs)\n \n # PCA-sphere data\n W = np.dot(V.T,X)\n D_ = np.array([1/d**(0.5) for d in D])\n D_ = np.diag(D_)\n S = np.dot(D_,W)\n \n # rotate data back to original orientation - ZCA sphere\n Z = np.dot(V,S)\n \n return W,S,Z\n\n########## plotting functionality ############\ndef show_images(X):\n '''\n Function for plotting input images, stacked in columns of input X.\n '''\n # plotting mechanism taken from excellent answer from stack overflow: https://stackoverflow.com/questions/20057260/how-to-remove-gaps-between-subplots-in-matplotlib\n plt.figure(figsize = (9,3))\n gs1 = gridspec.GridSpec(5, 14)\n gs1.update(wspace=0, hspace=0.05) # set the spacing between axes. \n \n # shape of square version of image\n square_shape = int((X.shape[0])**(0.5))\n\n for i in range(min(70,X.shape[1])):\n # plot image in panel\n ax = plt.subplot(gs1[i])\n im = ax.imshow(255 - np.reshape(X[:,i],(square_shape,square_shape)),cmap = 'gray')\n\n # clean up panel\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n plt.show()","sub_path":"mlrefined_libraries/unsupervised_library/PCA_functionality.py","file_name":"PCA_functionality.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"465917651","text":"from os import error\nfrom PIL import Image\nfrom quantize import quantize\nfrom pathlib import Path\n\ndef parameterization():\n img = Image.open(\"./demoInput.jpg\")\n pixels = img.load()\n dims = img.size\n\n minCellDims = [8, 8]\n\n if(dims[0] != dims[1]):\n error(\"The code currently only works for sqaure images.\")\n for minCellDims in [ [4, 4], [6, 6], [10, 10] ]:\n for thresh in [ 6900, 42000, 420000, 690000 ]:\n for edgeType in [ \"inv\", \"black\", \"white\", \"darken\", \"lighten\" ]:\n print(\"{e} | {t} | {w}x{h}\".format(e=edgeType, t=thresh, w=minCellDims[0], h=minCellDims[1]))\n\n out = Image.new(mode=\"RGB\", size=dims)\n quantize(\n cell=[ 0, 0, dims[0], dims[1] ], \n inputPixels=pixels, \n outputImage=out, \n thresh=thresh, \n minCellDims=minCellDims,\n showEdges=True, \n edgeType=edgeType\n )\n path = Path(\"./demoOut/out_{thresh}_{edge}_min{w}x{h}.png\".format(thresh=thresh, edge=edgeType, w=minCellDims[0], h=minCellDims[1]))\n out.save(path)\n out.close()\n\ndef test():\n img = Image.open(\"./laikka.jpg\")\n pixels = img.load()\n dims = img.size\n\n minCellDims = [6, 6]\n\n thresh = 69420\n\n for edgeType in [ \"inv\", \"black\", \"white\" ]:\n out = Image.new(mode=\"RGB\", size=dims)\n quantize(\n cell=[ 0, 0, dims[0], dims[1] ], \n inputPixels=pixels, \n outputImage=out, \n thresh=thresh, \n minCellDims=minCellDims,\n showEdges=True, \n edgeType=edgeType\n )\n path = Path(\"./demoOut/out_{thresh}_{edge}_min{w}x{h}.png\".format(thresh=thresh, edge=edgeType, w=minCellDims[0], h=minCellDims[1]))\n out.save(path)\n out.close()\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"586819982","text":"###################################################################################\n# pop uo three new windows, with style\n# destroy() kills one window, quit() kill all windows and app; top-level\n# windows have title, icon, iconify/deconify and protocol for wm events;\n# there always is an app root window, whether by default or created as an\n# explicit Tk object; alll top-level windows are containers, but never\n# packed/gridded; Toplevel is like frame, but new windows, and can have menus;\n###################################################################################\n\nfrom Tkinter import *\nfrom tkSimpleDialog import askstring\n\ndef getName():\n label = askstring('Would you kindly', 'Enter your name?: ')\n root.title(label)\n\nroot = Tk() # exlicit root\nname = 'Phillip'\n\n# win = Toplevel(root) \n# win.title(name) \n\n\nmsg = Button(root, text=name, command=getName)\nmsg.pack(expand=YES, fill=BOTH)\nmsg.config(padx=10, pady=10, bd=10, relief=RAISED)\nmsg.config(bg='black', fg='white', font=('times', 30, 'bold italic'))\n\nroot.mainloop()\n","sub_path":"Python/ProgramPython/c9/experiment/askForNameGUI.py","file_name":"askForNameGUI.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554881153","text":"array = [1, 3, 9, 8, 2, 7, 5]\n\niCount = 0\n\ndef iSort(arr, start, end):\n global iCount\n for i in range(start + 1, end + 1):\n j = i \n while(j > 0 and arr[j - 1] > arr[j]):\n \n j -= 1\n iCount = iCount + 1\n arr[j + 1] = key\n \n return arr\n \niSort(array, 0, 6)\n\nprint(array)\n","sub_path":"Insertion_sort.py","file_name":"Insertion_sort.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"602790854","text":"# https://www.hackerrank.com/challenges/candies/problem\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the candies function below.\ndef candies(n, arr):\n toffee = [0]*n\n\n # forward pass\n toffee[0] = 1\n for i in range(1, n):\n if(arr[i] > arr[i-1]):\n toffee[i] = toffee[i-1] + 1\n else:\n toffee[i] = 1\n\n # backward pass\n for i in range(n-2, -1, -1):\n if(arr[i] > arr[i+1]):\n toffee[i] = max(toffee[i+1] + 1, toffee[i])\n \n # count the total toffees\n total = 0\n for i in range(n):\n total += toffee[i]\n\n return total\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n arr = []\n\n for _ in range(n):\n arr_item = int(input())\n arr.append(arr_item)\n\n result = candies(n, arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"Hackerrank/Array/Candies.py","file_name":"Candies.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"434101355","text":"from sys import stdin\ndef solve(l):\n if len(l)%2 !=0:\n print((l[len(l)//2])/1)\n else:\n print((l[len(l)//2] + l[(len(l)//2)-1])/2)\ndef main():\n n,l= int(stdin.readline().strip()), []\n for elm in range(n):\n m= int(stdin.readline().strip())\n l.append(m)\n l.sort()\n solve(l)\nmain()\n","sub_path":"laboratorios/Lab-9/B/2_.py","file_name":"2_.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"17459495","text":"\"\"\"\nWAR CARD GAME\n\"\"\"\nfrom random import shuffle\n\ncolors=(\"Spades\",\"Hearts\",\"Clubs\",\"Diamonds\")\nfigures=(\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Ten\",\"Jack\",\"Queen\",\"King\",\"Ace\")\ncards_and_values={'Two':2,\"Three\":3,\"Four\":4,\"Five\":5,\"Six\":6,\"Seven\":7,\"Eight\":8,\"Nine\":9,\\\n\"Ten\":10,\"Jack\":11,\"Queen\":12,\"King\":13,\"Ace\":14}\n\nclass Card():\n \"\"\"\n Class CARD\n \"\"\"\n def __init__(self,color_card,figure):\n self.color_card=color_card\n self.figure=figure\n self.value = cards_and_values[figure]#value of card,the higher card has higher the value\n\n def __str__(self):\n return f\"{self.figure} {self.color_card}\"\n\n def __repr__(self):\n return self.__str__()\n\nclass Deck():\n \"\"\"\n CLASS DECK\n \"\"\"\n def __init__(self):\n self.all_of_cards =[]\n #how many cards are in the deck\n def __len__(self):\n \"\"\"\n how many cards are in the deck\n \"\"\"\n return len(self.all_of_cards)\n\n def create_deck_of_cards(self):\n \"\"\"\n create deck\n \"\"\"\n for color_card in colors :\n for card_figure in figures:\n new_card=Card(color_card,card_figure)\n self.all_of_cards.append(new_card)\n \"\"\"\n for unit test add new method\n \"\"\"\n def add_cards_to_deck(self,deck):\n self.all_of_cards.extend(deck)\n\n def shuffle(self):\n \"\"\"\n shuffle deck\n \"\"\"\n shuffle(self.all_of_cards)\n\nclass Player():\n \"\"\"\n CLASS PLAYER\n \"\"\"\n def __init__(self,name):\n self.name=name\n self.cards=[]\n\n def __str__(self):\n return f\"Player {self.name} has {len(self.cards)}\"\n\n def add_cards(self,new_cards):\n \"\"\"\n add cards to player's deck\n \"\"\"\n if isinstance(new_cards,type([])):\n self.cards.extend(new_cards)\n else:\n self.cards.append(new_cards)\n\n def remove_cards(self,card_number):\n \"\"\"\n remove cards from player's deck\n \"\"\"\n del self.cards[0:card_number+1]\n\n\ndef main(set_of_cards):\n \"\"\"\n main function\n \"\"\"\n player_one=Player(\"One\")#create player\n player_two=Player(\"Two\")#create player\n my_deck=Deck()\n my_deck.add_cards_to_deck(set_of_cards)\n player_one.cards=my_deck.all_of_cards[:3]#split deck\n player_two.cards=my_deck.all_of_cards[3:6]#split deck\n print(\"Start a game:\")\n game_on=True\n war_round=1\n result=0\n #GAME START\n while game_on:#check game on\n #Check if player one's deck is empty\n #if player one's deck is empty, player 2 will win\n if len(player_one.cards)==0:\n print(\"Congratulions. Win player 2\")\n result=2\n break\n #Check if player second's deck is empty\n #if it is empty, player 1 will win\n if len(player_two.cards)==0:\n print(\"Congratulions. Win player 1\")\n result=1\n break\n\n print(f\"{war_round} round\")\n\n card_index=0\n #if first player's card is equal to second player's card\n #there is war and check next cards until if any of player win round\n #counter is incremented by 2,because we check every second card\n while card_index<26:\n #Battle\n if card_index>=2:#if value of player one's cards is equal to value of player two a draw, it will be War\n print(\"War\")\n if player_one.cards[card_index].value > player_two.cards[card_index].value: #if player one's card is better than player two's card\n player_one.remove_cards(card_index+1)\n player_two.remove_cards(card_index+1)\n player_one.add_cards(player_one.cards[:card_index+1])\n player_one.add_cards(player_two.cards[:card_index+1])\n print(f\"Win player 1 in the {war_round} round\")\n break\n elif player_one.cards[card_index].value < player_two.cards[card_index].value:#if player two's card is better than player one's card\n player_one.remove_cards(card_index+1)\n player_two.remove_cards(card_index+1)\n player_two.add_cards(player_two.cards[:card_index+1])\n player_two.add_cards(player_one.cards[:card_index+1])\n print(f\"Win player 2 in the {war_round} round\")\n break\n else:#if there is draw\n #check how many cards player 1 has\n #if he has less than 3 cards,he loses\n if len(player_one.cards)<3:\n print(\"Player One unable to declare war\")\n print(\"Congratulions. Win player 2\")\n game_on=False\n result=2\n break\n #check how many cards player 2 has\n #if he has less than 3 cards,he loses\n if len(player_two.cards)<3:\n print(\"Player Two unable to declare war\")\n print(\"Congratulions. Win player 1\")\n game_on=False\n result=1\n break\n #if players have more than 3 cards\n #players will take next cards and check the following value of cards again\n else:\n card_index+=2\n continue\n war_round+=1\n return result\n\ncards=[Card(\"Spades\",\"Ten\"),Card(\"Hearts\",\"Nine\"),Card(\"Clubs\",\"Eight\"),\\\n Card(\"Hearts\",\"Seven\"),Card(\"Clubs\",\"Six\"),Card(\"Clubs\",\"Five\")]\nmain(cards)\n","sub_path":"war_card_game_code_to_unit_test.py","file_name":"war_card_game_code_to_unit_test.py","file_ext":"py","file_size_in_byte":5551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"596249841","text":"import math\nimport random\nimport libpyDirtMP as prx\n\n\nprx.init_random(random.randint(1,999999))\nacrobot = prx.two_link_acrobot(\"acrobot\")\nsimulation_step = 0.01\nprx.set_simulation_step(simulation_step)\nprint(\"Using simulation_step:\", simulation_step)\n\nstart_state = [0, 0, 0, 0]\ngoal_state = [math.pi, 0, 0, 0]\n\n\nobs_pose_1 = prx.transform()\nobs_pose_2 = prx.transform()\nobs_pose_3 = prx.transform()\nobs_pose_4 = prx.transform()\nobs_pose_1.setIdentity()\nobs_pose_2.setIdentity()\nobs_pose_3.setIdentity()\nobs_pose_4.setIdentity()\nobs_pose_1.translation(prx.vector( 20, 20,0.5))\nobs_pose_2.translation(prx.vector(-20, 20,0.5))\nobs_pose_3.translation(prx.vector( 20,-20,0.5))\nobs_pose_4.translation(prx.vector(-20,-20,0.5))\nb1 = prx.box.create_obstacle(\"b1\", 1., 1., 1., obs_pose_1)\nb2 = prx.box.create_obstacle(\"b2\", 1., 1., 1., obs_pose_2)\nb3 = prx.box.create_obstacle(\"b3\", 1., 1., 1., obs_pose_3)\nb4 = prx.box.create_obstacle(\"b4\", 1., 1., 1., obs_pose_4)\n\nobstacles = [b1, b2, b3, b4]\nobs_names = [\"b1\", \"b2\", \"b3\", \"b4\"]\n### To have an obstacle-free environment, uncomment the following lines (and comment the above)\n# obstacles = []\n# obs_names = []\nwm = prx.world_model([acrobot], obstacles)\nwm.create_context(\"context\", [\"acrobot\"], obs_names)\ncontext = wm.get_context(\"context\");\n\nplanner = prx.dirt(\"dirt\");\nplanner_spec = prx.dirt_specification(context.system_group,context.collision_group);\nplanner_spec.blossom_number = 5\nplanner_spec.use_pruning = False\n\n\ndef acrobot_distance_function(s1, s2):\n\tcost = 0\t\n\ts1a0 = s1[0] + prx.PRX_PI\n\ts1a1 = s1[1] + prx.PRX_PI\n\ts1a2 = s1[2] \n\ts1a3 = s1[3] \n\t\t\n\ts2a0 = s2[0] + prx.PRX_PI\n\ts2a1 = s2[1] + prx.PRX_PI\n\ts2a2 = s2[2] \n\ts2a3 = s2[3] \n\n\ta0 = min((2 * prx.PRX_PI) - abs(s1a0 - s2a0), abs(s1a0 - s2a0));\n\ta1 = min((2 * prx.PRX_PI) - abs(s1a1 - s2a1), abs(s1a1 - s2a1));\n\ta2 = s1a2 - s2a2;\n\ta3 = s1a3 - s2a3;\n\n\tcost = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3\n\n\treturn math.sqrt(cost);\n\nplanner_spec.distance_function = prx.distance_function.set_df(acrobot_distance_function);\n\nplanner_spec.min_control_steps = 1\nplanner_spec.max_control_steps = 50\n\n# planner_spec.random_seed = random.randint(1,999999);\nplanner_spec.bnb = True;\n\nplanner_query = prx.dirt_query(context.system_group.get_state_space(),context.system_group.get_control_space());\nplanner_query.start_state = context.system_group.get_state_space().make_point()\nplanner_query.goal_state = context.system_group.get_state_space().make_point()\ncontext.system_group.get_state_space().copy_point_from_vector(planner_query.start_state, start_state);\ncontext.system_group.get_state_space().copy_point_from_vector(planner_query.goal_state, goal_state);\n\nprint(\"Start State:\", planner_query.start_state)\nprint(\"Goal State:\", planner_query.goal_state)\n\nplanner_query.goal_region_radius = 0.5;\nplanner_query.get_visualization = True;\n\nplanner.link_and_setup_spec(planner_spec)\nplanner.preprocess()\nplanner.link_and_setup_query(planner_query)\n\n### Note: Python slows down computation ==> more time might be needed\n# checker = prx.condition_check(\"time\", 60)\nchecker = prx.condition_check(\"iterations\", 50000)\n\nprint(\"Resolving query...\")\nplanner.resolve_query(checker)\nplanner.fulfill_query();\n\n\n### This part is only to visualize the solution\nif (planner_query.get_visualization):\n\tvis_group = prx.three_js_group([acrobot], obstacles)\n\tif ( len(planner_query.solution_traj) != 0 ) :\n\t\tvis_group.add_vis_infos(prx.info_geometry.FULL_LINE, planner_query.solution_traj, \"acrobot/ball\", context.system_group.get_state_space(), \"0x000000\");\n\n\ttimestamp = 0.0\n\tfor state in planner_query.solution_traj :\n\t\tcontext.system_group.get_state_space().copy_from_point(state);\n\t\tvis_group.snapshot_state(timestamp)\n\t\ttimestamp += simulation_step\n\n\tvis_group.output_html(\"py_output.html\");\n","sub_path":"examples/basic/acrobot/dirt.py","file_name":"dirt.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"490928276","text":"from setuptools import setup, find_packages\r\nimport redpic\r\n\r\nwith open(\"README.md\", \"r\") as fh:\r\n long_description = fh.read()\r\n\r\nsetup(\r\n name='redpic',\r\n version=redpic.__version__,\r\n author='Vyacheslav Fedorov',\r\n author_email='fuodorov1998@gmail.com',\r\n description=redpic.__doc__,\r\n long_description=long_description,\r\n long_description_content_type=\"text/markdown\",\r\n url='https://github.com/fuodorov/redpic',\r\n packages=find_packages(),\r\n classifiers=[\r\n \"Programming Language :: Python :: 3\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Operating System :: OS Independent\",\r\n 'Intended Audience :: Science/Research',\r\n 'Topic :: Scientific/Engineering :: Physics'\r\n ],\r\n python_requires='>=3.6',\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"290860852","text":"import string\nimport random\nimport subprocess\n\nword_list = subprocess.check_output(\n \"cat /usr/share/dict/words | grep -v \\\"'s\\\"\",\n shell=True, \n universal_newlines=True\n).split('\\n')\n\n# word_list = ['munchkin', 'cat', 'vex', 'dog', 'doom', 'aardvark', 'recursion', 'dyslexia']\n\nword = random.choice(word_list).upper()\nblanks = [\"_\"] * len(word)\navailable_guesses = 10\nnum_bad_guess = 0\nplayer_guesses = []\nwinner = False\n\n\ndef get_input():\n invalid = True\n while invalid:\n print(\"You have guessed: {}\".format(', '.join(sorted(player_guesses)) if player_guesses else ''))\n guess = input(\"Guess letter: \").upper()\n if len(guess) > 1:\n print(\"Only guess one letter, dummy.\")\n elif guess in player_guesses:\n print(\"You've already guessed that letter, dummy.\")\n elif guess not in string.ascii_letters:\n print(\"Enter only letters, dummy.\")\n else:\n invalid = False\n return guess\n\n\nwhile num_bad_guess < available_guesses and not winner:\n\n print('\\n({} letters)\\t{}'.format(len(word), ''.join(blanks)))\n \n guess = get_input()\n player_guesses.append(guess)\n\n if guess in word.upper(): \n print(\"You guessed right\")\n indecies = [pos for pos, char in enumerate(word) if char == guess]\n for index in indecies:\n blanks[index] = guess\n else:\n print(\"You guessed wrong\")\n num_bad_guess += 1\n print(\"You've made {}/{} wrong guesses\".format(num_bad_guess, available_guesses))\n\n if ''.join(blanks).upper() == word.upper():\n winner = True\n\nif winner: \n print(\"You have guessed the word! {}\".format(word))\nelse:\n print(\"You lose! The word was {}\".format(word))\n\n\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"462782156","text":"from boa.interop.System.Storage import Put, Get, GetContext\nfrom boa.builtins import concat\n\nfrom boa.interop.System.Storage import Put, Delete\nfrom boa.interop.System.Runtime import CheckWitness, Notify\n\nfrom template_contract_test.libs.SafeCheck import Require, RequireScriptHash,RequireWitness\nfrom template_contract_test.libs.Utils import SafePut\nfrom template_contract_test.libs.SafeMath import Sub, Add\n\n\nTOKEN_NAME = 'My Simple Token'\nTOKEN_SYMBOL = 'MST'\n\n################################################################################\n# TOKEN INFO CONSTANTS\n\n# DEPLOYER is AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p---616f2a4a38396ff203ea01e6c070ae421bb8ce2d\nDEPLOYER = bytearray(b'\\x61\\x6f\\x2a\\x4a\\x38\\x39\\x6f\\xf2\\x03\\xea\\x01\\xe6\\xc0\\x70\\xae\\x42\\x1b\\xb8\\xce\\x2d')\n\nINIT_SUPPLY = 1000000000\nTOKEN_DECIMALS = 8\nFACTOR = 100000000\n\n################################################################################\n# STORAGE KEY CONSTANT\n# Belows are storage key for some variable token information.\n\nOWNER_KEY = '___OWNER'\nMST_SUPPLY_KEY = '__SUPPLY'\n\n\n################################################################################\n# STORAGE KEY PREFIX\n# Since all data are stored in the key-value storage, the data need to be\n# classified by key prefix. All key prefixes length must be the same.\n\nOWN_PREFIX = '_____own'\nALLOWANCE_PREFIX = '___allow'\n\n\n################################################################################\n#\n\ndef Main(operation, args):\n if operation == 'deploy':\n return Deploy()\n elif operation == 'name':\n return TOKEN_NAME\n elif operation == 'decimals':\n return TOKEN_DECIMALS\n elif operation == 'symbol':\n return TOKEN_SYMBOL\n elif operation == 'totalSupply':\n return TotalSupply()\n elif operation == 'balanceOf':\n if len(args) == 1:\n return BalanceOf(args[0])\n elif operation == 'transfer':\n if len(args) == 3:\n return Transfer(args[0], args[1], args[2])\n elif operation == 'transferFrom':\n if len(args) == 4:\n return TransferFrom(args[0], args[1], args[2], args[3])\n elif operation == 'approve':\n if len(args) == 3:\n return Approve(args[0], args[1], args[2])\n elif operation == 'allowance':\n if len(args) == 2:\n return Allowance(args[0], args[1])\n elif operation == 'mint':\n if len(args) == 2:\n return Mint(args[0], args[1])\n elif operation == 'burn':\n if len(args) == 1:\n return Burn(args[0])\n elif operation == 'transferOwnership':\n if len(args) == 1:\n return TransferOwnership(args[0])\n\n return False\n\n\ndef Deploy():\n \"\"\"\n Constructor of this contract. Only deployer hard-coded can call this function\n and cannot call this function after called once.\n Followings are initialization list for this token\n 1. Transfer the owner to the deployer. (Owner can mint and burn the token)\n 2. Supply initial coin to the deployer.\n \"\"\"\n ctx = GetContext()\n\n Require(CheckWitness(DEPLOYER)) # only can be initialized by deployer\n Require(not Get(ctx, 'DEPLOYED')) # only can deploy once\n\n # disable to deploy again\n Put(ctx, 'DEPLOYED', 1)\n\n # the first owner is the deployer\n # can transfer ownership to other by calling `transferOwner` function\n Put(ctx, OWNER_KEY, DEPLOYER)\n\n # supply the coin. All coin will belong to deployer.\n Put(ctx, MST_SUPPLY_KEY, INIT_SUPPLY * FACTOR)\n Put(ctx, concat(OWN_PREFIX, DEPLOYER), INIT_SUPPLY * FACTOR)\n\n return True\n\n\ndef TotalSupply():\n \"\"\"\n Gets the total supply for MST token. The total supply can be changed by\n owner's invoking function calls for minting and burning.\n \"\"\"\n return _totalSupply(GetContext())\n\n\ndef BalanceOf(account):\n \"\"\"\n Gets the MST token balance of an account.\n :param account: account\n \"\"\"\n return _balanceOf(GetContext(), account)\n\n\ndef Transfer(_from, _to, _value):\n \"\"\"\n Sends the amount of tokens from address `from` to address `to`. The parameter\n `from` must be the invoker.\n :param _from: invoker address.\n :param _to: receiver address.\n :param _value: MST amount.\n \"\"\"\n RequireWitness(_from) # from address validation\n return _transfer(GetContext(), _from, _to, _value)\n\n\ndef TransferFrom(_originator, _from, _to, _amount):\n \"\"\"\n Transfers the amount of tokens in `from` address to `to` address by invoker.\n Only approved amount can be sent.\n :param _originator: invoker address.\n :param _from: address for withdrawing.\n :param _to: address to receive.\n :param _amount: MST amount.\n \"\"\"\n return _transferFrom(GetContext(), _originator, _from, _to, _amount)\n\n\ndef Approve(_from, _to, _amount):\n \"\"\"\n Approves `to` address to withdraw MST token from the invoker's address. It\n overwrites the previous approval value.\n :param _from: invoker address.\n :param _to: address to approve.\n :param _amount: MST amount to approve.\n \"\"\"\n RequireWitness(_from) # only the token owner can approve\n return _approve(GetContext(), _from, _to, _amount)\n\n\ndef Burn(_amount):\n \"\"\"\n Burns the amount of MST token from the owner's address.\n :param _amount: MST amount to burn.\n \"\"\"\n ctx = GetContext()\n _onlyOwner(ctx) # only owner can burn the token\n return _burn(ctx, Get(ctx, OWNER_KEY), _amount)\n\n\ndef Mint(_to, _amount):\n \"\"\"\n Mints the amount of MST token.\n :param _to: address to receive token.\n :param _amount: the amount to mint.\n \"\"\"\n ctx = GetContext()\n _onlyOwner(ctx) # only owner can mint token\n return _mint(ctx, _to, _amount)\n\n\ndef TransferOwnership(_account):\n \"\"\"\n Transfers the ownership of this contract to other.\n :param _account: address to transfer ownership.\n \"\"\"\n ctx = GetContext()\n _onlyOwner(ctx)\n return _transferOwnership(ctx, _account)\n\n\ndef Allowance(_from, _to):\n \"\"\"\n Gets the amount of allowance from address `from` to address `to`.\n :param _from: from address\n :param _to: to address\n :return: the amount of allowance.\n \"\"\"\n return _allowance(GetContext(), _from, _to)\n\n\n################################################################################\n# INTERNAL FUNCTIONS\n# Internal functions checks parameter and storage result validation but these\n# wouldn't check the witness validation, so caller function must check the\n# witness if necessary.\n\ndef _transfer(_context, _from, _to, _value):\n Require(_value > 0) # transfer value must be over 0\n RequireScriptHash(_to) # to-address validation\n\n from_val = _balanceOf(_context, _from)\n to_val = _balanceOf(_context, _to)\n\n from_val = Sub(from_val, _value)\n to_val = Add(to_val, _value)\n\n SafePut(_context, concat(OWN_PREFIX, _from), from_val)\n SafePut(_context, concat(OWN_PREFIX, _to), to_val)\n\n Notify([\"transfer\", from_val, to_val, _value])\n\n return True\n\n\ndef _balanceOf(_context, _account):\n return Get(_context, concat(OWN_PREFIX, _account))\n\n\ndef _transferFrom(_context, _owner, _spender, _to, _amount):\n RequireWitness(_owner)\n RequireScriptHash(_spender)\n RequireScriptHash(_to)\n\n Require(_amount > 0)\n\n approve_key = concat(ALLOWANCE_PREFIX, concat(_spender, _owner))\n approve_amount = Get(_context, approve_key)\n approve_amount = Sub(approve_amount, _amount)\n\n\n if not _transfer(_context, _spender, _to, _amount):\n return False\n\n SafePut(_context, approve_key, approve_amount)\n\n Notify([\"transferFrom\", _owner, _spender, _to, _amount])\n\n return True\n\n\ndef _approve(_context, _from, _to, _amount):\n RequireScriptHash(_to) # to-address validation\n Require(_amount >= 0) # amount must be not minus value\n\n from_val = _balanceOf(_context, _from)\n approved_val = _allowance(_context, _from, _to)\n approve_val = Add(approved_val, _amount)\n Require(from_val >= approve_val) # the token owner must have the amount over approved\n\n approve_key = concat(ALLOWANCE_PREFIX, concat(_from, _to))\n SafePut(_context, approve_key, approve_val)\n\n return True\n\n\ndef _burn(_context, _account, _amount):\n Require(_amount > 0) # the amount to burn should be over 0\n\n account_val = _balanceOf(_context, _account)\n total_supply = _totalSupply(_context)\n\n Require(_amount < total_supply) # should be not over total supply\n\n # burn the token from account. It also subtract the total supply\n account_val = Sub(account_val, _amount)\n total_supply = Sub(total_supply, _amount)\n\n SafePut(_context, concat(OWN_PREFIX, _account), account_val)\n SafePut(_context, MST_SUPPLY_KEY, total_supply)\n\n Notify([\"burn\", _account, _amount])\n\n return True\n\n\ndef _mint(_context, _to, _amount):\n Require(_amount > 0) # mint value must be over 0\n RequireScriptHash(_to) # to address should\n\n total_supply = _totalSupply(_context)\n to_val = _balanceOf(_context, _to)\n\n # Add total supply value and give the token to the to-address\n total_supply += _amount\n to_val += _amount\n\n SafePut(_context, MST_SUPPLY_KEY, total_supply)\n SafePut(_context, concat(OWN_PREFIX, _to), to_val)\n\n Notify([\"mint\", _to, _amount])\n\n return True\n\n\ndef _transferOwnership(_context, _account):\n RequireScriptHash(_account)\n Put(_context, OWNER_KEY, _account)\n\n Notify([\"transferOwnership\", _account])\n\n return True\n\n\n################################################################################\n# modifiers\n\ndef _onlyOwner(_context):\n \"\"\"\n Checks the invoker is the contract owner or not. Owner key is saved in the\n storage key `___OWNER`, so check its value and invoker.\n \"\"\"\n RequireWitness(Get(_context, OWNER_KEY))\n\n\n################################################################################\n\ndef _totalSupply(_context):\n return Get(_context, MST_SUPPLY_KEY)\n\n\ndef _allowance(_context, _from, _to):\n return Get(_context, concat(ALLOWANCE_PREFIX, concat(_from, _to)))","sub_path":"MySimpleToken/MySimpleToken.py","file_name":"MySimpleToken.py","file_ext":"py","file_size_in_byte":10117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"243530395","text":"import argparse\nimport os\nfrom termcolor import cprint\n\nfrom MidiGenerator.MidiGenerator import MidiGenerator\n\n\ndef main():\n \"\"\"\n Entry point\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Program to train a model over a Midi dataset',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('load', type=str, default='',\n help='The model of the Neural Network ot load')\n parser.add_argument('-d', '--data', type=str, default='lmd_matched_mini',\n help='The name of the data')\n parser.add_argument('--pc', action='store_true', default=False,\n help='to work on a small computer with a cpu')\n parser.add_argument('--gpu', type=str, default='0',\n help='What GPU to use')\n parser.add_argument('-s', '--seed', default=10,\n help='number of seeds or the path to the folder with the seeds')\n parser.add_argument('-l', '--length', type=int, default=20,\n help='The length of the generated music')\n parser.add_argument('-i', '--images', action='store_true', default=False,\n help='Save the images for each instruments')\n parser.add_argument('--no-duration', action='store_true', default=False,\n help='Generate only shortest notes possible')\n parser.add_argument('-v', '--verbose', type=int, default=1,\n help='Level of verbose')\n\n args = parser.parse_args()\n\n if args.pc:\n data_path = os.path.join('../Dataset', args.data)\n args.length = 50\n args.seed = 2\n else:\n data_path = os.path.join('../../../../../../storage1/valentin', args.data)\n data_transformed_path = data_path + '_transformed'\n\n if not args.pc:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\n my_model = MidiGenerator.with_model(id=args.load) # Load the model\n my_model.generate_fom_data(length=args.length,\n nb_seeds=args.seed,\n save_images=args.images,\n no_duration=args.no_duration,\n verbose=args.verbose)\n\n cprint('---------- Done ----------', 'grey', 'on_green')\n\n\nif __name__ == '__main__':\n # create a separate main function because original main function is too mainstream\n main()\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565898032","text":"subs = {\n 'all' : [ ## Special key: Changes are applied to all applicable conversions automatically\n [None,None]\n ],\n 'normal' : [ ## Dictionary is keyed on substitution type\n ['s','d'], ## Special Line Indicating type columns\n ('sdot','ddot'),\n ('sgemm','dgemm'),\n ('sgemm_para','dgemm_para'),\n ('sgemv','dgemv'),\n ('sger','dger'),\n ('saxpy','daxpy'),\n ('smut','dmut'),\n ('shandler','dhandler'),\n ('float','double'),\n ],\n};\n","sub_path":"TDP1/src_blas/subs.py","file_name":"subs.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287522974","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import Http404\nfrom PIL import Image, ImageFont, ImageDraw\nimport random\nimport sys\n\n# Create your views here.\n\n\ndef rmdRGB():\n c1 = random.randrange(0, 255)\n c2 = random.randrange(0, 255)\n c3 = random.randrange(0, 255)\n return c1, c2, c3\n\n\ndef verify_code(request):\n bgcolor = '#997679'\n width = 100\n height = 25\n # 创建画布\n im = Image.new('RGB', (width, height), bgcolor)\n # 创建画笔\n draw = ImageDraw.Draw(im)\n # 画点\n for i in range(0, 100):\n xy = (random.randrange(0, width), random.randrange(0, height))\n fill = (random.randrange(0, 255), 255, random.randrange(0, 255))\n draw.point(xy, fill=fill)\n\n # 添加干扰线\n for i in range(8):\n x1 = random.randrange(0, width)\n y1 = random.randrange(0, height)\n x2 = random.randrange(0, width)\n y2 = random.randrange(0, height)\n draw.line((x1, y1, x2, y2), fill=rmdRGB())\n # 添加圆\n\n # 写字\n str1 = '123456789abcdefghijkmnpgrstuvwxyzABCDEFJHJKLMNPQRSTUVWXYZ'\n rand_str = ''\n for i in range(0, 4):\n rand_str += str1[random.randrange(0, len(str1))]\n\n # 字体\n # font = ImageFont.truetype('/usr/share/fonts/truetype/fonts-japanese-gothic',23)\n # 判断是什么操作系统(操作系统兼容)\n if sys.platform == 'linux':\n font = ImageFont.truetype(\n '/usr/share/fonts/truetype/fonts-japanese-gothic', 23)\n elif sys.platform == 'darwin': # Mac OS X\n font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 23)\n elif sys.platform == 'win32':\n font = ImageFont.truetype(r'C:\\Windows\\Fonts\\arial.ttf', 23)\n else:\n raise Http404(\"暂不支持此操作系统: \" + sys.platform)\n\n # 构造字体颜色\n fontcolors = ['yellow', 'blue', 'green', 'red', 'orange', 'pink']\n\n draw.text((5, 2), rand_str[0], fill=random.sample(fontcolors, 1)[0], font=font)\n draw.text((25, 2), rand_str[1], fill=random.sample(fontcolors, 1)[0], font=font)\n draw.text((45, 2), rand_str[2], fill=random.sample(fontcolors, 1)[0], font=font)\n draw.text((70, 2), rand_str[3], fill=random.sample(fontcolors, 1)[0], font=font)\n\n # 结束\n del draw\n # 存入session\n request.session['verifycode'] = rand_str\n print('verifycode', request.session['verifycode'])\n # 内存文件操作\n import io\n # 获得一个内存缓存区\n buf = io.BytesIO()\n # 将图片保存在缓存区,格式为png\n im.save(buf, 'png')\n # 将缓存区的内容返回给前端 .getvalue 是把缓存区的所有数据读取\n return HttpResponse(buf.getvalue(), 'image/png')\n","sub_path":"verify/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"601946962","text":"#-*-coding:utf-8 -*-\n# from framework.testApiWay import *\nfrom framework.readExcel import ReadExcel\nimport unittest\nfrom framework import readConfigFile\nfrom framework.logger import Logger\n\nfrom framework.testApiUpdate import testApi\nfrom common.login import test_Login_token\nconfig = readConfigFile.ReadConfig()\n# token=config.get_http(\"token\")\n# login = test_login()\n# token = login.test_Login_token()\nmylog = Logger(logger=\"test_AddLuckys\").getlog()\n\n\n\n\nclass test_AddLuckys(unittest.TestCase):\n '''接口名称:发布幸运红包'''\n\n def setUp(self):\n print(\"测试开始\")\n pass\n\n\n def test_AddLucky(self):\n \"\"\"\n 幸运红包\n :return:\n\n \"\"\"\n token = test_Login_token()\n print(token)\n excel = ReadExcel(\"幸运红包\")\n\n\n data = excel.getData\n state_code = excel.getStatusCode\n\n\n\n\n url = excel.getUrl\n print(url)\n method = excel.getMethod\n\n row = excel.getRows\n buer=excel.getEncryption\n status=excel.getStatus\n t = testApi()\n\n\n for i in range(0, row - 1):\n if status[i]=='执行':\n dict_data = eval(data[i])\n buer_i = int(buer[i])\n result = t.http_request(url=url[i], method=method[i], token=token, encryption=buer_i, **dict_data)\n print(result)\n self.assertEqual(result['message'], state_code[i])\n\n # print(type(result))\n\n if result['message'] == state_code[i]:\n RESULT = 'PASS'\n else:\n RESULT = 'FAIL'\n\n excel.result_write(str(RESULT))\n else:\n print('你规定不执行')\n\n\n\n mylog.info(\"测试完成\")\n\nif __name__=='__main__':\n unittest.main(verbosity=2)","sub_path":"testCase/test_add_lucky_D.py","file_name":"test_add_lucky_D.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542129895","text":"from math import * \nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\nfrom Samecolor import *\nfrom Color import *\nfrom hgm import *\nfrom featurename import *\n\nclass ClusterModel():\n def __init__(self):\n self.count = 0\n self.data = []\n self.timeent = []\n self.header = None\n self.gmm = False\n self.prior = False\n self.lasty = [0]\n self.perm = {0:0}\n self.changed = False\n self.version = -1\n self.type = 'ClusterModel'\n self.featurename1 = 'ClusterIndex'\n self.featurename2 = 'ClusterAnomaly'\n self.index_attribute = False\n self.time_attribute = False\n self.entity_attribute = False\n self.maxsplit = 1\n\n def dictaddindex(self, vec, dic):\n res = {}\n if self.time_attribute:\n res[self.time_attribute] = vec[self.time_attribute]\n else:\n res[self.index_attribute] = vec[self.index_attribute]\n if self.entity_attribute:\n res[self.entity_attribute] = vec[self.entity_attribute]\n res.update(dic)\n return res\n\n def indexvalues(self, vec):\n return tuple([vec[a] for a in self.indexattrs()])\n\n def indexattrs(self):\n return ([self.index_attribute if not self.time_attribute else self.time_attribute] +\n ([self.entity_attribute] if self.entity_attribute else []))\n\n def reset_data(self):\n self.count = 0\n self.data = []\n self.timeent = []\n self.header = None\n\n def handle_data(self, vecdict):\n if self.header is None:\n self.header = [key for key in vecdict if key not in self.indexattrs()]\n form = { col : ContForm(0,0) for col in self.header}\n self.gmm = MixtureModel(GaussianModel(self.header, form), 1)\n self.prior = MixturePrior(self.gmm, 1.0, form, pd.DataFrame(columns=self.header))\n self.gmm.estimate_init(self.prior)\n vec = pd.DataFrame([vecdict]).iloc[0]\n self.data.append(vec)\n self.timeent.append(self.indexvalues(vecdict))\n self.gmm.estimate_incr(vec, 1.0)\n self.count += 1\n # at regular intervals, call update_model\n if self.count % 200 == 50:\n self.maxsplit = 1\n self.update_model()\n return self.dictaddindex(vecdict,\n {self.featurename1: self.perm[self.maxindex(vec)],\n self.featurename2: self.anomaly(vec)})\n\n def handle_batch_data(self, dt):\n if len(dt) > 0:\n newdata = pd.DataFrame(dt)\n self.data += [newdata.iloc[i] for i in range(len(newdata))]\n self.timeent += [self.indexvalues(newdata.iloc[i]) for i in range(len(newdata))]\n self.count += len(newdata)\n if self.header is None:\n self.header = [key for key in dt[0] if key not in self.indexattrs()]\n form = { col : ContForm(0,0) for col in self.header}\n self.gmm = MixtureModel(GaussianModel(self.header, form), 1)\n self.prior = MixturePrior(self.gmm, 1.0, form, pd.DataFrame(self.data, columns=self.header))\n self.gmm.estimate_init(self.prior)\n self.maxsplit = 6\n self.update_model()\n return [self.dictaddindex(newdata.iloc[i],\n {self.featurename1: self.perm[self.maxindex(newdata.iloc[i])],\n self.featurename2: self.anomaly(newdata.iloc[i])}) for i in range(len(newdata))]\n else:\n return None\n\n def model_type(self):\n return self.type\n\n def model_version(self):\n return self.version\n\n def extract_model(self):\n if self.gmm is not False:\n mod = [{ 'prob':p, 'mean':m.mean, 'var':m.var} for m,p in zip(self.gmm.models,self.gmm.probs)]\n else:\n mod = []\n return { 'type': self.type,\n 'version': self.version,\n 'mixture': mod }\n\n def features_changed(self):\n return self.changed\n\n def maxindex(self, sample):\n if len(self.gmm.models) == 1:\n return 0\n else:\n v = [m.logprobability(sample) + log(p) for m,p in zip(self.gmm.models,self.gmm.probs)]\n return v.index(max(v))\n\n def anomaly(self, sample):\n #if self.gmm.count < 2*len(sample):\n if self.version < 0: # initialized\n return 0.0\n else:\n ano = self.gmm.anomaly(sample)\n return min(1.0, max(0.0, (ano - 14.0)/36.0))\n\n def update_features(self):\n self.changed = False\n y = [self.maxindex(v) for v in self.data]\n z = [self.anomaly(v) for v in self.data]\n ia = self.indexattrs()\n return [self.dictaddindex(dict(zip(ia, te)),\n {self.featurename1: self.perm[yy],\n self.featurename2: zz}) for (te,yy,zz) in zip(self.timeent, y, z)] \n \n def default_params(self):\n return { 'index_attribute': False,\n 'time_attribute': False,\n 'entity_attribute': False}\n\n def set_params(self, dic):\n #if 'num_components' in dic:\n # self.numcomp = dic['num_components']\n if 'time_attribute' in dic:\n self.time_attribute = dic['time_attribute']\n if 'index_attribute' in dic:\n self.index_attribute = dic['index_attribute']\n if 'entity_attribute' in dic:\n self.entity_attribute = dic['entity_attribute']\n\n #----------------------------\n\n def update_model(self):\n def smaxind(ss, i):\n v = [ss[j][i] for j in range(len(ss))]\n return v.index(max(v))\n # check if split, if so run em\n df = pd.DataFrame(self.data, columns= self.header)\n if not self.gmm.initialized:\n ss = self.gmm.init_ss(df, False)\n mod.initialized = True\n else:\n ss = self.gmm.get_ss(df, False)\n # ok rebuild the prior\n self.prior = MixturePrior(self.gmm, 1.0, self.gmm.form, df)\n #print(\"Old: \", self.gmm.models[0].mean, self.gmm.models[0].var)\n ss = self.gmm.estimate_ss(df, False, self.prior, ss, 20, 0.001)\n #print(\"New: \", self.gmm.models[0].mean, self.gmm.models[0].var)\n loop = 0\n while loop < self.maxsplit:\n sigs = []\n if self.time_attribute is not False:\n scales = [feature_scale(n) for n in self.header]\n maxtimescale = max(scales) if scales else 15.0\n tmmd = 4*maxtimescale\n print(\"Gamma timescale:\", tmmd)\n else:\n tmmd = nan\n for i in range(len(ss)):\n sigs.append(gammatest_ts(self.gmm.models[i], ss[i], df, self.timeent, 4000, tmmd))\n print(\"Gamma sigs: \", sigs)\n mx = min(sigs)\n if mx < 0.001:\n ss = self.gmm.split(sigs.index(mx), ss)\n if len(df) > 1600*len(ss):\n ss = self.gmm.estimate_ss_sample(df, False, self.prior, ss, 800*len(ss), 60, 0.0001)\n else:\n ss = self.gmm.estimate_ss(df, False, self.prior, ss, 80, 0.0001)\n y = [smaxind(ss,i) for i in range(len(self.data))]\n self.perm = samecolor(self.lasty, y, self.perm)\n self.lasty = y\n loop += 1\n else:\n loop = self.maxsplit\n if len(df) > 1600*len(ss):\n ss = self.gmm.estimate_ss(df, False, self.prior, ss, 40, 0.0001)\n self.version += 1\n self.changed = True\n \n\ndef gammatest_ts(comp, weights, data, timeent, num, tsmindist):\n # set up vector for quicker search\n # (select first sample)\n # a large number of times\n # select random sample\n # calculate normalized distance from last sample\n # sort distances\n # express expected gamma parameters\n # find the distance at which deviation from expected distr is largest\n # compute its significane level\n data = data[comp.feet]\n dim = len(comp.feet)\n acc = np.cumsum(weights)\n dists = [False]*num\n ps = [False]*num\n oldind = selectind(acc)\n ind = oldind\n wsum = 0\n anum = 0\n if acc[-1] < 10.0 or len(data) < 2*sqrt(num) or (not isnan(tsmindist) and (timeent[-1][0] - timeent[0][0]) < tsmindist):\n return 1.0\n for i in range(num):\n while ind == oldind:\n ind = selectind(acc)\n if isnan(tsmindist) or (len(timeent[ind]) >= 2 and timeent[ind][1] != timeent[oldind][1]) or abs(timeent[ind][0] - timeent[oldind][0]) >= tsmindist:\n dist = sqvec(np.matmul(comp.ilower, np.subtract(data.iloc[ind], data.iloc[oldind])))\n w = weights[oldind] # Because weights[ind] is already accounted for in selection\n dists[i] = (dist, w)\n wsum += w\n anum += 1\n else:\n dists[i] = (inf, 0.0)\n oldind = ind\n dists.sort(key = lambda pr:pr[0])\n mnval = 0\n mnind = 0\n w = 0\n for i in range(anum):\n (d, w0) = dists[i]\n w += w0\n p = gammainc(dim/2, d/4)\n ps[i] = p\n # print((wsum, w, p))\n val = log(wsum*p/w)*w + log(wsum*(1-p)/(wsum-w))*(wsum-w) if p > 0 and p < 1 and w > 0 and w < wsum else 0\n dists[i] = (d, w) \n if val<mnval and p<0.95 and p>0.05 and p*wsum > w:\n mnval = val\n mnind = i\n (d, w) = dists[mnind]\n p = ps[mnind] #gammainc(dim/2, d/4)\n if mnval == 0:\n sig = 1.0\n elif w > wsum*p:\n n = ceil(w)\n nn = ceil(wsum)\n sig = binom.cdf((nn-n), nn, (1-p))\n else:\n n = floor(w)\n nn = ceil(wsum)\n sig = binom.cdf(n, nn, p)\n\n #plt.figure(2)\n #plt.axes().clear()\n #plt.plot([dists[i][0] for i in range(anum)],[dists[i][1] for i in range(anum)])\n #plt.plot([dists[i][0] for i in range(anum)],[ps[i]*wsum for i in range(anum)])\n \n return sig\n\n\n","sub_path":"bidaf/cluster_model.py","file_name":"cluster_model.py","file_ext":"py","file_size_in_byte":10026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274789833","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 6 10:41:53 2018\n\n@author: stevechen\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport math\n\n# Read file to get wanted variables from the Airbnb data set\ndef Get_Airbnb_Data(filename):\n data=pd.read_csv(filename,sep=',')\n newdata_df=pd.DataFrame({'price':data['price'],'property_type':data['property_type'],\n 'room_type':data['room_type'],'accommodates':data['accommodates'],\n 'bathrooms':data['bathrooms'],'bedrooms':data['bedrooms'],\n 'beds':data['beds'],'bed_type':data['bed_type'],\n 'guests_included':data['guests_included'],\n 'host_profile_pic':data['host_has_profile_pic'],'identity_verified':data['host_identity_verified'],\n 'zipcode':data['zipcode'],'latitude':data['latitude'],'longitude':data['longitude']})\n\n return (newdata_df)\n \n# Calculate the score of cleaness\ndef Score_Cleanliness(data,positive_var_list,integer_var_list,bool_var_list=None):\n \n # Calculate the number of null variables and calculate the percentage of them\n total_num=data.shape[0]*data.shape[1]\n na_num = sum(data.isnull().sum())\n na_percen = na_num/total_num\n \n # Check missing values for each column\n na_num_df=pd.DataFrame({'total':[na_num]})\n for i in list(data.columns.values):\n temp_num=data[i].isnull().sum()\n temp_df=pd.DataFrame({i:[temp_num]})\n na_num_df=pd.concat([na_num_df,temp_df],axis=1) \n\n\n incor_num=0\n # Find all non positive values\n for i in positive_var_list:\n # Let us omit the na and find the incorrect value\n temp=data.loc[~(np.isnan(data[i]))] \n # Find all negative number\n incor_num=incor_num+sum(temp[i].apply(lambda x: x<0))\n \n # Find all non integer value\n for i in integer_var_list:\n # Let us omit the na and negative number,and find the incorrect value\n temp=data.loc[~(np.isnan(data[i]))]\n temp=temp.loc[~(temp[i]<0)] \n # Find all non integer number\n incor_num=incor_num+sum(temp[i].apply(lambda x: math.floor(x) != x))\n \n \n # Find all incorrect value for a bool variable\n if bool_var_list!=None:\n for i in bool_var_list:\n temp=data.loc[~(pd.isnull(data['bedrooms']))]\n incor_num=incor_num+sum(temp[i].apply(lambda x: x != 't' and x != 'f' and x!='true' and x!='false' and x!='1' and x!='0'))\n \n # Calcualte the percentage of incorrect data\n inco_percen = incor_num/total_num\n \n #Calcuate final score\n score_final=100-100*(na_percen+inco_percen)\n \n #print(\"\\nThe total number of NA value in our original data set is: \",na_num, \", and the percentage of it is: \",na_percen)\n #print(\"\\nThe total number of incorrect value in our original data set is: \",incor_num, \", and the percentage of it is: \",inco_percen)\n\n \n return(na_num_df,incor_num,score_final)\n\n# Transform Categorical variables into dummies: \ndef Category_to_Dummy(data,category_var_list):\n for i in category_var_list:\n # Create dummies variables and concatenate them\n dummies=pd.get_dummies(data[i])\n data=pd.concat([data,dummies],axis=1)\n \n # Drop the categorical variable\n data=data.drop([i],axis=1)\n \n return (data)\n\n \n# Glance at the data \ndef Glancing_Data(data):\n pd.set_option('display.max_columns', None)\n print(data.info())\n print(data.describe())\n \n\n# Clean the data\ndef Data_Cleaning(data,positive_var_list,integer_var_list):\n data=data.dropna() \n \n # Drop variables is not positive\n for i in positive_var_list:\n data=data.loc[~(data[i]<0)] \n \n # Drop variables is not integer\n for i in integer_var_list:\n data=data.loc[~(data[i].apply(lambda x: math.floor(x)!= x))]\n \n return(data)\n \n \n# Change upper case into lower case \ndef LowerCase(data,var):\n for i in var:\n data[i]=data[i].str.lower()\n return (data)\n\n\n# Generate new features and check Airbnb Cleanliness\ndef Airbnb_Cleanliness():\n # Read a csv file and store data into a dataframe\n filename=\"Airbnb_listings.csv\"\n airbnb_df=Get_Airbnb_Data(filename)\n \n # Define lists to store columns' names based on their types\n positive_var_list = {'price','bathrooms','bedrooms','beds','guests_included','zipcode','accommodates','latitude'}\n integer_var_list = {'bedrooms','beds','guests_included','zipcode','accommodates'}\n \n bool_var_list = {'host_profile_pic','identity_verified'}\n \n na_num_df,incor_num,score_final=Score_Cleanliness(airbnb_df,positive_var_list,integer_var_list,bool_var_list)\n na_num_df=na_num_df.T.reset_index()\n with open('Missing&Incorrect_Airbnb.txt','w') as f:\n f.write('The missing values for each variable is: \\n')\n na_num_df.to_csv(f, header=True, index=False, sep='\\t', mode='a')\n f.write('\\nThe total number of incorrect values is: {}.\\nThe final score is: {:4.3f}.'\n .format(incor_num,score_final))\n \n category_var_list = {'property_type','room_type','bed_type'}\n airbnb_df=Category_to_Dummy(airbnb_df,category_var_list)\n print(airbnb_df.shape[0])\n return (airbnb_df)\n \n \n#Check Hotel prices data Cleanliness \ndef HotelPrice_Cleanliness():\n # Read a csv file and store data into a dataframe\n filename=\"Hotel_prices.csv\"\n data=pd.read_csv(filename,sep=',')\n # Select variables which we need\n hotel_df=pd.DataFrame({'price':data['price'],'hotelName':data['hotelName'],'zipcode':data['postalCode']})\n\n\n # Define lists to store columns' names based on their types\n positive_var_list = {'price'}\n integer_var_list = {}\n \n na_num_df,incor_num,score_final=Score_Cleanliness(hotel_df,positive_var_list,integer_var_list)\n na_num_df=na_num_df.T.reset_index()\n with open('Missing&Incorrect_HotelPrice.txt','w') as f:\n f.write('The missing values for each variable is: \\n')\n na_num_df.to_csv(f, header=True, index=False, sep='\\t', mode='a')\n f.write('\\nThe total number of incorrect values is: {}.\\nThe final score is: {:4.3f}.'\n .format(incor_num,score_final))\n \n \n# Check Yelp Data Cleanliness\ndef YelpData_Cleanliness():\n # Read a csv file and store data into a dataframe\n filename=\"YelpData.csv\"\n data=pd.read_csv(filename,sep=',')\n # Select variables which we need\n hotel_df=pd.DataFrame({'zipcode':data['zipcode'],'rating':data['rating'],'review_count':data['review_count']})\n\n\n # Define lists to store columns' names based on their types\n positive_var_list = {'rating','review_count'}\n integer_var_list = {'review_count','zipcode'}\n \n na_num_df,incor_num,score_final=Score_Cleanliness(hotel_df,positive_var_list,integer_var_list)\n na_num_df=na_num_df.T.reset_index()\n with open('Missing&Incorrect_YelpData.txt','w') as f:\n f.write('The missing values for each variable is: \\n')\n na_num_df.to_csv(f, header=True, index=False, sep='\\t', mode='a')\n f.write('\\nThe total number of incorrect values is: {}.\\nThe final score is: {:4.3f}.'\n .format(incor_num,score_final))\n \n\nif __name__ == \"__main__\":\n # Generate new features and check Airbnb Cleanliness\n airbnb_df=Airbnb_Cleanliness()\n \n #Check Hotel prices data Cleanliness\n HotelPrice_Cleanliness()\n \n # Check Yelp Data Cleanliness\n YelpData_Cleanliness()\n \n\"\"\" \nWe will use below variables for airbnb\n price\n property_type\n room_type\n accommodates\n bathrooms\n bedrooms\n beds\n bed_type\n square_feet \n guests_included\n host_profile_pic\n identity_verified\n zipcode\n latitude\n longitude\n\n\"\"\" \n \n \n ","sub_path":"ANLY501_Project_Part1/DataCleaning-Part1.py","file_name":"DataCleaning-Part1.py","file_ext":"py","file_size_in_byte":7878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"244976167","text":"from time import sleep\nfrom enum import Enum\n\nfrom tron.map import Map, Tile\nfrom tron.player import ACPlayer\nfrom orderedset import OrderedSet\n\nimport torch\nimport random\nimport numpy as np\nimport queue\nfrom config import *\nfrom Net.ACNet import MapNet\n\n\n\nmaptype=type(MapNet())\nclass SetQueue(queue.Queue):\n def _init(self, maxsize):\n self.queue = OrderedSet()\n\n def _put(self, item):\n self.queue.add(item)\n\n def _get(self):\n head = self.queue.__getitem__(0)\n self.queue.remove(head)\n return head\n\n\nclass Winner(Enum):\n PLAYER_ONE = 1\n PLAYER_TWO = 2\n\n\nclass PositionPlayer:\n def __init__(self, id, player, position):\n self.id = id\n self.player = player\n self.position = position\n self.alive = True\n\n def body(self):\n if self.id == 1:\n return Tile.PLAYER_ONE_BODY\n elif self.id == 2:\n return Tile.PLAYER_TWO_BODY\n def slide(self):\n if self.id == 1:\n return Tile.PLAYER_ONE_slide\n elif self.id == 2:\n return Tile.PLAYER_TWO_slide\n\n def head(self):\n if self.id == 1:\n return Tile.PLAYER_ONE_HEAD\n elif self.id == 2:\n return Tile.PLAYER_TWO_HEAD\n\n\nclass HistoryElement:\n def __init__(self, mmap, player_one_direction, player_two_direction):\n self.map = mmap\n self.player_one_direction = player_one_direction\n self.player_two_direction = player_two_direction\n\n\n\n\nclass Game:\n def __init__(self, width, height, pps,mode=None,slide_pram=None):\n\n self.width = width\n self.height = height\n mmap = Map(width, height, Tile.EMPTY, Tile.WALL)\n self.history = [HistoryElement(mmap, None, None)]\n self.pps = pps\n self.winner = None\n # self.loser_len=0\n # self.winner_len = 0\n self.next_p1 = []\n self.next_p2 = []\n self.weight=[random.randint(40,101),random.randint(40,101)]\n # self.reward = 0\n self.done = False\n self.mode=mode\n self.degree=random.randint(-30,30)\n self.slide= slide if slide_pram is None else slide_pram\n\n for pp in self.pps:\n self.history[-1].map[pp.position[0], pp.position[1]] = pp.head()\n\n def map(self):\n return self.history[-1].map.clone()\n\n def get_rate(self,player_num=None):\n\n # return ((self.degree-30)/100) ** 2\n if player_num is None:\n return -((self.degree-30)*0.6)/100\n else:\n return (-((self.degree - 30) * 0.6) / 100)-((70-self.get_weight(player_num))/100)\n\n\n def get_degree(self):\n\n\n return float(self.degree)\n\n def get_degree_silde(self):\n\n return float((-self.slide*100)*(10/6)+30)\n\n def change_degree(self):\n\n if random.random()>0.5:\n temp=self.degree+random.randint(0,3)\n self.degree=min(30,temp)\n\n else:\n temp=self.degree-random.randint(1,5)\n self.degree=max(-30,temp)\n\n def prob_map(self):\n\n temp = np.zeros((MAP_WIDTH + 2, MAP_HEIGHT + 2))\n\n for i in range(MAP_HEIGHT + 2):\n for j in range(MAP_WIDTH + 2):\n temp[i][j] = self.get_degree_silde()\n # print(temp)\n return temp\n def get_weight(self,player_num):\n\n return self.weight[player_num]\n\n def get_multy(self,player_num):\n\n return [self.get_degree(),self.get_weight(player_num)]\n def degree_map(self):\n\n temp = np.zeros((MAP_WIDTH + 2, MAP_HEIGHT + 2))\n\n for i in range(MAP_HEIGHT + 2):\n for j in range(MAP_WIDTH + 2):\n temp[i][j] = self.get_degree()\n return temp\n\n def next_frame(self, action_p1, action_p2, window=None):\n\n map_clone = self.map()\n\n action = [action_p1, action_p2]\n\n for pp in self.pps:\n map_clone[pp.position[0], pp.position[1]] = pp.body()\n\n for id, pp in enumerate(self.pps):\n\n if type(pp.player) == type(ACPlayer()):\n (pp.position, pp.player.direction) = pp.player.next_position_and_direction(pp.position, action[id])\n\n if self.mode == \"ice\" or self.mode ==\"temper\":\n if pp.position[0] >= 0 and pp.position[1] >= 0 and \\\n pp.position[0] < self.width and pp.position[1] < self.height and map_clone[pp.position[0], pp.position[1]] is Tile.EMPTY:\n\n rate = self.slide if self.mode ==\"ice\" else self.get_rate(id)\n\n if random.random() <= rate:\n\n if(id==0):\n self.history[-1].player_one_direction = self.pps[0].player.direction\n else:\n self.history[-1].player_two_direction = self.pps[1].player.direction\n\n # print(\"미끌\")\n map_clone[pp.position[0], pp.position[1]] = pp.slide()\n (pp.position, pp.player.direction) = pp.player.next_position_and_direction(pp.position, action[id])\n\n else:\n\n (pp.position, pp.player.direction) = pp.player.next_position_and_direction(pp.position, id + 1,self.map())\n\n if self.mode==\"ice\" or self.mode ==\"temper\":\n if pp.position[0] >= 0 and pp.position[1] >= 0 and \\\n pp.position[0] < self.width and pp.position[1] < self.height and map_clone[pp.position[0], pp.position[1]] is Tile.EMPTY:\n rate = self.slide if self.mode == \"ice\" else self.get_rate(id)\n\n if random.random() <= rate:\n\n if (id == 0):\n self.history[-1].player_one_direction = self.pps[0].player.direction\n else:\n self.history[-1].player_two_direction = self.pps[1].player.direction\n\n # print(\"미끌\")\n map_clone[pp.position[0], pp.position[1]] = pp.slide()\n (pp.position, pp.player.direction) = pp.player.next_position_and_direction(pp.position,id + 1,self.map(),pp.player.direction)\n\n self.history[-1].player_one_direction = self.pps[0].player.direction\n self.history[-1].player_two_direction = self.pps[1].player.direction\n\n # self.change_degree()\n\n for (id, pp) in enumerate(self.pps):\n if pp.position[0] < 0 or pp.position[1] < 0 or \\\n pp.position[0] >= self.width or pp.position[1] >= self.height:\n pp.alive, done = False, True\n map_clone[pp.position[0], pp.position[1]] = pp.head()\n elif map_clone[pp.position[0], pp.position[1]] is not Tile.EMPTY:\n pp.alive, done = False, True\n map_clone[pp.position[0], pp.position[1]] = pp.head()\n else:\n map_clone[pp.position[0], pp.position[1]] = pp.head()\n \"\"\"\n if not done and independent condition \n get player's longest path\n \n # if not done and self.check_separated(map_clone, self.pps[0]):\n # winner = self.get_longest_path(map_clone, self.pps[0], self.pps[1])\n # if winner == 1:\n # self.pps[1].alive = False\n # elif winner == 2:\n # self.pps[0].alive = False\n # else:\n # self.pps[0].alive = False\n # self.pps[1].alive = False\n \"\"\"\n\n self.history.append(HistoryElement(map_clone, None, None))\n self.next_p1 = self.history[-1].map.state_for_player(1)\n self.next_p2 = self.history[-1].map.state_for_player(2)\n\n if window:\n import pygame\n while True:\n event = pygame.event.poll()\n\n if event.type == pygame.NOEVENT:\n break\n\n for pp in self.pps:\n try:\n pp.player.manage_event(event)\n except:\n if id == 0:\n self.winner = 2\n elif id == 1:\n self.winner = 1\n return False\n\n return True\n\n def step(self, action_p1, action_p2):\n\n alive_count = 0\n alive = None\n\n\n if not self.next_frame(action_p1, action_p2):\n self.done = True\n\n return self.next_p1, self.next_p2, self.done\n for pp in self.pps:\n if pp.alive:\n alive_count += 1\n alive = pp.id\n\n if alive_count <= 1:\n if alive_count == 1:\n if self.pps[0].position[0] != self.pps[1].position[0] or \\\n self.pps[0].position[1] != self.pps[1].position[1]:\n self.winner = alive\n\n self.done = True\n\n return self.next_p1, self.next_p2, self.done\n\n def main_loop(self,model, pop=None,window=None,model2=None):\n\n if window:\n window.render_map(self.map())\n\n if (not model2):\n model2=model\n\n while True:\n alive_count = 0\n alive = None\n\n if window:\n sleep(0.3)\n\n map=self.map()\n with torch.no_grad():\n if type(model) ==maptype:\n action1 = model.act(torch.cat([torch.tensor(pop(map.state_for_player(1))),torch.tensor(self.prob_map()).unsqueeze(0)],0).unsqueeze(0).float())\n else:\n action1 = model.act(torch.tensor(pop(map.state_for_player(1))).unsqueeze(0).float(),torch.tensor([self.get_multy(0)]).to(device))\n\n if type(model2) == maptype:\n action1 = model2.act(torch.cat([torch.tensor(pop(map.state_for_player(2))), torch.tensor(self.prob_map()).unsqueeze(0)],0).unsqueeze(0).float())\n else:\n action2 = model2.act(torch.tensor(pop(map.state_for_player(2))).unsqueeze(0).float(),torch.tensor([self.get_rate()]).to(device))\n\n # action2 = model2.act(torch.tensor(pop(map.state_for_player(2))).unsqueeze(0).float(),torch.tensor([self.slide]).to(device))\n\n # action1 = model.act(torch.tensor(np.expand_dims(np.concatenate((pop(map.state_for_player(1)),np.expand_dims(np.array(self.prob_map()),axis=0)),axis=0), axis=0)).float())\n # action2 = model2.act(torch.tensor(np.expand_dims(np.concatenate((pop(map.state_for_player(2)), np.expand_dims(np.array(self.prob_map()),axis=0)), axis=0),axis=0)).float())\n\n\n if not self.next_frame(action1,action2,window):\n break\n\n for pp in self.pps:\n if pp.alive:\n alive_count += 1\n alive = pp.id\n\n if alive_count <= 1:\n if alive_count == 1:\n if self.pps[0].position[0] != self.pps[1].position[0] or \\\n self.pps[0].position[1] != self.pps[1].position[1]:\n self.winner = alive\n break\n\n if window:\n window.render_map(self.map())\n","sub_path":"Deep-Q-learning_TRON/tron/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":11164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"290461762","text":"#!/usr/bin/env python\n\n\"\"\" A TLS server that spits out random md5 hashes every half second. \"\"\"\n\nimport os\nimport ssl\nfrom hashlib import md5\nimport logging\n\nfrom tornado.ioloop import IOLoop, PeriodicCallback\nfrom tornado.tcpserver import TCPServer\nfrom tornado import options\n\n\nlog = logging.getLogger(__name__)\nport = 4443\nssl_options = {\n 'ssl_version': ssl.PROTOCOL_TLSv1,\n 'certfile': os.path.join(os.path.dirname(__file__), 'server.crt'),\n 'keyfile': os.path.join(os.path.dirname(__file__), 'server.key')\n}\n\n\nclass RandomServer(TCPServer):\n def handle_stream(self, stream, address):\n SpitRandomStuff(stream, address)\n\n\nclass SpitRandomStuff(object):\n def __init__(self, stream, address):\n log.info('Received connection from %s', address)\n self.address = address\n self.stream = stream\n self.stream.set_close_callback(self._on_close)\n self.writer = PeriodicCallback(self._random_stuff, 500)\n self.writer.start()\n\n def _on_close(self):\n log.info('Closed connection from %s', self.address)\n self.writer.stop()\n\n def _random_stuff(self):\n output = os.urandom(60)\n self.stream.write(md5(output).hexdigest() + \"\\n\")\n\n\nif __name__ == '__main__':\n options.parse_command_line()\n server = RandomServer(ssl_options=ssl_options)\n server.listen(port)\n log.info('Listening on port %d...', port)\n # To test from command-line:\n # $ openssl s_client -connect localhost:<port>\n IOLoop.instance().start()\n","sub_path":"SocketServer/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"17507912","text":"import pygame\nimport random\n\n\n\nclass game:\n def __init__(self,xmax,ymax):\n\n self.xmax = xmax\n self.ymax = ymax\n\n self._runing = True\n self.screen = None\n self.keyinput = None\n\n self.xobj = random.randint(0,self.xmax - 10)\n self.yobj = random.randint(0,self.ymax - 10)\n self.y = [100]\n self.x = [100]\n self.direction = 0\n self.fitness = 0\n self.speed = 30\n self.size = 30\n self.aiin = []\n self.aiout = []\n self.movesremaining = 100000\n self.tempdirection1 = None\n self.tempdirection2 = None\n self.paused = False\n\n def on_init(self):\n pygame.init()\n\n self.screen = pygame.display.set_mode((self.xmax, self.ymax))\n self._runing = True\n self.clock = pygame.time.Clock()\n\n def reset(self, draw_game):\n self._runing = True\n self.screen = None\n self.keyinput = None\n\n self.xobj = random.randint(0,self.xmax - 10)\n self.yobj = random.randint(0,self.ymax - 10)\n self.y = [100]\n self.x = [100]\n self.direction = 0\n self.fitness = 0\n self.speed = 30\n self.size = 30\n self.aiin = []\n self.aiout = []\n self.movesremaining = 100000\n self.tempdirection1 = None\n self.tempdirection2 = None\n\n if draw_game == True:\n self.on_init()\n\n def event(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_q:\n self._runing = False\n\n if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.paused == False:\n self.paused = True\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.paused == True:\n self.paused = False\n\n def get_point(self):\n self.movesremaining += 200\n self.fitness += 20000\n self.xobj = random.randint(0,self.xmax - 10)\n self.yobj = random.randint(0,self.ymax - 10)\n self.x.append(self.x[-1])\n self.y.append(self.y[-1])\n\n def render_game(self,fps):\n self.screen.fill((0,0,0))\n\n pygame.draw.rect(self.screen, (0, 25, 120), pygame.Rect(self.xobj, self.yobj, self.size, self.size))\n\n for i in range(len(self.x)):\n pygame.draw.rect(self.screen, (255,255,255), pygame.Rect(self.x[i], self.y[i], self.size, self.size))\n\n self.clock.tick(fps)\n pygame.display.flip()\n\n def play_game(self,fps):\n\n\n while self._runing == True:\n\n # gets the user input and changes the direction\n self.keyinput = pygame.key.get_pressed()\n if self.keyinput[pygame.K_w]: self.direction = 1\n elif self.keyinput[pygame.K_s]: self.direction = 0\n elif self.keyinput[pygame.K_d]: self.direction = 2\n elif self.keyinput[pygame.K_a]: self.direction =3\n\n # making other cubes move\n for i in reversed(range(len(self.x))):\n if i != 0:\n self.x[i] = self.x[int(i-1)]\n self.y[i] = self.y[int(i-1)]\n\n # moving the first cube\n if self.direction == 0: self.y[0] += self.speed\n elif self.direction == 1: self.y[0] -= self.speed\n elif self.direction == 2: self.x[0] += self.speed\n elif self.direction == 3: self.x[0] -= self.speed\n\n # pasing to the other side x\n if self.x[0] > self.xmax: self.x[0] = 1\n elif self.x[0] < 0: self.x[0] = self.xmax - 1\n\n # pasing to the other side y\n if self.y[0] > self.ymax: self.y[0] = 1\n elif self.y[0] < 0: self.y[0] = self.ymax -1\n\n if self.x[0] > self.xobj - self.size and self.x[0] < self.xobj + self.size and self.y[0] > self.yobj - self.size and self.y[0] < self.yobj + self.size:\n self.get_point()\n else:\n for i in reversed(range(len(self.x))):\n if i != 0:\n if self.x[0] == self.x[i] and self.y[0] == self.y[i]:\n #print('die')\n self._runing = False\n self.fitness -= 20000\n\n self.event()\n self.render_game(fps)\n\n pygame.quit()\n\n def ai_game(self, ai, draw_game, fps, seeds):\n\n if seeds != None:\n random.seed(seeds)\n self.xobj = random.randint(0,self.xmax - 10)\n self.yobj = random.randint(0,self.ymax - 10)\n\n while self._runing == True:\n\n while self.paused == True:\n self.render_game(fps)\n self.event()\n\n self.aiin.append(self.xobj)\n self.aiin.append(self.yobj)\n\n for i in range(len(self.x)):\n self.aiin.append(self.x[i])\n self.aiin.append(self.y[i])\n\n self.aiout = ai.evaluate(self.aiin)\n self.aiin = []\n\n self.tempdirection2 = self.tempdirection1\n self.tempdirection1 = self.direction\n\n while True:\n if self.aiout[0] == max(self.aiout): self.direction = 0 #s\n elif self.aiout[1] == max(self.aiout): self.direction = 1 #w\n elif self.aiout[2] == max(self.aiout): self.direction = 2 #d\n elif self.aiout[3] == max(self.aiout): self.direction =3 #a\n\n if (self.direction == 0 and 1 == self.tempdirection1) or (self.direction == 1 and 0 == self.tempdirection1) or (self.direction == 2 and 3 == self.tempdirection1) or (self.direction == 3 and 2 == self.tempdirection1):\n self.aiout[self.direction] -= 10000\n else:\n break\n\n if self.tempdirection1 == self.direction:\n self.movesremaining -= 150\n elif self.tempdirection2 == self.direction:\n self.movesremaining -= 150\n\n # making other cubes move\n for i in reversed(range(len(self.x))):\n if i != 0:\n self.x[i] = self.x[int(i-1)]\n self.y[i] = self.y[int(i-1)]\n\n # moving the first cube\n if self.direction == 0: self.y[0] += self.speed\n elif self.direction == 1: self.y[0] -= self.speed\n elif self.direction == 2: self.x[0] += self.speed\n elif self.direction == 3: self.x[0] -= self.speed\n\n # pasing to the other side x\n if self.x[0] > self.xmax: self.x[0] = 1\n elif self.x[0] < 0: self.x[0] = self.xmax - 1\n\n # pasing to the other side y\n if self.y[0] > self.ymax: self.y[0] = 1\n elif self.y[0] < 0: self.y[0] = self.ymax -1\n\n #not dieing\n if self.x[0] > self.xobj - self.size and self.x[0] < self.xobj + self.size and self.y[0] > self.yobj - self.size and self.y[0] < self.yobj + self.size:\n self.get_point()\n else:\n for i in reversed(range(len(self.x))):\n if i != 0:\n if self.x[0] == self.x[i] and self.y[0] == self.y[i]:\n #print('die')\n self._runing = False\n if self.movesremaining < 0:\n self._runing = False\n\n self.movesremaining -= 1\n #print(self.movesremaining)\n\n # fitness\n if self.x[0] > self.xobj:\n if self.y[0] > self.yobj:\n self.fitness -= (self.x[0] - self.xobj) + (self.y[0] - self.yobj)\n elif self.y[0] < self.yobj:\n self.fitness -= (self.x[0] - self.xobj) + (self.yobj - self.y[0])\n elif self.x[0] < self.xobj:\n if self.y[0] > self.yobj:\n self.fitness -= (self.xobj - self.x[0]) + (self.y[0] - self.yobj)\n elif self.y[0] < self.yobj:\n self.fitness -= (self.xobj - self.x[0]) + (self.yobj - self.y[0])\n\n #if ( self.x[0] - self.xobj < 100 or self.x[0] - self.xobj < -100 ) and ( self.y[0] - self.yobj < 100 or self.y[0] - self.yobj < -100 ):\n #self.fitness += 1\n\n # options to draw the game\n if draw_game == True:\n self.render_game(fps)\n self.event()\n\n pygame.quit()\n return self.fitness\n\n\n\nif __name__ == \"__main__\" :\n App = game(700,700)\n App.on_init()\n App.play_game(15)\n\n\n'''\n\n\nwhile not done:\n screen.fill((0,0,0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_q:\n done = True\n\n # gets the user input and changes the direction\n keyinput = pygame.key.get_pressed()\n if keyinput[pygame.K_w]: direction = 1\n elif keyinput[pygame.K_s]: direction = 0\n elif keyinput[pygame.K_d]: direction = 2\n elif keyinput[pygame.K_a]: direction =3\n\n # changes the direction of the verlocety\n if direction == 0: y += 5\n elif direction == 1: y -= 5\n elif direction == 2: x += 5\n elif direction == 3: x -= 5\n\n # pasing to the other side x\n if x > xmax: x = 1\n elif x < 0: x = xmax - 1\n\n # pasing to the other side y\n if y > ymax: y = 1\n elif y < 0: y = ymax -1\n\n pygame.draw.rect(screen, (0, 25, 120), pygame.Rect(xobj, yobj, 30, 30))\n pygame.draw.rect(screen, colour, pygame.Rect(x, y, 30, 30))\n\n clock.tick(60)\n pygame.display.flip()\n\n\nsnake\n\n'''\n","sub_path":"snake/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":10206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"621703324","text":"\"\"\" Simple FancyLED example for NeoPixel strip\n\"\"\"\n\nimport board\nimport neopixel\nimport adafruit_fancyled as fancy\n\n# Function names are kept the same as FastLED examples, which normally\n# upsets pylint. Disable name-checking so this passes muster.\n# pylint: disable=invalid-name\n\nNUM_LEDS = 23\n\n# A dynamic gradient palette is a compact representation of a color palette\n# that lists only the key points (specific positions and colors), which are\n# later interpolated to produce a full 'normal' color palette.\n# This one is an RGB spectrum -- red to yellow, green, blue, ... back to red.\nRAINBOW = bytes([\n 0, 255, 0, 0,\n 32, 171, 85, 0,\n 64, 171, 171, 0,\n 96, 0, 255, 0,\n 128, 0, 171, 85,\n 160, 0, 0, 255,\n 192, 85, 0, 171,\n 224, 171, 0, 85,\n 255, 255, 0, 0])\n\n# Here the gradient palette is converted to a full normal palette.\n# First we need a list to hold the resulting palette...it can be\n# filled with nonsense but the list length needs to match the desired\n# palette length (in FastLED, after which FancyLED is modeled, color\n# palettes always have 16, 32 or 256 entries...we can actually use whatever\n# length we want in CircuitPython, but for the sake of consistency, let's\n# make it a 256-element palette...\nPALETTE = [0] * 256\nfancy.loadDynamicGradientPalette(RAINBOW, PALETTE)\n\n# The dynamic gradient step is optional...some projects will just specify\n# a whole color palette directly on their own, not expand it from bytes.\n\n# Declare a NeoPixel object on pin D6 with NUM_LEDS pixels, no auto-write\nPIXELS = neopixel.NeoPixel(board.D6, NUM_LEDS, brightness=1.0,\n auto_write=False)\n\ndef FillLEDsFromPaletteColors(palette, offset):\n \"\"\" This function fills the global PIXELS NeoPixel strip from a color\n palette plus an offset to allow us to 'spin' the colors. In FancyLED\n (a la FastLED), palette indices are multiples of 16 (e.g. first palette\n entry is index 0, second is index 16, third is 32, etc) and indices\n between these values will interpolate color between the two nearest\n palette entries.\n \"\"\"\n\n for i in range(NUM_LEDS):\n # This looks up the color in the palette, scaling from\n # 'palette space' to 'pixel space':\n color = fancy.ColorFromPalette(\n palette, int(i * len(palette) * 16 / NUM_LEDS + offset),\n 255, True)\n # Gamma correction gives more sensible-looking colors\n PIXELS[i] = fancy.applyGamma_video(color)\n\n# This is an offset (0-4095) into the color palette to get it to 'spin'\nADJUST = 0\n\nwhile True:\n FillLEDsFromPaletteColors(PALETTE, ADJUST)\n PIXELS.show()\n ADJUST += 50 # Bigger number = faster spin\n if ADJUST >= 4096:\n ADJUST -= 4096\n","sub_path":"examples/neopixel_rotate.py","file_name":"neopixel_rotate.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2860973","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport numpy.random as rd\r\nimport mpl_toolkits.mplot3d.axes3d as p3\r\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\r\nimport matplotlib.animation as animation\r\n\r\n\r\n\r\n\r\n################################################################\r\n###-----------------Définition des fonctions-----------------### \r\n################################################################ \r\n\r\ndef plot_cube(cube_definition): #La fonction volée\r\n cube_definition_array = [\r\n np.array(list(item))\r\n for item in cube_definition\r\n ]\r\n\r\n points = []\r\n points += cube_definition_array\r\n vectors = [\r\n cube_definition_array[1] - cube_definition_array[0],\r\n cube_definition_array[2] - cube_definition_array[0],\r\n cube_definition_array[3] - cube_definition_array[0]\r\n ]\r\n\r\n points += [cube_definition_array[0] + vectors[0] + vectors[1]]\r\n points += [cube_definition_array[0] + vectors[0] + vectors[2]]\r\n points += [cube_definition_array[0] + vectors[1] + vectors[2]]\r\n points += [cube_definition_array[0] + vectors[0] + vectors[1] + vectors[2]]\r\n\r\n points = np.array(points)\r\n\r\n edges = [\r\n [points[0], points[3], points[5], points[1]],\r\n [points[1], points[5], points[7], points[4]],\r\n [points[4], points[2], points[6], points[7]],\r\n [points[2], points[6], points[3], points[0]],\r\n [points[0], points[2], points[4], points[1]],\r\n [points[3], points[6], points[7], points[5]]\r\n ]\r\n\r\n\r\n faces = Poly3DCollection(edges, linewidths=1, edgecolors='k')\r\n faces.set_facecolor((0,0,1,0.1))\r\n\r\n axes.add_collection3d(faces)\r\n\r\n\r\n\r\n\r\ndef norme(Vec3D):\r\n return np.sqrt(normeCarree(Vec3D))\r\n\r\ndef normeCarree(Vec3D):\r\n return Vec3D[0]**2+Vec3D[1]**2+Vec3D[2]**2\r\n\r\n#Avec la vitesse/température T et l'écart type E, la fonction renvoie UNE vitesse prise dans une gaussienne\r\ndef GenVitesse(T,E):\r\n vit_xyz=np.zeros(3)\r\n for i in range(3):\r\n vit_xyz[i]=rd.random()\r\n NormEtVit=norme(vit_xyz)/rd.normal(T,E) #constante permettant de normer vit_xyz pour ensuite lui donner une norme prise au hasard dans une gaussienne\r\n\r\n for i in range(3):\r\n signe=rd.random()\r\n if signe<0.5:\r\n vit_xyz[i]=vit_xyz[i]/NormEtVit\r\n else:\r\n vit_xyz[i]=-vit_xyz[i]/NormEtVit\r\n \r\n return np.array(vit_xyz)\r\n\r\n#La fonction renvoie la distribution des corps selon la demi-longueur envoyée\r\ndef GenPosition(nombrePlanete,rayon,methode):\r\n if methode==\"Cube\":\r\n Ecart=(2*rayon)/((nombrePlanete)**(1/3))\r\n T=[]\r\n for i in np.arange(-rayon,rayon,Ecart):\r\n for j in np.arange(-rayon+Ecart/2,rayon,Ecart):\r\n for z in np.arange(-rayon,rayon,Ecart):\r\n T.append([i,j,z])\r\n if len(T)<nombrePlanete:\r\n print(\"L'attribution est mauvaise\")\r\n return \"L'attribution est mauvaise\"\r\n return np.array(T[:nombrePlanete]) #Je ne suis pas arrivé à faire un programme renvoyant tout le temps une matrice avec le nombre exacte de planetes, du coup, j'augmente un peu les\r\n #limites du cube et je ne prend que les \"nombrePlanetes\" premières valeurs de la distribution.\r\n\r\n\r\n#La fonction attribue les positions et vitesses initiales aux corps \r\ndef AttributionInitiale(rayon,Vitesse,Ecart):\r\n particule=GenPosition(nombrePlan, rayon, \"Cube\")\r\n for i in range(nombrePlan):\r\n TPosx[0,i]=particule[i,0]\r\n TPosy[0,i]=particule[i,1]\r\n TPosz[0,i]=particule[i,2]\r\n\r\n for i in range(nombrePlan):\r\n A=GenVitesse(Vitesse,Ecart)\r\n TVitx[0,i]=A[0]\r\n TVity[0,i]=A[1]\r\n TVitz[0,i]=A[2]\r\n \r\n\r\n\r\n#Calcul de l'acceleration\r\ndef CalculAcceleration():\r\n\td=distance(TPosx[i-1,planete],TPosx[i-1,planeteAutre],TPosy[i-1,planete],TPosy[i-1,planeteAutre],TPosz[i-1,planete],TPosz[i-1,planeteAutre])\r\n\ta=((12/d**13)-(6/d**7))/1\r\n\treturn a*(TPosx[i-1,planete]-TPosx[i-1,planeteAutre])/d, a*(TPosy[i-1,planete]-TPosy[i-1,planeteAutre])/d,a*(TPosz[i-1,planete]-TPosz[i-1,planeteAutre])/d, d \r\n\r\n#Calcul de la position et de la vitesse avec la méthode d'euler semi-explicite\r\ndef CalculVitesseEtPosition():\r\n TVitx[i,planete]=TVitx[i-1,planete]+dt*ax\r\n TVity[i,planete]=TVity[i-1,planete]+dt*ay\t\r\n TVitz[i,planete]=TVitz[i-1,planete]+dt*az\r\n TPosx[i,planete]=TPosx[i-1,planete]+dt*TVitx[i,planete]\r\n TPosy[i,planete]=TPosy[i-1,planete]+dt*TVity[i,planete]\r\n TPosz[i,planete]=TPosz[i-1,planete]+dt*TVitz[i,planete] \r\n \r\n \r\n#Teste si la particule à l'étape i se trouve dans la boite ou non \r\ndef DansBoite(r):\r\n \r\n #r la demi longueur du cube\r\n if TPosx[i,planete]<-r:\r\n return \"x-\"\r\n if TPosx[i,planete]>r:\r\n return \"x+\"\r\n if TPosy[i,planete]<-r:\r\n return \"y-\"\r\n if TPosy[i,planete]>r:\r\n return \"y+\"\r\n if TPosz[i,planete]<-r:\r\n return \"z-\"\r\n if TPosz[i,planete]>r:\r\n return \"z+\"\r\n return(\"no\")\r\n\r\n#Modifie, selon le resultat de la fonction DansBoite(), la vitesse et la position de la particule à l'étape i pour simuler une collision, enregistre aussi la quantité de mouvement transmise aux parois\r\ndef modif(info):\r\n if info==\"no\":\r\n return()\r\n if info=='x-':\r\n TPosx[i,planete]=TPosx[i,planete] + 2*(-TailleBoite-TPosx[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVitx[i,planete])\r\n TVitx[i,planete]=-TVitx[i,planete]\r\n return()\r\n if info=='x+':\r\n TPosx[i,planete]=TPosx[i,planete] + 2*(TailleBoite-TPosx[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVitx[i,planete])\r\n TVitx[i,planete]=-TVitx[i,planete]\r\n return()\r\n if info=='y-':\r\n TPosy[i,planete]=TPosy[i,planete] + 2*(-TailleBoite-TPosy[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVity[i,planete])\r\n TVity[i,planete]=-TVity[i,planete]\r\n return()\r\n if info=='y+':\r\n TPosy[i,planete]=TPosy[i,planete] + 2*(TailleBoite-TPosy[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVity[i,planete])\r\n TVity[i,planete]=-TVity[i,planete]\r\n return()\r\n if info=='z-':\r\n TPosz[i,planete]=TPosz[i,planete] + 2*(-TailleBoite-TPosz[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVitz[i,planete])\r\n TVitz[i,planete]=-TVitz[i,planete]\r\n return()\r\n if info=='z+':\r\n TPosz[i,planete]=TPosz[i,planete] + 2*(TailleBoite-TPosz[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVitz[i,planete])\r\n TVitz[i,planete]=-TVitz[i,planete]\r\n \r\n\r\ndef distance(x1,x2,y1,y2,z1,z2):\r\n\treturn np.sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)\r\n\r\ndef Ecinetique(vx,vy,vz):\r\n\treturn 0.5*1*(vx**2+vy**2+vz**2)\r\n\r\ndef Epotentielle(d):\r\n\treturn 0.5*((1/d**12)-(1/d**6)) #Multiplication par 0.5 parceque je compte deux fois l'energie: pour un couple {i,j} de particule, je compte Eij et Eji, donc il faut diviser par deux\r\n\r\n\r\n\r\n#####################################################################\r\n###-----------------Initialisation des paramètres-----------------### \r\n##################################################################### \r\nrd.seed(1)\r\n\r\n#Nombre de corps\r\nnombrePlan=15\r\n\r\n#Durée de la simulation\r\ntemps=30\r\n\r\n#Intervalle de temps (Il vaut mieux garder un multiple de 10 sinon, le ttab peut avoir des problemes de dimensionnement (N+1 colonnes plutot que N))\r\ndt=0.01\r\n\r\n#Nombre de simulation(s)\r\nN=int(temps/dt)\r\n\r\n\r\n#Définition des tableaux contenant les différentes données\r\nttab=np.arange(dt,temps,dt)\r\n\r\n#Position et vitesse\r\nTPosx=np.zeros((N,nombrePlan))\r\nTPosy=np.zeros((N,nombrePlan))\r\nTPosz=np.zeros((N,nombrePlan))\r\nTVitx=np.zeros((N,nombrePlan))\r\nTVity=np.zeros((N,nombrePlan))\r\nTVitz=np.zeros((N,nombrePlan))\r\n\r\n#Energie et quantité de mouvement\r\nEpot=np.zeros(N)\r\nEcin=np.zeros(N)\r\nMoment=np.zeros(N) #Quantité de mouvement transmise aux parois, en valeur absolue puisqu'elle ne sert qu'à trouver une pression\r\n\r\n#Demi longueur du cube dans lequel on place les corps et leurs vitesses + ecart type de la gaussienne en t=0\r\nTailleInitiale=1.5\r\nVitesseInitiale=0.001\r\nEcartType=0.00\r\n\r\n#Taille de la boite dans laquelle se passe les collisions (à garder STRICTEMENT inférieur à: TailleInitiale)\r\nTailleBoite=10\r\n\r\ncube_definition = [\r\n (-TailleBoite,-TailleBoite,-TailleBoite), (TailleBoite,-TailleBoite,-TailleBoite), (-TailleBoite,TailleBoite,-TailleBoite), (-TailleBoite,-TailleBoite,TailleBoite)\r\n]\r\n\r\n#Generation des conditions initiales\r\nAttributionInitiale(TailleInitiale,VitesseInitiale,EcartType)\r\n\r\nTVitx[0,0]=5\r\nTVity[0,0]=-5\r\nTVitz[0,0]=5\r\nTPosx[0,0]=9.98\r\nTPosy[0,0]=9.98\r\nTPosz[0,0]=9.98\r\n\r\n############################################################\r\n###-----------------Programme Principale-----------------### \r\n############################################################ \r\n\r\n\r\nprint(\"Début des calculs\")\r\nfor i in range(1,N):\r\n print(i,\"/\",N)\r\n for planete in range(nombrePlan):\r\n ax=0\r\n ay=0\r\n az=0\r\n for planeteAutre in range(nombrePlan):\r\n if planeteAutre!=planete: \r\n a=CalculAcceleration()\r\n ax+=a[0]\r\n ay+=a[1]\r\n az+=a[2]\r\n Epot[i-1]=Epot[i-1]+Epotentielle(a[3])\r\n CalculVitesseEtPosition()\r\n modif(DansBoite(TailleBoite)) #A mettre en commentaire pour desactiver les collisions\r\n Ecin[i]=Ecin[i]+Ecinetique(TVitx[i,planete],TVity[i,planete],TVitz[i,planete]) \r\n \r\n \r\n###############################################\r\n###-----------------Calculs-----------------### \r\n###############################################\r\n\r\n#Calcul de la pression exercée sur les parois \r\naireBoite=6*(2*TailleBoite)**2\r\npas=100\r\nnombreDivision=int(N/pas)\r\n\r\nttab2=np.linspace(0,dt*N,nombreDivision)\r\nTMoment=np.zeros(nombreDivision)\r\nfor i in range(nombreDivision):\r\n TMoment[i]=sum(Moment[i*pas:(i*pas)+pas])\r\nTpress=TMoment/(pas*dt*aireBoite)\r\n\r\n#Calcul temperature\r\nkb=1\r\n\r\neneCinMoyenne=0\r\nfor i in range(int(N/2),N):\r\n eneCinMoyenne+=2*Ecin[i]/N\r\ntemperature=eneCinMoyenne/(1.5*kb*nombrePlan)\r\n\r\n\r\n\r\n#Pression exercée en moyenne sur les parois pendant le temps (dt*N)/2\r\npression=sum(Tpress[:int(len(Tpress)/2)])*2/len(Tpress)\r\n\r\n#Calcul de l'énergie totale \r\nEtot=Epot[1:-1]+Ecin[1:-1]\r\n\r\nprint(\"pression=\", pression,\"temperature=\",temperature ) \r\n\r\n\r\n \r\n###########################################################\r\n###-----------------Affichage Graphique-----------------### \r\n########################################################### \r\n \r\nfig = plt.figure()\r\naxes = p3.Axes3D(fig)\r\ndef animate(i):\r\n i=i*10\r\n axes.clear()\r\n axes.plot(TPosx[i,:1],TPosy[i,:1],TPosz[i,:1],\"ro\")\r\n axes.plot(TPosx[i,1:],TPosy[i,1:],TPosz[i,1:],\"bo\")\r\n plot_cube(cube_definition)\r\n axes.set_xlim3d([-TailleBoite, TailleBoite])\r\n\r\n axes.set_ylim3d([-TailleBoite, TailleBoite])\r\n\r\n axes.set_zlim3d([-TailleBoite, TailleBoite])\r\n\r\n \r\nani = animation.FuncAnimation(fig, animate, interval=10)\r\n#ani.save('./gif/animation.gif', writer='imagemagick', fps=10)\r\n\r\n \r\n\r\n\"\"\" \r\nplt.legend()\r\nplt.figure()\r\nplt.plot(ttab[:-1],Epot[1:-1],label=\"Epot\")\r\nplt.plot(ttab[:-1],Ecin[1:-1],label=\"Ecin\")\r\nplt.plot(ttab[:-1],Etot,label=\"Etot\")\r\n\r\nplt.figure()\r\nplt.plot(ttab2,Tpress,label='Pression')\r\nplt.figure()\r\nplt.plot(ttab[:-1],Moment[1:-1],label=\"Quantité de mouvement\")\r\n\r\nplt.legend()\r\n\"\"\"\r\nplt.show()","sub_path":"dyna_mole_5.8.py","file_name":"dyna_mole_5.8.py","file_ext":"py","file_size_in_byte":11578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"137194542","text":"'''\n@Author: Ru_j\n@Date: 2020-03-13 19:50:16\n@LastEditors: Ru_j\n@LastEditTime: 2020-03-13 21:43:15\n@Description:\n'''\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_boston\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import SGDRegressor, Ridge, RidgeCV\nfrom sklearn.decomposition import PCA\nimport pandas as pd\nimport os\nfrom sklearn.cluster import KMeans\n\n\ndef SGD_boston():\n boston = load_boston()\n x = boston.data\n y = boston.target\n train_x, test_x, train_y, test_y = \\\n train_test_split(x, y, test_size=.25)\n std_s = StandardScaler()\n train_x = std_s.fit_transform(train_x)\n test_x = std_s.fit_transform(test_x)\n\n sgd = SGDRegressor()\n sgd.fit(train_x, train_y)\n score = sgd.score(test_x, test_y)\n predict_y = sgd.predict(test_x)\n print(score)\n print(predict_y[:20])\n print(test_y[:20])\n # print(sgd.coef_)\n # print(sgd.intercept_)\n\n return None\n\n\ndef ridge_boston():\n boston = load_boston()\n x = boston.data\n y = boston.target\n train_x, test_x, train_y, test_y = \\\n train_test_split(x, y, test_size=.25)\n std_s = StandardScaler()\n train_x = std_s.fit_transform(train_x)\n test_x = std_s.fit_transform(test_x)\n\n # ridge = Ridge(alpha=1.5)\n ridge = RidgeCV(alphas=[1e-3, 1e-2, 1e-1, 1], cv=4)\n ridge.fit(train_x, train_y)\n score = ridge.score(test_x, test_y)\n predict_y = ridge.predict(test_x)\n print(score)\n print(predict_y[:20])\n print(test_y[:20])\n return None\n\n\ndef pca_kmeans():\n path = os.path.dirname(__file__) + \\\n '/machine_learning_data/'\n products = pd.read_csv(path + 'products.csv')\n orders = pd.read_csv(path + 'orders.csv')\n aisles = pd.read_csv(path + 'aisles.csv')\n prior = pd.read_csv(path + 'order_products_prior.csv', iterator=True)\n prior = prior.get_chunk(10000)\n table_1 = pd.merge(prior, products, on=['product_id', 'product_id'])\n table_2 = pd.merge(table_1, orders, on=['order_id', 'order_id'])\n table = pd.merge(table_2, aisles, on=['aisle_id', 'aisle_id'])\n\n data = pd.crosstab(table['user_id'], table['aisle'])\n _pca = PCA(n_components=0.95)\n data = _pca.fit_transform(data)\n\n km = KMeans()\n km.fit(data)\n predict = km.predict(data)\n print(predict[:100])\n\n return None\n\n\nif __name__ == \"__main__\":\n SGD_boston()\n ridge_boston()\n pca_kmeans()\n","sub_path":"python/day10/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"346286904","text":"#io_utilities.py\n#open es como si fuera una clase\nfilepath = './data/iris.data' #r de read\n\nwith open (filepath ,'r') as fp:\n data = fp.read()\n\ndata_lines = data.split('\\n')\ndata_final = [f.split(',')for f in data_lines]\n\nprint (data_final)\n","sub_path":"io_utilities.py","file_name":"io_utilities.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"8099633","text":"from selenium import webdriver\r\nfrom PyQt5 import QtWidgets\r\nfrom PyQt5 import QtCore\r\nfrom PyQt5.QtWidgets import QToolButton, QSizePolicy, QLabel, QLineEdit,QPushButton\r\nimport random\r\nimport keyboard\r\nimport re\r\n# options=webdriver.ChromeOptions()\r\n# options.add_argument('headless')#창을 안띄우는 headless모드\r\n# options.add_argument('window-size=1920x1080')\r\n# options.add_argument(\"disable-gpu\")#gpu가속 끔\r\n# #user-agent값을 변경하여 headless모드 감지를 방지\r\n# options.add_argument(\"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\")\r\n# options.add_argument(\"lang=ko_KR\") #headless모드에선 언어설정이 안되있으므로 한국어로 설정(감지 방지)\r\ndriver = webdriver.Chrome('C://Users//dhrms//Downloads//chromedriver_win32\\\\chromedriver.exe')#,chrome_options=options)\r\n\r\nclass start(QtWidgets.QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.layout=QtWidgets.QHBoxLayout(self)\r\n\r\n self.id_layout = QtWidgets.QVBoxLayout(self)\r\n self.pwd_layout = QtWidgets.QVBoxLayout(self) #QV=가로 QH=세로\r\n\r\n self.id=QLabel(\"ID\")\r\n self._id=QLineEdit()\r\n self.pwd=QLabel(\"password\")\r\n self._pwd=QLineEdit()\r\n\r\n self.id_layout.addWidget(self.id)\r\n self.id_layout.addWidget(self._id)\r\n\r\n self.pwd_layout.addWidget(self.pwd)\r\n self.pwd_layout.addWidget(self._pwd)\r\n self.layout.addLayout(self.id_layout)\r\n self.layout.addLayout(self.pwd_layout)\r\n\r\n self.setLayout(self.layout)\r\n\r\n self._pwd.setEchoMode(QLineEdit.Password)\r\n self._pwd.returnPressed.connect(self.login)\r\n\r\n self.show()\r\n\r\n def login(self):\r\n driver.get(\"https://www.instagram.com/accounts/login/\")\r\n driver.find_element_by_name('username').send_keys(self._id.text())\r\n driver.find_element_by_name('password').send_keys(self._pwd.text())\r\n driver.implicitly_wait(10)\r\n driver.find_elements_by_tag_name('button')[1].click()\r\n driver.implicitly_wait(100)\r\n self.newWindow = Main()\r\n self.newWindow.show()\r\n self.close()\r\n\r\n\r\nclass Main(QtWidgets.QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.layout_m = QtWidgets.QHBoxLayout(self) #전체틀\r\n self.start_layout = QtWidgets.QVBoxLayout() #버튼을 담을 틀\r\n self.setFixedSize(300, 200)\r\n \r\n ''' 수정 필요 '''\r\n \r\n self.target=QLabel(\"상대의 아이디를 입력하세요\")\r\n self._target=QLineEdit()\r\n self.like = self.createButton(\"좋아요\",self.clicklike)#버튼watch\r\n #self.comment = self.createButton(\"댓글\",self.clickcomment)#버튼graph\r\n \r\n self.like.resize(self.like.sizeHint())#sizeHint=holds the recommended size for the widget\r\n #self.comment.resize(self.comment.sizeHint())\r\n\r\n #틀에 버튼 담음\r\n #self.start_layout.addWidget(self.comment)\r\n self.start_layout.addWidget(self.target)\r\n self.start_layout.addWidget(self._target)\r\n self.layout_m.addLayout(self.start_layout)#전체틀에 버튼을 담은 틀을 담음\r\n self.layout_m.addWidget(self.like)\r\n self.setLayout(self.layout_m)\r\n \r\n self.show()\r\n \r\n self.timer = QtCore.QTimer() # 타이머 생성\r\n \r\n # 함수 연결\r\n self.timer.timeout.connect(self.clicklike) # 타임아웃 이벤트를 showWatch와 연결\r\n # 정한 시간이 지날때마다 show_time 실행\r\n self.timer.start(1000*60*60)#1시간에 한번씩\r\n\r\n\r\n def clicklike(self):\r\n # driver.find_element_by_name('username').send_keys(\"01037395297\")\r\n # driver.find_element_by_name('password').send_keys(\"dh241152!\")\r\n driver.get('https://www.instagram.com/{}'.format(self._target.text()))\r\n # driver.get('https://www.instagram.com/{}/'.format(input_target_id))\r\n #첫번째 게시글 클릭\r\n driver.find_elements_by_css_selector('.v1Nh3.kIKUG._bz0w')[0].find_element_by_tag_name('a').click()\r\n driver.implicitly_wait(10)\r\n #좋아요누르기\r\n driver.get(driver.current_url)\r\n temp1=driver.find_elements_by_class_name('eo2As ')\r\n temp1[0].find_element_by_class_name('wpO6b ').click()\r\n #사진의 정보가져와서 필요한데이터 추출\r\n img_information=driver.find_elements_by_tag_name('img')[1].get_attribute('alt')\r\n img_information=img_information.split(': ')\r\n img_information=img_information[1].split(' and ')\r\n #print(img_information)\r\n food = [\"맛있겠네\",\"맛있어 보이는구나!\",\"다음에 나도 데려가~~\", \"돼지야!\"]\r\n people=[\"오 아주 잘나왔군!\", \"정말 멋쟁이군\", \"우도환 닮았다\", \"손나은 닮았다\"]\r\n\r\n for i in img_information:\r\n if re.search('people',i):\r\n case=\"인물\"\r\n break\r\n if re.search('food',i):\r\n case=\"음식\"\r\n break\r\n else:\r\n case=\"기타\"\r\n\r\n if case==\"인물\":\r\n rand_number=random.randint(0,3)\r\n comment=people[rand_number]\r\n elif case==\"음식\":\r\n rand_number=random.randint(0,3)\r\n comment=food[rand_number]\r\n else:\r\n comment=\"^^7\"\r\n #댓글입력\r\n temp1[0].find_elements_by_class_name('wpO6b ')[1].click()\r\n driver.find_element_by_tag_name('textarea').send_keys(comment)\r\n driver.implicitly_wait(10)\r\n driver.find_element_by_class_name('X7cDz').find_element_by_tag_name('button').click()\r\n \r\n \r\n def createButton(self, text, function):\r\n button = Button(text)\r\n button.clicked.connect(function)\r\n return button\r\n\r\n\r\n\r\nclass Button(QToolButton):\r\n def __init__(self, text):\r\n super().__init__()\r\n buttonStyle = '''\r\n QToolButton:hover {border:1px solid #0078d7; background-color:#e5f1fb;}\r\n QToolButton:pressed {background-color:#a7c8e3}\r\n QToolButton {font-size:11pt; font-family:나눔고딕; border:1px solid #d6d7d8; background-color:#f0f1f1}\r\n '''\r\n self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)\r\n self.setText(text)\r\n self.setStyleSheet(buttonStyle)\r\n\r\n def sizeHint(self):\r\n size = super(Button, self).sizeHint()\r\n size.setHeight(size.height() + 30)\r\n size.setWidth(max(size.width(), size.height()))\r\n return size\r\n\r\nif __name__ == '__main__':\r\n app = QtWidgets.QApplication([])\r\n win=start()\r\n app.exec_()","sub_path":"Like&comment.py","file_name":"Like&comment.py","file_ext":"py","file_size_in_byte":6720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"252429319","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\n\nfrom src.sparse_distributed_representation import SDR\nfrom src.numeric_encoder import NumericEncoder\nfrom src.category_encoder import CategoryEncoder\nfrom src.sam_fabric import SAM\nfrom examples.sam_viz import plot_pors, plot_sam\n\n\nfrom sklearn.datasets import make_moons\n\n\ndef moon_test():\n\n # get moon raw data with 1% noise and 200 samples\n #\n data_set, labels = make_moons(n_samples=200,\n noise=0.01,\n random_state=0)\n\n # create a numeric encoder and label encoder\n #\n numeric_encoder = NumericEncoder(min_step=0.005,\n n_bits=40,\n enc_size=2048,\n seed=123)\n\n label_encoder = CategoryEncoder(n_bits=40,\n enc_size=2048,\n seed=456)\n\n # construct a training set of SDRs encoding the x and y values of the 2D moons and\n # encoding the label\n #\n training_graphs = []\n\n for idx in range(len(data_set)):\n\n # the xy_sdr represents the sparse encoding of a 2D point\n #\n xy_sdr = SDR()\n\n # here enc_key identifies an edge to an x value\n #\n xy_sdr.add_encoding(enc_key=('x',), value=data_set[idx][0], encoder=numeric_encoder)\n\n # here enc_key identifies an edge to a y value\n #\n xy_sdr.add_encoding(enc_key=('y',), value=data_set[idx][1], encoder=numeric_encoder)\n\n # the label_sdr represents the sparse encoding of the label\n #\n label_sdr = SDR()\n label_sdr.add_encoding(enc_key=('label',), value=str(labels[idx]), encoder=label_encoder)\n\n training_graphs.append({'xy': xy_sdr, 'label': label_sdr})\n\n # the xy_sdr and label_sdr will be trained in different regions of the SAM\n # but associated with each other because they occur at the same time\n # The sam_params is a default config for each region of the SAMFabric\n #\n regional_sam_params = {\n # an incoming training sdr must be at least 70% similar to a neuron to be mapped to it\n 'similarity_threshold': 0.7,\n\n # neurons that are at least 63% (0.7 * 0.9) similar to the incoming sdr are considered to be in the same community\n 'community_factor': 0.9,\n\n # the level below which a weight is considered zero and will be deleted\n 'prune_threshold': 0.01,\n\n # a set of enc_type tuples to be used in learning - settin to None implies all enc_types will be learned\n 'activation_enc_keys': None}\n\n association_sam_params = {\n # an incoming training sdr must be at least 50% similar to a neuron to be mapped to it\n 'similarity_threshold': 0.5,\n\n # neurons that are at least 45% (0.5 * 0.9) similar to the incoming sdr are considered to be in the same community\n 'community_factor': 0.9,\n\n # the level below which a weight is considered zero and will be deleted\n 'prune_threshold': 0.01,\n\n # a set of enc_type tuples to be used in learning - setting to None implies all enc_types will be learned\n 'activation_enc_keys': None}\n\n # we have the possibility of having different configurations per region\n #\n region_params = {'xy': regional_sam_params,\n 'label': regional_sam_params}\n\n sam_fabric = SAM(spatial_params=region_params, association_params=association_sam_params)\n\n pors = []\n\n for t_idx in range(len(training_graphs)):\n por = sam_fabric.train(sdrs=training_graphs[t_idx])\n pors.append(por)\n\n sam_dict = sam_fabric.to_dict(decode=True)\n\n plot_sam(sam_region=sam_dict['xy'],\n raw_data=data_set,\n xyz_types=[('x',), ('y',)],\n colour_nodes=None,\n title='Moons')\n\n xy_pors = [por['xy'] for por in pors]\n\n plot_pors(xy_pors)\n\n print('Finished')\n\n\nif __name__ == '__main__':\n\n moon_test()\n","sub_path":"examples/sam_fabric_moon.py","file_name":"sam_fabric_moon.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"624708181","text":"import os\nimport argparse\n\nimport sys\n\nsys.path.append(os.getcwd())\n\nimport torch\n\nprint(\"Current working path:\", os.getcwd())\nmodels = [\"seq2seq\", \"memnn\", \"transformer\", \"itdd\"]\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--model\", type=str, default=\"seq2seq\", help=\" or \".join(models))\nparser.add_argument(\n \"--embed_size\", type=int, default=128, help=\"default 64. word embedding size\"\n)\nparser.add_argument(\n \"--batch_size\", type=int, default=32, help=\"default 32. input batch size\"\n)\nparser.add_argument(\n \"--num_epochs\", type=int, default=40, help=\"default 40. the number of epochs\"\n)\n\nparser.add_argument(\n \"--start_epoch\", type=int, default=0, help=\"resume epoch count, default=0\"\n)\nparser.add_argument(\n \"--resume\", type=int, default=1, help=\"defalut 1. read pretrained models\"\n)\nparser.add_argument(\"--seed\", type=int, default=1111, help=\"random seed\")\nargs = parser.parse_args()\n\ntorch.manual_seed(args.seed)\n\n\n# command line parameters\nmodel = args.model\nembed_size = args.embed_size\nbatch_size = args.batch_size\nnum_epochs = args.num_epochs\nstart_epoch = args.start_epoch\nresume = args.resume\n","sub_path":"snow/utils/configer.py","file_name":"configer.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"275117395","text":"# -*- coding: utf-8 -*-\n# Django settings for aikidodze project.\nimport os\n\nDEBUG = False\nTEMPLATE_DEBUG = False\nTHUMBNAIL_DEBUG = False\n\nADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)\n\nSITE_ROOT = os.path.realpath(os.path.dirname(__file__))\nMANAGERS = ADMINS\n\nDATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\nDATABASE_NAME = \"*********\" # Or path to database file if using sqlite3.\nDATABASE_USER = '*********' # Not used with sqlite3.\nDATABASE_PASSWORD = '*********' # Not used with sqlite3.\nDATABASE_HOST = 'localhost' # Set to empty string for localhost. Not used with sqlite3.\nDATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.\n\nDEFAULT_CHARSET = \"utf-8\"\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'Asia/Novosibirsk'\n\ngettext = lambda s: s\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'ru-ru'\n\nLANGUAGES = (\n ('ru', gettext('Russian')),\n)\nCMS_LANGUAGES = (\n ('ru', gettext('Russian')),\n)\nCMS_LANGUAGE_CONF = {\n 'ru':['ru'],\n}\n\nCMS_DEFAULT_LANGUAGE = 'ru'\n\nCMS_FRONTEND_LANGUAGES = (\"ru\",)\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\nURL_ROOT= ''#/sibposad'\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = os.path.join(SITE_ROOT, 'media')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\nMEDIA_URL = URL_ROOT+'/media/'\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\nADMIN_MEDIA_PREFIX = URL_ROOT+'/media/amedia/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'fm5s3rn(#f2fkzpzawdk(8j_0j$on@a&lwyq(0ds(5w%1vl!=m'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source',\n # 'django.template.loaders.eggs.load_template_source',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'cms.middleware.media.PlaceholderMediaMiddleware',\n 'cms.middleware.page.CurrentPageMiddleware',\n 'cms.middleware.user.CurrentUserMiddleware',\n #'cms.middleware.multilingual.MultilingualURLMiddleware',\n)\n\nROOT_URLCONF = 'sibposad.urls'\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.core.context_processors.auth\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.request\",\n \"django.core.context_processors.media\",\n \"cms.context_processors.media\",\n \"main.main_processor.template\",\n)\n\nTEMPLATE_DIRS = (\n os.path.join(SITE_ROOT, 'tmpl'),\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\nCMS_TEMPLATES = (\n ('base.html', gettext('default')),\n ('index.html', gettext('index')),\n ('main.html',gettext('main')),\n ('news.html',gettext('news')),\n ('service.html',gettext('service')),\n ('contacts.html',gettext('contacts')),\n)\n\nCMS_APPLICATIONS_URLS = (\n ('news.urls', 'News'),\n)\n\n#CMS_NAVIGATION_EXTENDERS = (\n# ('cmsplugin_news.navigation.get_nodes', 'News navigation'),\n#)\n\nCMS_SEO_FIELDS = True\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.admin',\n 'django.contrib.sites',\n 'cms',\n 'cms.plugins.text',\n 'cms.plugins.picture',\n 'cms.plugins.link',\n 'cms.plugins.file',\n 'cms.plugins.video',\n 'menus',\n 'mptt',\n 'publisher',\n #'south',\n 'sorl.thumbnail',\n 'news',\n 'gallery',\n 'opinion',\n 'roster',\n)\n\nROSTER_PAGE = 9\n\n\nWYM_TOOLS = \",\\n\".join([\n \"{'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}\",\n \"{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'}\",\n \"{'name': 'Superscript', 'title': 'Superscript', 'css': 'wym_tools_superscript'}\",\n \"{'name': 'Subscript', 'title': 'Subscript', 'css': 'wym_tools_subscript'}\",\n \"{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'}\",\n \"{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'}\",\n \"{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'}\",\n \"{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'}\",\n \"{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'}\",\n \"{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'}\",\n \"{'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'}\",\n \"{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'}\",\n \"{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'}\",\n])\n\nWYM_CLASSES = \",\\n\".join([\n \"{'name': 'transparent', 'title': 'Таблица без границ', 'expr': 'table'}\",\n])\n\nWYM_STYLES = \",\\n\".join([\n \"{'name': '.transparent', 'css': 'background-color: #E1E8F1'}\",\n])\n","sub_path":"ExampleDjangoCMS/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"243597041","text":"# -*- coding: utf-8 -*-\n\nimport math\nimport random\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\n\ndef get_softmax(z, tau=1.0):\n exp_z = np.exp((z - np.max(z)) / tau)\n p = list(exp_z / exp_z.sum())\n p[-1] = 1 - sum(p[:-1])\n return p\n\nclass ReplayMemory:\n def __init__(self,capacity=1000):\n self.position = -1\n self.capacity = capacity\n self.memory = []\n\n def push(self, *args):\n if len(self.memory) < self.capacity:\n self.memory.append(args)\n self.position = (self.position + 1) % self.capacity\n else:\n self.memory[self.position] = args\n self.position = (self.position + 1) % self.capacity\n\n def sample(self,sample_size):\n return random.sample(self.memory, sample_size)\n\nclass Q_Net(torch.nn.Module):\n def __init__(self, lsize):\n super().__init__()\n self.layers = nn.ModuleList()\n self.n_layers = len(lsize) - 1\n for i in range(self.n_layers):\n self.layers.append(torch.nn.Linear(lsize[i], lsize[i+1]))\n\n def forward(self, x):\n for i in range(self.n_layers):\n x = self.layers[i](x)\n if i < self.n_layers-1:\n x = F.relu(x)\n return x\n\n def save(self, fn):\n torch.save(self.state_dict(), fn)\n\n def load(self, fn):\n self.load_state_dict(torch.load(fn))\n\nclass PlayerMLP:\n def __init__(self, casino):\n self.casino = casino\n self.nA = casino.get_action_space()\n self.nDS = casino.nDS\n self.nPS = casino.nPS\n self.nPA = casino.nPA\n self.nSnA = (self.nDS, self.nPS, self.nPA, self.nA)\n self.n_episode = 0\n self.pocket = 0\n self.make_net()\n\n #self.optimizer1 = optim.Adam(self.qf1.parameters(), lr=0.001, weight_decay=0)\n #self.optimizer2 = optim.Adam(self.qf2.parameters(), lr=0.001, weight_decay=0)\n #self.optimizer1 = optim.Adadelta(self.qf1.parameters(), lr=0.1, weight_decay=0)\n #self.optimizer2 = optim.Adadelta(self.qf2.parameters(), lr=0.1, weight_decay=0)\n #self.optimizer1 = optim.Adagrad(self.qf1.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer2 = optim.Adagrad(self.qf2.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer1 = optim.SparseAdam(self.qf1.parameters(), lr=0.001)\n #self.optimizer2 = optim.SparseAdam(self.qf2.parameters(), lr=0.001)\n self.optimizer1 = optim.Adamax(self.qf1.parameters(), lr=0.002, weight_decay=0)\n self.optimizer2 = optim.Adamax(self.qf2.parameters(), lr=0.002, weight_decay=0)\n #self.optimizer1 = optim.ASGD(self.qf1.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer2 = optim.ASGD(self.qf2.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer1 = optim.LBFGS(self.qf1.parameters(), lr=1)\n #self.optimizer2 = optim.LBFGS(self.qf2.parameters(), lr=1)\n #self.optimizer1 = optim.RMSprop(self.qf1.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer2 = optim.RMSprop(self.qf2.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer1 = optim.Rprop(self.qf1.parameters(), lr=0.01)\n #self.optimizer2 = optim.Rprop(self.qf2.parameters(), lr=0.01)\n #self.optimizer1 = optim.SGD(self.qf1.parameters(), lr=0.01, nesterov = True, momentum = 0.1)\n #self.optimizer2 = optim.SGD(self.qf2.parameters(), lr=0.01, nesterov = True, momentum = 0.1)\n\n milestone = [5000, 10000,30000,50000,70000,90000,120000,160000,200000,250000,]\n\n self.lr_scheduler1 = optim.lr_scheduler.MultiStepLR(self.optimizer1, milestone, gamma=1/np.sqrt(10))\n self.lr_scheduler2 = optim.lr_scheduler.MultiStepLR(self.optimizer2, milestone, gamma=1/np.sqrt(10))\n #self.lr_scheduler1 = optim.lr_scheduler.LambdaLR(self.optimizer1, lr_lambda = lambda epoch: 1/math.sqrt((epoch+1)/1000))\n #self.lr_scheduler2 = optim.lr_scheduler.LambdaLR(self.optimizer2, lr_lambda = lambda epoch: 1/math.sqrt((epoch+1)/1000))\n #self.lr_scheduler1 = optim.lr_scheduler.ExponentialLR(self.optimizer1, gamma = 1+1e-5)\n #self.lr_scheduler2 = optim.lr_scheduler.ExponentialLR(self.optimizer2, gamma = 1+1e-5)\n #self.lr_scheduler1 = optim.lr_scheduler.CosineAnnealingLR(self.optimizer1, T_max=1000)\n #self.lr_scheduler2 = optim.lr_scheduler.CosineAnnealingLR(self.optimizer2, T_max=1000)\n\n self.batch_size = 1\n\n self.choice = 1\n\n self.test_episode = 0\n\n def make_net(self):\n H = 64\n lsize = [self.dimS(), H, H,H, self.nA]\n self.qf1 = Q_Net(lsize)\n self.qf2 = Q_Net(lsize)\n\n def load(self, fn):\n self.qf1.load(fn)\n\n def save(self, fn):\n self.qf1.save(fn)\n\n def dimS(self):\n return 13\n\n def get_state(self):\n s = self.casino.observe()\n s = torch.tensor(s, dtype=torch.float32)\n p = self.casino.peep()\n p = torch.tensor(p, dtype=torch.float32)\n s = torch.cat((s,p))\n return s\n\n def get_action(self, state, greedy=True):\n if greedy:\n with torch.no_grad():\n q = (self.qf1(state)+ self.qf2(state))/2\n q = q.cpu()\n q = q.numpy()\n a = q.argmax()\n else:\n a = np.random.choice(self.nA)\n return a\n\n def get_eps_greedy_action(self, state):\n eps = 1/math.sqrt(self.n_episode/10000)\n eps = min(eps, 0.5)\n p = np.random.random()\n if p > eps:\n with torch.no_grad():\n q = self.qf(state)\n q = q.cpu()\n q = q.numpy()\n a = q.argmax()\n else:\n a = np.random.choice(self.nA)\n return a\n\n def get_DQ_eps_action(self, state):\n eps = 1/math.sqrt(self.n_episode/10000)\n eps = min(eps, 0.5)\n p = np.random.random()\n if p > eps:\n with torch.no_grad():\n q1 = self.qf1(state)\n q2 = self.qf2(state)\n q = (q1+q2)/2\n q = q.cpu()\n q = q.numpy()\n a = q.argmax()\n else:\n a = np.random.choice(self.nA)\n return a\n\n def get_softmax_action(self, state,tau):\n with torch.no_grad():\n q = self.qf(state)\n q = q.cpu()\n q = q.numpy()\n soft_q = get_softmax(q,tau)\n a = np.random.choice(4,1,p=soft_q)\n return a\n\n def TD_update_Q(self, s,a,r,sp):\n s = torch.tensor(s)\n q = self.qf(s)[a]\n if sp is None:\n t = torch.tensor(float(r))\n else:\n sp = torch.tensor(sp)\n with torch.no_grad():\n t = r + self.qf(sp).max()\n #loss = F.mse_loss(q, t)\n loss = F.smooth_l1_loss(q, t)\n #loss = F.soft_margin_loss(q,t)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n def TD_update_DQ(self, s,a,r,sp):\n s = torch.tensor(s)\n\n if sp is None:\n t = torch.tensor(float(r))\n else:\n sp = torch.tensor(sp)\n with torch.no_grad():\n if self.choice == 1:\n t = r + self.qf2(sp).max()\n else:\n t = r + self.qf1(sp).max()\n if self.choice == 1:\n q = self.qf1(s)[a]\n\n #loss = F.l1_loss(q,t)\n loss = F.mse_loss(q, t)\n #loss = F.smooth_l1_loss(q, t)\n #loss = F.kl_div(q,t)\n #loss = F.multilabel_soft_margin_loss(q,t)\n\n #loss = F.poisson_nll_loss(q,t)\n #loss = F.cross_entropy(q,t)\n #loss = F.hinge_embedding_loss(q,t)\n #loss = F.multilabel_margin_loss(q,t)\n #loss = F.multi_margin_loss(q,t)\n #loss = F.nll_loss(q,t)\n #loss = F.soft_margin_loss(q,t)\n\n self.optimizer1.zero_grad()\n loss.backward()\n self.optimizer1.step()\n else:\n q = self.qf2(s)[a]\n\n #loss = F.l1_loss(q,t)\n loss = F.mse_loss(q, t)\n #loss = F.smooth_l1_loss(q, t)\n #loss = F.kl_div(q,t)\n #loss = F.multilabel_soft_margin_loss(q,t)\n\n #loss = F.poisson_nll_loss(q,t)\n #loss = F.cross_entropy(q,t)\n #loss = F.hinge_embedding_loss(q,t)\n #loss = F.multilabel_margin_loss(q,t)\n #loss = F.multi_margin_loss(q,t)\n #loss = F.nll_loss(q,t)\n #loss = F.soft_margin_loss(q,t)\n\n self.optimizer2.zero_grad()\n loss.backward()\n self.optimizer2.step()\n\n\n def Batch_update(self,batch_size):\n sample = self.Trans_Memory.sample(batch_size)\n for i in range(len(sample)):\n s,a,r,sp = sample[i]\n self.TD_update_DQ(s,a,r,sp)\n\n def reset_episode(self):\n self.n_episode += 1\n\n def run_episode1(self, batch_size):\n p = random.random()\n if p < 0.5:\n self.lr_scheduler1.step()\n self.choice = 1\n else:\n self.lr_scheduler2.step()\n self.choice = 2\n self.n_episode += 1\n self.casino.start_game()\n s = self.get_state()\n done = False\n while not done:\n #tau = math.sqrt(1/self.n_episode)\n #a = self.get_softmax_action(s,tau)\n #a = self.get_eps_greedy_action(s)\n a = self.get_DQ_eps_action(s)\n _, reward, done = self.casino.step(a)\n if done: sp = None\n else: sp = self.get_state()\n self.Trans_Memory.push(s,a,reward,sp)\n s = sp\n if len(self.Trans_Memory.memory) > batch_size*100:\n self.Batch_update(batch_size)\n\n\n def run_simulation(self, n_episode=1E7, max_time=6000000):\n stime = time.time()\n ip1 = 0\n self.Trans_Memory = ReplayMemory(1000)\n self.n_episode = 0\n\n while time.time() - stime < max_time:\n ip1 += 1\n if ip1 > n_episode: break\n self.run_episode1(self.batch_size)\n\n if ip1 % 10000 == 0:\n print (ip1, 'lr = %f'%((self.optimizer1.param_groups[0]['lr']+self.optimizer2.param_groups[0]['lr'])/2))\n w = self.test_performance(30000) * 100\n print(ip1, 'winning rate = ', w)\n print('--------------------------------------')\n #self.plot_Q()\n\n print(\"learning complete\")\n\n def get_all_state_tensor(self, p):\n S = torch.zeros((self.nDS * self.nPS * self.nPA, self.dimS()))\n k = 0\n for ds in range(self.nDS):\n for ps in range(self.nPS):\n for ua in range(self.nPA):\n S[k][0] = ds\n S[k][1] = ps\n S[k][2] = ua\n k += 1\n return S\n\n def plot_Q(self, p=None, fid=0):\n if p is None:\n p = np.zeros(10)\n p.fill(1 / 13)\n p[8] = 4 / 13\n S = self.get_all_state_tensor(p)\n with torch.no_grad():\n Q = self.qf(S)\n Q = Q.numpy()\n Q = Q.reshape(self.nSnA)\n pi = Q.argmax(-1)\n Q[0:2, :, :, :] = -2\n Q[:, 0:4, :, :] = -2\n Q[:, 22, :, :] = -2\n Q[:, 4:12, 1, :] = -2\n pi[0:2, :] = -2\n pi[:, 0:4, :] = -2\n pi[:, 22, :] = -2\n pi[:, 4:12, 1] = -2\n\n fig = plt.figure(fid, figsize=(7, 8), clear=True)\n for ua in range(self.nPA):\n for a in range(self.nA):\n self.plot_Qi(fig, Q, a, ua)\n self.plot_pi(fig, pi, ua)\n self.diff_Q(fig, Q, pi)\n plt.draw()\n plt.pause(1)\n\n def plot_Qi(self, fig, Q, a, ua):\n ax = fig.add_subplot(6, 2, 2 * a + ua + 1)\n ax.imshow(Q[:, :, ua, a], vmin=-2, vmax=1)\n\n def plot_pi(self, fig, pi, ua):\n ax = fig.add_subplot(6, 2, 9 + ua)\n ax.imshow(pi[:, :, ua], vmin=-2, vmax=self.nA - 1)\n\n def diff_Q(self, fig, Q, pi):\n if 'pi_old' in dir(self):\n PIdiff = (pi != self.pi_old)\n Qdiff = (Q - self.Q_old)\n print(\"PI diff = %d\" % (PIdiff.sum()))\n print('Qdiff max=%.3f, min=%.3f' % (Qdiff.max(), Qdiff.min()))\n ax = fig.add_subplot(6, 2, 11)\n ax.imshow(PIdiff[:, :, 0])\n ax = fig.add_subplot(6, 2, 12)\n ax.imshow(PIdiff[:, :, 1])\n self.Q_old = Q\n self.pi_old = pi\n\n def update_pocket(self, reward):\n self.pocket += reward\n\n def play_game(self):\n self.test_episode += 1\n self.casino.start_game()\n done = False\n while not done:\n s = self.get_state()\n a = self.get_action(s, greedy=True)\n _, reward, done = self.casino.step(a)\n self.update_pocket(reward)\n return reward\n\n def print_epg_wr(self, n_games):\n epg = self.pocket / n_games\n wr = (epg + 1) / 2\n std_wr = np.sqrt(wr * (1 - wr) / n_games)\n print(\"# of game=%d, player's pocket=%d, E/G=%.5f, WR=%.5f%% +- %.5f\"\n % (n_games, self.pocket, epg, wr * 100, std_wr * 100))\n return wr\n\n def test_performance(self, n_games):\n self.pocket = 0\n n_10 = n_games / 10\n for i in range(1, n_games + 1):\n reward = self.play_game()\n if n_games > 100000 and i % n_10 == 0:\n self.print_epg_wr(i)\n print (\"Final result\")\n return self.print_epg_wr(n_games)\n","sub_path":"RL(Reinforcement Learning)/Blackjack/other Players/NNPlayer_Optimizer_selection.py","file_name":"NNPlayer_Optimizer_selection.py","file_ext":"py","file_size_in_byte":13586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496298004","text":"class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n \nclass creatTree:#先序遍历创建二叉树\n def __init__(self, arr):\n self.arr = arr\n self.root = None\n self.creatXian(0,None)\n def creatXian(self, k, Node):\n if k == 0:\n self.root = TreeNode(self.arr[k])\n self.creatXian(k+1,self.root)\n else:\n #Node.left\n if self.arr[k] is None:\n Node.left = None\n #Node.right\n if self.arr[k+1] is None:\n Node.right = None\n return k+1\n else:\n Node.right = TreeNode(self.arr[k+1])\n n = self.creatXian(k+2,Node.right)\n return n\n else:\n Node.left = TreeNode(self.arr[k])\n n = self.creatXian(k+1,Node.left)\n\n #Node.right\n if self.arr[n+1] is None:\n Node.right = None\n return n+1\n else:\n Node.right = TreeNode(self.arr[n+1])\n n = self.creatXian(n+2,Node.right)\n return n\n \na = creatTree([3,9,None,None,20,15,None,None,7,None,None])\nclass Solution:\n def __init__(self, root):\n self.root = root\n self.load = []\n self.averageOfLevels([self.root])\n print(self.load)\n\n def averageOfLevels(self, arr):\n temp = []\n sumnumb = 0\n for i in range(len(arr)):\n sumnumb += arr[i].val\n if arr[i].left is not None:\n temp.append(arr[i].left)\n if arr[i].right is not None:\n temp.append(arr[i].right)\n self.load.append(sumnumb/len(arr))\n if len(temp) != 0:\n self.averageOfLevels(temp)\n else:\n return\n","sub_path":"code/二叉树每层平均值.py","file_name":"二叉树每层平均值.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"615748589","text":"class UnionFind:\r\n\r\n def __init__(self, n):\r\n self.table = [-1] * (n + 1)\r\n self.size = [1] * (n + 1)\r\n\r\n def merge(self, r1, r2):\r\n self.table[r1] = r2\r\n self.size[r2] += self.size[r1]\r\n self.size[r1] = 0\r\n\r\n def find_root(self, k):\r\n path = []\r\n curr = k\r\n while self.table[curr] != -1:\r\n path.append(curr)\r\n curr = self.table[curr]\r\n for i in path:\r\n self.table[i] = curr\r\n return curr\r\n\r\n\r\ndef solve(string):\r\n n, m, *ab = map(int, string.split())\r\n ab = ab[::-1]\r\n ans = [n * (n - 1) // 2]\r\n uf = UnionFind(n)\r\n for _b, _a in zip(ab[::2], ab[1::2]):\r\n ra = uf.find_root(_a)\r\n rb = uf.find_root(_b)\r\n if ra == rb:\r\n ans.append(ans[-1])\r\n continue\r\n ans.append(ans[-1] - uf.size[ra] * uf.size[rb])\r\n uf.merge(ra, rb)\r\n return \"\\n\".join([str(a) for a in ans[:-1][::-1]])\r\n\r\n\r\nif __name__ == '__main__':\r\n n, m = map(int, input().split())\r\n print(solve('{} {}\\n'.format(n, m) + '\\n'.join([input() for _ in range(m)])))","sub_path":"Source Codes/AtCoder/abc120/D/4902363.py","file_name":"4902363.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"108112611","text":"from webalchemy.Stacker import Stacker\nfrom sympy import *\n\nexamples = [\n (r'Take the derivative of \\(\\sin{(x)}e^x\\)', 'diff(sin(x)*exp(x), x)'),\n (r'Compute \\(\\int(e^x\\sin{(x)} + e^x\\cos{(x)})\\,dx\\)', 'integrate(exp(x)*sin(x) + exp(x)*cos(x), x)'),\n (r'Compute \\(\\int_{-\\infty}^\\infty \\sin{(x^2)}\\,dx\\)', 'integrate(sin(x**2), (x, -oo, oo))'),\n (r'Find \\(\\lim_{x\\to 0}\\frac{\\sin{(x)}}{x}\\)', 'limit(sin(x)/x, x, 0)'),\n (r'Solve \\(x^2 - 2 = 0\\)', 'solve(x**2 - 2, x)'),\n (r'Solve the differential equation \\(y'' - y = e^t\\)', '''y = Function('y'); dsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t))'''),\n (r'Find the eigenvalues of \\(\\left[\\begin{smallmatrix}1 & 2\\\\2 & 2\\end{smallmatrix}\\right]\\)', 'Matrix([[1, 2], [2, 2]]).eigenvals()'),\n (r'Rewrite the Bessel function \\(J_{\\nu}\\left(z\\right)\\) in terms of the spherical Bessel function \\(j_\\nu(z)\\)','besselj(nu, z).rewrite(jn)')\n]\n\nfunctions = ['diff', 'integrate', 'limit', ]\n\nclass MathExplorer:\n \"\"\"Application to explore math from the browser\"\"\"\n\n include = ['//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',\n '//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js',\n 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML']\n stylesheets = ['//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css']\n\n def initialize(self, **kwargs):\n self.rdoc = kwargs['remote_document']\n s = Stacker(self.rdoc.body)\n with s.div(cls='container'), s.div(cls='row'), s.div(cls='col-md-12 page-header'):\n with s.h1(text=\"The Math Exploerer\"):\n s.small(text=\" use it for... uhm... exploring math?\")\n with s.div(cls='row'):\n # left column\n with s.div(cls='col-md-7'), s.div(cls='row'):\n with s.div(cls='col-md-12 panel panel-default'):\n self.pbody = s.div(cls='panel-body', style={'minHeight':'500px', 'overflowY':'auto'})\n with s.div(cls='row'), s.div(cls='col-md-12'), s.div(cls='well'):\n self.inp = s.input(cls='form-control', att={'placeholder': \"Enter Math here (see examples)\"})\n self.inp.events.add(keydown=self.execute, translate=True)\n # right column\n with s.div(cls='col-md-5'):\n\n with s.div(cls='row'), s.div(cls='col-md-12'), s.div(cls='panel panel-success'), s.div(text=\"Examples:\", cls='panel-heading'):\n s.button(text=\"toggle\", att={'data-toggle':\"collapse\", 'data-target':\"#examples_body\"}, cls=\"btn btn-xs btn-default pull-right\")\n with s.div(customvarname='examples_body', cls='panel-body collapse in'):\n with s.ul():\n for desc, codes in examples:\n with s.li(text=desc.replace('\\\\', '\\\\\\\\')):\n for code in codes.split(';'):\n s.br()\n s.code(text=code).events.add(click=lambda: self.inp.prop(value=code))\n with s.div(cls='row'), s.div(cls='col-md-12'), s.div(cls='panel panel-info'):\n s.div(text=\"Symbols:\", cls='panel-heading')\n s.div(text=\"x\", cls='panel-body')\n with s.div(cls='row'), s.div(cls='col-md-12'), s.div(cls='panel panel-info'):\n s.div(text=\"Functions:\", cls='panel-heading')\n s.div(text=\"bla bla\", cls='panel-body')\n self.rdoc.JS('MathJax.Hub.Queue([\"Typeset\",MathJax.Hub, \"examples_body\"]);')\n\n def execute(e):\n if e.keyCode == weba.KeyCode.ENTER:\n rpc(self.calc_with_sympy, self.value)\n\n def calc_with_sympy(self, sender_id, text):\n try:\n self.pbody.element(p=str(sympify(text)))\n except Exception as e:\n self.pbody.element('p').prop.innerHTML = str(e).replace(\"\\n\", '<br>')\n\n\nif __name__ == \"__main__\":\n from webalchemy import server\n from math_explorer import MathExplorer\n server.run(MathExplorer)\n\n\n\n\n","sub_path":"examples/math_explorer/math_explorer.py","file_name":"math_explorer.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"194049743","text":"#!python\r\n\r\nfrom tkinter import *\r\n\r\nclass Application(Frame):\r\n\tdef say_hi(self):\r\n\t\tprint(\"hi there, everyone!\")\r\n\r\n\tdef createWidgets(self):\r\n\t\tself.Forward = Button(self, text=\"/\\\\\", command=lambda: self.control(\"F\"), font=(20))\r\n\t\tself.Reverse = Button(self, text=\"V\", command=lambda: self.control(\"R\"), font=(20))\r\n\t\tself.Left = Button(self, text=\"<\", command=lambda: self.control(\"L\"), font=(20))\r\n\t\tself.Right = Button(self, text=\">\", command=lambda: self.control(\"R\"), font=(20))\r\n\t\tself.QUIT = Button(self, text=\"QUIT\", fg=\"red\", command=self.quit)\r\n\t\tself.QUIT.focus()\r\n\t\t\r\n\r\n\t\tself.Forward.grid(column=1, row=0)\r\n\t\tself.Left.grid(column=0, row=1)\r\n\t\tself.QUIT.grid(column=1, row=1)\r\n\t\tself.Right.grid(column=2, row=1)\r\n\t\tself.Reverse.grid(column=1, row=2)\r\n\r\n#\t\tself.hi_there = Button(self)\r\n#\t\tself.hi_there[\"text\"] = \"Hello\",\r\n#\t\tself.hi_there[\"command\"] = self.say_hi\r\n\r\n#\t\tself.hi_there.pack({\"side\": \"left\"})\r\n\r\n\tdef __init__(self, master=None):\r\n\t\tFrame.__init__(self, master)\r\n\t\tself.pack()\r\n\t\tself.createWidgets()\r\n\r\n\tdef control(self, command):\r\n\t\tprint(command)\r\n\r\ndef main():\r\n\troot = Tk()\r\n\tapp = Application(master=root)\r\n\tapp.mainloop()\r\n\troot.destroy()\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()","sub_path":"tk/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"185528678","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 12 21:25:25 2018\n\n@author: Thinkpad\n\"\"\"\n\nimport cv2\nimport numpy as np\nfrom driver import driver\n\ncap=cv2.VideoCapture(0)\nd=driver()\nd.setStatus(mode=\"speed\")\n\n#*****************************图像处理部分***********************************\n#***************************************************************************\n\ndef ImgPro():\n #img = cv2.imread(\"F://testimages//road2.jpg\", cv2.IMREAD_COLOR) \n img=cap.read()\n cv2.imshow(\"color\", img )\n dst=img.copy()\n\n size=np.shape(img)\n height=size[0]\n width=size[1]\n\n grayImg=cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)\n #cv2.imshow(\"grayImg\",grayImg)\n medianImg= cv2.medianBlur(grayImg,3)\n #cv2.imshow(\"medianImg\",medianImg)\n ret,binary=cv2.threshold(medianImg,80,255,cv2.THRESH_BINARY_INV)\n #ret2,binary = cv2.threshold(medianImg,0,100,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n #cv2.imshow(\"binary\",binary)\n kernel = np.ones((2,2),np.uint8)\n opening = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)\n #cv2.imshow(\"open\",opening)\n\n #近处参考点用于控制当拍动作\n rec_sum=0\n rec_num=0\n for i in range(height-3,height-1) :\n for j in range(width-5):\n if (opening[i][j]==255 and opening[i][j+1]==255 and opening[i][j+2]==255 and opening[i][j+3]==255 and opening[i][j+4]==255):\n rec_num+=1\n rec_sum+=j\n ref=rec_sum/rec_num\n \n p1=(ref,0)\n p2=(ref,height)\n cv2.line(opening,p1,p2,(255))\n #cv2.imshow(\"opening\",opening)\n \n #远处参考点用于预测前方路段形状\n rec_sum=0\n rec_num=0\n pre_ref=0\n for i in range(height-43,height-40) :\n for j in range(width-5):\n if (opening[i][j]==255 and opening[i][j+1]==255 and opening[i][j+2]==255 and opening[i][j+3]==255 and opening[i][j+4]==255):\n rec_num+=1\n rec_sum+=j\n pre_ref=rec_sum/rec_num\n p1=(pre_ref,0)\n p2=(pre_ref,height)\n cv2.line(opening,p1,p2,(255))\n cv2.imshow(\"opening\",opening)\n \n #sign_detector\n flag=0\n \n \n \n if cv2.waitKey(1) & 0xFF==ord('p'):\n cv2.imwrite('test'+str(1)+'.jpg',img)\n \n \n cv2.waitKey(0) \n cv2.destroyAllWindows()\n \n return ref,pre_ref,flag\n\n#***************************main**********************************************\nwhile(1):\n ref,pre_ref,flag=ImgPro()\n if (flag==1):\n d.setStatus(motor=0.0, servo=0.0, dist=0x00, mode=\"stop\")\n break\n \n if (pre_ref<160 or pre_ref>480):\n sm=0.2\n else:\n sm=0.5\n \n if (ref<352 & ref>288):\n st=0\n else:\n st=-(320-ref)*0.02\n \n d.setStatus(motor = sm, servo = st)\n \n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"cruise.py","file_name":"cruise.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"585696149","text":"# -*- coding: utf-8 -*-\nfrom core.mlang.forms import TranslatedForm\nfrom core.mlang.utils import translate\nfrom django.utils.translation import get_language\nfrom .models import Page\nfrom django.contrib import admin\n\n\nclass PageAdmin(admin.ModelAdmin):\n form = TranslatedForm\n\n suit_form_tabs = (\n (\"general\", 'General'),\n (\"seo\", \"Seo\"),\n (\"content\", \"Content\"),\n )\n\n fieldsets = [\n (None, {\n 'classes': ('suit-tab suit-tab-general',),\n 'fields': ['code', 'parent']\n }),\n (None, {\n 'classes': ('suit-tab suit-tab-seo',),\n 'fields': [\"title\", \"description\", \"keywords\"]}),\n (None, {\n 'classes': ('suit-tab suit-tab-content',),\n 'fields': ['content']}),\n ]\n\n def get_queryset(self, request):\n qs = super(PageAdmin, self).get_queryset(request).filter(id__isnull=False)\n return translate(qs, get_language(), exclude=['description', 'keywords', 'content'])\n\n\nadmin.site.register(Page, PageAdmin)","sub_path":"apps/flatpages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"180084634","text":"#coding:utf-8\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.utils import timezone\nfrom .models import *\nimport json\nimport logging\nimport datetime\nimport time\n\ndef index(request):\n return HttpResponse(u\"欢迎光临本站!\")\n\ndef home(request):\n subjectlist = []\n pageIndex = int(request.GET.get('pageIndex',1))\n pagesize = 15\n subjectlist = Subject.objects.all()[(pageIndex-1)*pagesize:pageIndex*pagesize-1]\n pagetotal = (Subject.objects.all().count()-1)/pagesize + 1\n if pagetotal==0:\n pagetotal = 1\n\n pageinfo = {\n 'pageIndex':pageIndex,\n 'pageprev2':False,\n 'pageprev':False,\n 'pagenext':False,\n 'pagenext2':False\n }\n if pageIndex-2 > 0:\n pageinfo['pageprev2']=pageIndex-2\n if pageIndex-1 > 0:\n pageinfo['pageprev']=pageIndex-1\n if pageIndex < pagetotal:\n pageinfo['pagenext'] = pageIndex+1\n if pageIndex+1 < pagetotal:\n pageinfo['pagenext2']=pageIndex+2\n\n return render(request,'vote.html',{'subjectlist':subjectlist,'pageinfo':pageinfo})\n # logging.debug(request.session['username'])\n\ndef createvote(request):\n subject = request.GET['subject']\n deadline = request.GET['deadline']\n options = request.GET.getlist('options[]')\n # print subject\n ret = {'status_code':'success'}\n for item in options:\n # print item\n if item==\"\":\n ret = {'status_code':'fail'}\n if subject == \"\" or deadline==\"\":\n ret = {'status_code':'fail'}\n if ret['status_code'] == 'fail':\n return HttpResponse(json.dumps(ret),content_type='application/json')\n # print deadline\n t= time.strptime(deadline, \"%Y-%m-%d - %H:%M\")\n y,m,d,h,mm = t[0:5]\n obj_time = datetime.datetime(y,m,d,h,mm)\n # print obj_time\n obj_sub = Subject.objects.create(title=subject,deadline=obj_time)\n for option in options:\n obj_opt = Option.objects.create(subject=obj_sub,name=option)\n \n return HttpResponse(json.dumps(ret),content_type='application/json')\n\ndef votequery(request):\n ret = {'vote_status':'ok'}\n subject_id = request.GET['subject_id']\n obj_sub = Subject.objects.get(id=subject_id)\n # time_now = datetime.datetime.now()\\\n time_now = timezone.now()\n if time_now >= obj_sub.deadline:\n ret['vote_status'] = 'over_deadline'\n return HttpResponse(json.dumps(ret),content_type='application/json')\n options = Option.objects.filter(subject=obj_sub)\n result = VoteRecord.objects.filter(option__in=options,user=request.user)\n if len(result)==1:\n ret['vote_status'] = 'vote_already'\n return HttpResponse(json.dumps(ret),content_type='application/json')\n\n \ndef optionquery(request):\n options = []\n subject_id = request.GET['subject_id']\n obj_sub = Subject.objects.get(id=subject_id)\n obj_opt_list = Option.objects.filter(subject=obj_sub)\n for obj in obj_opt_list:\n entity = {}\n entity['id'] = obj.id\n entity['name'] = obj.name\n options.append(entity)\n ret = {'options':options}\n return HttpResponse(json.dumps(ret),content_type='application/json')\n\ndef votesubmit(request):\n option_id = request.GET.get('option_id',None)\n ret = {'status_code':'fail'}\n if option_id == None:\n ret = {'status_code':'nopara'}\n return HttpResponse(json.dumps(ret),content_type='application/json')\n\n obj_opt = Option.objects.get(id=option_id)\n result = VoteRecord.objects.get_or_create(user=request.user,option=obj_opt)\n\n #重新计算主题得票王\n obj_sub = obj_opt.subject\n options = Option.objects.filter(subject=obj_sub)\n opt_hot = \"\"\n num_max = 1\n for option in options:\n num = VoteRecord.objects.filter(option=option).count()\n if num > num_max:\n num_max = num\n opt_hot = option.name\n elif num == num_max:\n opt_hot = opt_hot + \" \" + option.name\n obj_sub.hot = opt_hot\n # print opt_hot\n # print obj_sub.hot\n obj_sub.save()\n # print 'after save'\n # obj_sub = obj_opt.subject\n # print obj_sub.hot\n\n if result[1]==True:\n ret['status_code']='success'\n return HttpResponse(json.dumps(ret),content_type='application/json')\n \ndef voteresult(request):\n subject_id = request.GET['subject_id']\n result = []\n obj_sub = Subject.objects.get(id=subject_id)\n obj_opt_list = Option.objects.filter(subject=obj_sub)\n for obj_opt in obj_opt_list:\n count = VoteRecord.objects.filter(option=obj_opt).count()\n entity = {}\n entity['name'] = obj_opt.name\n entity['count'] = count\n result.append(entity)\n ret = {'result':result}\n return HttpResponse(json.dumps(ret),content_type='application/json')\n\n\ndef test(request):\n return HttpResponse(request.user.username)\n # logging.debug(request.session['username'])\n\n# Create your views here.\n","sub_path":"vote/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"604383002","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'junk.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$','views.dashboard'),\n url(r'^facebook_connect/$', 'views_fb.facebook_connect'),\n url('^accounts/facebook_callback/$','views_fb.facebook_callback'),\n url(r'^twitter_connect/$','views_tw.twitter_connect'),\n url(r'^accounts/twitter_callback/$','views_tw.twitter_callback'),\n url('^accounts/login/$','views_login.login_screen'),\n url('^accounts/create/$','views_login.create'),\n url('^confirmed/$','views_login.confirmed'),\n url('^accounts/logout/$','views_login.logout_view'),\n url(r'^in_connect/$','views_in.in_connect'),\n url(r'^accounts/in_callback/$','views_in.in_callback'),\n url(r'^g_connect/$','views_g.g_connect'),\n url(r'^accounts/g_callback/$','views_g.g_callback'),\n url(r'^instagram_connect/$','views_instagram.instagram_connect'),\n url(r'^accounts/instagram_callback/$','views_instagram.instagram_callback'), \n\n url(r'^upload/$','views_upload.upload'),\n url(r'^upload_process/$','views_upload.upload_process'),\t\n\n #custom tab for FB Biz page\n url(r'^fb_custom_tab/$','views_fb_custom_tab.custom_tab'),\n\n url(r'^ajax_call/$','views_ajax.ajax_call'),\n\n)\n","sub_path":"junk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"546861293","text":"'''\nACFun is a Chinese Video sharing website\n'''\n\nfrom .common import InfoExtractor\nimport re\nfrom .sina import SinaIE\n\nclass ACFunIE(InfoExtractor):\n _VALID_URL = r'^https?://(?:www\\.)?acfun\\.tv/v/(?P<id>[a-zA-Z0-9]+)'\n _TESTS = [\n {\n u'url' : u'http://www.acfun.tv/v/ac976407',\n u'file' : u'pv 22-123189263.flv'\n }\n ]\n\n def _real_extract(self, url):\n mobj = re.match(self._VALID_URL, url)\n\n vid = mobj.group('id')\n webpage = self._download_webpage(url, vid)\n vid = self._html_search_regex(\n r'data-vid\\=\\\"([0-9]*)\\\"', webpage, u'vid')\n\n info = self._download_json(\"http://www.acfun.tv/video/getVideo.aspx?id=%s\" % vid, vid)\n if info['sourceType'] == \"sina\":\n return self.url_result(\"http://video.sina.com.cn/something/?vid=%s\" % info['sourceId'])\n elif info['sourceType'] == \"yoku\":\n return self.url_result(\"http://v.youku.com/v_show/id_%s.html\" % info['sourceId'])\n elif info['sourceType'] == \"tudou\":\n raise Error('tudou is not supported yet via acfun')\n elif info['sourceType'] == \"qq\":\n raise Error('qq downloading is not supported via youtube-dl')\n else:\n raise Error('source type not supported: %s' % info['sourceType'])\n","sub_path":"youtube_dl/extractor/acfun.py","file_name":"acfun.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219924521","text":"\"\"\"Calico utility script.\n\nCalico utility script\n\"\"\"\n\nimport yaml\n\n# needed this to execute from the command line, otherwise received an ImportError\n# import os, sys\n# sys.path.insert(0, os.path.abspath(\"..\"))\n\nimport interfaces\nfrom utils import ConfigReader\nfrom utils import jm_general\nfrom snmp import poll\nfrom snmp import snmp_manager\nfrom snmp import snmp_info\nfrom web import ws_device\n\nimport urllib.request\nimport string\nimport os\n\n# from pprint import pprint\n\nOUI_URL = 'http://standards-oui.ieee.org/oui.txt'\nOUI_YAML_FILE_NAME = \"oui_data.yaml\"\n\nCACHE_FILE_PATH = '{}/bin/oui.txt'.format(os.getcwd())\nFILE_LOCATION = '{}/data/aux/{}'.format(os.getcwd(), OUI_YAML_FILE_NAME)\n\n\ndef main():\n \"\"\"Main Function.\n\n Args:\n None\n Returns:\n None\n \"\"\"\n # Initialize key variables\n additional_help = \"\"\"\\ \n\tUtility script for the project.\n\t\"\"\"\n\n # Process the CLI\n cli_object = interfaces.Cli(additional_help=additional_help)\n cli_args = cli_object.args()\n\n # Process the config\n config = ConfigReader(cli_args.directory)\n\n # Show configuration data\n if cli_args.mode == 'config':\n do_config(cli_args, config)\n\n # Show interesting information\n if cli_args.mode == 'test':\n do_test(cli_args, config)\n\n # Process hosts\n if cli_args.mode == 'poll':\n do_poll(config, cli_args.verbose)\n\n # Create pages\n if cli_args.mode == 'pagemaker':\n do_pages(config, cli_args.verbose)\n\n # Get vendor OUI MAC addresses\n if cli_args.mode == 'oui':\n do_oui(cli_args, config)\n\n\ndef do_config(cli_args, config):\n \"\"\"Process 'config' CLI option.\n\n Args:\n connectivity_check: Set if testing for connectivity\n Returns:\n None\n \"\"\"\n # Show hosts if required\n if cli_args.hosts is True:\n print('hosts:')\n print(yaml.dump(config.hosts(), default_flow_style=False))\n\n # Show hosts if required\n if cli_args.snmp_auth is True:\n print('snmp_auth:')\n print(yaml.dump(config.snmp_auth(), default_flow_style=False))\n\n\ndef do_test(cli_args, config):\n \"\"\"Process 'test' CLI option.\n\n Args:\n connectivity_check: Set if testing for connectivity\n Returns:\n None\n \"\"\"\n # Show host information\n validate = snmp_manager.Validate(cli_args.host, config.snmp_auth())\n snmp_params = validate.credentials()\n snmp_object = snmp_manager.Interact(snmp_params)\n\n if bool(snmp_params) is True:\n print('\\nValid credentials found:\\n')\n print(yaml.dump(snmp_params, default_flow_style=False))\n print('\\n')\n\n # Get SNMP data and print\n status = snmp_info.Query(snmp_object)\n yaml_data = status.everything()\n print(yaml_data)\n else:\n # Error, host problems\n log_message = (\n 'Uncontactable host %s or no valid SNMP '\n 'credentials found for it.') % (cli_args.host)\n jm_general.logit(1006, log_message)\n\n\ndef do_pages(config, verbose=False):\n \"\"\"Process 'pagemaker' CLI option.\n\n Args:\n config: Configuration object\n verbose: Verbose output if True\n Returns:\n None\n \"\"\"\n # Poll\n ws_device.make(config, verbose)\n\n\ndef do_poll(config, verbose=False):\n \"\"\"Process 'run' CLI option.\n\n Args:\n config: Configuration object\n verbose: Verbose output if True\n Returns:\n None\n \"\"\"\n # Poll\n poll.snmp(config, verbose)\n\n\ndef do_oui(cli_args, config):\n \"\"\"\n\n Converts the groups of addresses that are assigned to NIC manufacturers based on the first 3 bytes of the address\n into a YAML file stored in data/aux in directory\n\n :param config:\n :param verbose:\n :return: None\n \"\"\"\n\n oui_data = {}\n if cli_args.inet:\n print('Reading OUI data from url:{}'.format(OUI_URL))\n response = urllib.request.urlopen(OUI_URL)\n # This is a very timely(>10 mins) operation\n data = response.read()\n data = data.split(\"\\n\")\n for line in data:\n hex_value = line[:6]\n if all(x in string.hexdigits for x in hex_value):\n organization = line[6:].replace(\"(base 16)\", \"\").strip().title()\n oui_data[hex_value.lower()] = organization\n else:\n print('Reading OUI MAC Address data from local cache file in bin')\n with open(CACHE_FILE_PATH, 'r') as file_data:\n for line in file_data:\n hex_value = line[:6]\n if all(x in string.hexdigits for x in hex_value):\n organization = line[6:].replace(\"(base 16)\", \"\").strip().title()\n oui_data[hex_value.lower()] = organization\n with open(FILE_LOCATION, 'wt+') as f:\n yaml.dump(oui_data, f, default_flow_style=False)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"infoset/toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"528998823","text":"\"\"\"\n3-way quicksort: Python implementation\n\nDuplicate keys\nMergesort with duplicate keys. Always between 1/2 NlgN and NlgN compares\n\nQuicksort with duplicate keys. The classic algorithm goes quadratic unless partitioning stops on equal keys\nRecommended: Stop scan on items equal to the partitioning item\nConsequence: ~NlgN compares when all keys equal\n\nBottom line: Randomized quicksort with 3-way partitioning reduces running time from linearithmic to linear in a broad class of applications.\nQuicksort with 3-way partitioning is most effective when the input array has a few distinct items?\n\nDijkstra 3-way partitioning\n\nEngineering a system sort\nBasic algorithm - quick sort\n - Cutoff to insertion sort for small subarrays\n - Partitioning scheme: 3-way partitioning\n - Partitioning items\n Large arrays: middle entry\n medium arrays: median of 3\n large arrays: Tukey's ninther\n\"\"\"\n\ndef quicksort(a, lo, hi):\n \"\"\"\n 3-way quicksort: Python implementation\n :param a: Array\n :param lo: low Index\n :param hi: high index\n \"\"\"\n if hi <= lo:\n return\n lt, gt = lo, hi\n i = lo\n while i <= gt:\n if a[i] < a[lt]:\n a[lt],a[i] = a[i],a[lt]\n lt += 1\n i += 1\n elif a[i] > a[lo]:\n a[gt],a[i] = a[i],a[gt]\n gt -= 1\n else:\n i += 1\n\n quicksort(a, lo, lt - 1)\n quicksort(a, gt + 1, hi)\n\n # assert isSorted(a) # Postcondition: a is sorted\n\n\ndef isSorted(a, asc=True):\n \"\"\"\n Check if an array is sorted\n :param a: array\n :param asc: ascending or descending\n :return: boolean\n \"\"\"\n s = 2*int(asc) - 1 # sign: int(True)=1 => 2*1-1 = 1\n\n for i in range(len(a)-1):\n if s * a[i] > s * a[i+1]:\n return False\n return True\n\n\ndef test_quicksort():\n import random\n\n a = [6,2,9,2,5]\n a_sorted = [2,2,5,6,9]\n random.shuffle(a) # Shuffle array only onсу\n quicksort(a, 0, len(a)-1)\n print(\"Test\", \"1.\", \"OK\" if a == a_sorted else \"Failed\")\n print()\n\n b = [1,0,0,0,0]\n b_sorted = [0,0,0,0,1]\n random.shuffle(b) # Shuffle array only onсу\n quicksort(b, 0, len(b)-1)\n print(\"Test\", \"2.\", \"OK\" if b == b_sorted else \"Failed\")\n print()\n\n c = [1]\n c_sorted = [1]\n random.shuffle(c)\n quicksort(c, 0, len(c)-1)\n print(\"Test\", \"3.\", \"OK\" if c == c_sorted else \"Failed\")\n print()\n\n\ndef test_isSorted():\n inp = [[0, 1, 2 , 3, 4], [6, 2, 9, 2, 5]]\n out = [True, False]\n for i in range(len(inp)):\n test_res = isSorted(inp[i])\n print(\"Test\", i + 1, \":\", \"OK\" if test_res == out[i] else \"Failed\")\n print()\n\n\nif __name__ == '__main__':\n print('test_quicksort')\n test_quicksort()\n\n print('test_isSorted')\n test_isSorted()\n","sub_path":"vladvvtesla/week03_MergeSort_QuickSort/2.imp_3-way-quicksort.py","file_name":"2.imp_3-way-quicksort.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"237734353","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom xsdata.models.datatype import XmlPeriod\nfrom travelport.models.phone_number_history_2 import PhoneNumberHistory2\nfrom travelport.models.type_structured_address_5 import TypeStructuredAddress5\n\n__NAMESPACE__ = \"http://www.travelport.com/schema/uprofile_v37_0\"\n\n\n@dataclass\nclass TypePaymentCardHistory2:\n \"\"\"\n Container for all credit and debit card information.\n\n Parameters\n ----------\n phone_number_history\n billing_address\n The address to where the billing statements for this card are sent.\n Used for address verification purposes.\n type_value\n The 2 letter credit/ debit card type.\n number\n exp_date\n The Expiration date of this card in YYYY-MM format.\n name\n The name as it appears on the card.\n cvv\n Card Verification Code\n approval_code\n This code is optional for an authorization process from the Credit\n Card company directly,optional for some of the CCH carriers.\n \"\"\"\n class Meta:\n name = \"typePaymentCardHistory\"\n\n phone_number_history: None | PhoneNumberHistory2 = field(\n default=None,\n metadata={\n \"name\": \"PhoneNumberHistory\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.travelport.com/schema/uprofile_v37_0\",\n }\n )\n billing_address: None | TypeStructuredAddress5 = field(\n default=None,\n metadata={\n \"name\": \"BillingAddress\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.travelport.com/schema/uprofile_v37_0\",\n }\n )\n type_value: None | str = field(\n default=None,\n metadata={\n \"name\": \"Type\",\n \"type\": \"Attribute\",\n \"min_length\": 2,\n \"max_length\": 2,\n }\n )\n number: None | str = field(\n default=None,\n metadata={\n \"name\": \"Number\",\n \"type\": \"Attribute\",\n \"min_length\": 13,\n \"max_length\": 128,\n }\n )\n exp_date: None | XmlPeriod = field(\n default=None,\n metadata={\n \"name\": \"ExpDate\",\n \"type\": \"Attribute\",\n }\n )\n name: None | str = field(\n default=None,\n metadata={\n \"name\": \"Name\",\n \"type\": \"Attribute\",\n \"max_length\": 128,\n }\n )\n cvv: None | str = field(\n default=None,\n metadata={\n \"name\": \"CVV\",\n \"type\": \"Attribute\",\n \"max_length\": 4,\n }\n )\n approval_code: None | str = field(\n default=None,\n metadata={\n \"name\": \"ApprovalCode\",\n \"type\": \"Attribute\",\n \"min_length\": 1,\n \"max_length\": 16,\n }\n )\n","sub_path":"travelport/models/type_payment_card_history_2.py","file_name":"type_payment_card_history_2.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219547671","text":"import ROOT\nimport os\n\nclass Workflow_Handler:\n\n def __init__(self,signalname, subprocess=\"//\"):\n\n ##Where the root files are\n self.subprocess = subprocess\n\n self.norm_filename = \"rootfiles/\" + self.subprocess + \"Normalizations_table.txt\"\n self.dir_back_input = \"rootfiles/\" + self.subprocess + \"backgrounds/\"\n self.dir_data_input = \"rootfiles/\" + self.subprocess + \"data/\" \n\n self.sig_samplename = signalname\n self.sig_filename = \"rootfiles/\" + self.subprocess + \"signals/\" + \"HAA4bAnalysis_\" + self.sig_samplename + \".root\"\n\n def get_normalizations_map(self):\n in_file = open(self.norm_filename,\"r\")\n norm_map = dict()\n\n for line in in_file:\n data_norm = line.split()\n norm_map[data_norm[0]] = float(data_norm[1])\n\n return norm_map\n\n # get the sample names and signal names\n def get_samples_names(self, Add_Signal=True):\n list_dirs_bkg = os.listdir(self.dir_back_input)\n samplename_list = []\n\n for dirname in list_dirs_bkg:\n tmp_samplename = dirname.split(\"HAA4bAnalysis_\")[1]\n tmp_samplename2 = tmp_samplename.replace(\".root\",\"\")\n samplename_list.append(tmp_samplename2)\n\n if Add_Signal:\n samplename_list.append(self.sig_samplename)\n return samplename_list \n\n # get data sample names\n def get_dataSample_names(self):\n list_dirs_data = os.listdir(self.dir_data_input)\n dataName_list = []\n\n for dirname in list_dirs_data:\n tmp_dataName = dirname.split(\"HAA4bAnalysis_\")[1]\n tmp_dataName2 = tmp_dataName.replace(\".root\",\"\")\n dataName_list.append(tmp_dataName2)\n\n return dataName_list\n\n # get the corresponding root files for the background and signal sample names\n def get_root_files(self,Add_Signal=True):\n list_dirs_bkg = os.listdir(self.dir_back_input)\n root_file = dict()\n\n for dirname in list_dirs_bkg:\n tmp_samplename = dirname.split(\"HAA4bAnalysis_\")[1]\n tmp_samplename2 = tmp_samplename.replace(\".root\",\"\")\n root_file[tmp_samplename2] = ROOT.TFile(self.dir_back_input + dirname)\n\n if Add_Signal:\n root_file[self.sig_samplename] = ROOT.TFile(self.sig_filename)\n return root_file\n\n\n # get the corresponding root files for the data samples\n def get_data_root_files(self):\n list_dirs_data = os.listdir(self.dir_data_input)\n root_file_data = dict()\n\n for dirname in list_dirs_data:\n tmp_dataName1 = dirname.split(\"HAA4bAnalysis_\")[1]\n tmp_dataName2 = tmp_dataName1.replace(\".root\",\"\")\n root_file_data[tmp_dataName2] = ROOT.TFile(self.dir_data_input + dirname)\n return root_file_data\n\n\n#========================================================================================\n def get_best_combination(self, m1, m2, m3, m4):\n\n diff_m_12_34 = abs( (m1+m2).M() - (m3+m4).M() );\n diff_m_13_24 = abs( (m1+m3).M() - (m2+m4).M() );\n diff_m_14_23 = abs( (m1+m4).M() - (m2+m3).M() );\n\n diff_vector = [diff_m_12_34, diff_m_13_24, diff_m_14_23]\n diff_vector.sort()\n\n if diff_vector[0] == diff_m_12_34:\n return 1\n elif diff_vector[0] == diff_m_13_24:\n return 2\n elif diff_vector[0] == diff_m_14_23:\n return 3\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"test/Workflow_Handler.py","file_name":"Workflow_Handler.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583025358","text":"from __future__ import absolute_import\nimport sys\nimport os\nimport seaborn as sns \nimport numpy as np\nimport scipy as sp\nsys.path.append('/home/drew/Documents/')\nsys.path.append('../')\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\nfrom ops.parameter_defaults import PaperDefaults\nfrom ops.single_hp_optim_yhist import optimize_model\nfrom ops import model_utils as utils\n\n\ndef run():\n defaults = PaperDefaults()\n\n # David's globals\n size = 51\n nr = 17\n npoints = 32//2\n ncontrasts = 5\n\n # experiment parameters\n # generate stimuli\n ##################\n im = []\n for k in range(nr):\n im_ = sp.zeros((size, size)) + sp.nan\n im_[size//2-k:size//2+k+1, size//2-k:size//2+k+1] = 0.5\n im.append(im_)\n im = sp.array(im)\n\n # generate populations\n ######################\n contrasts = sp.linspace(1., 0., ncontrasts, endpoint=False)[::-1]\n # contrasts = sp.logspace(-2, 0., ncontrasts)\n x = sp.array([utils.get_population(\n xim_, 'gaussian', npoints=npoints) for xim_ in im])\n ax = [c*x for c in contrasts]\n cx = np.concatenate(ax[:], axis=0)\n\n # Experimental data\n extra_vars = {}\n extra_vars['size'] = size\n extra_vars['npoints'] = npoints\n extra_vars['nr'] = nr\n extra_vars['stimsizes'] = 2*sp.arange(nr)+1\n extra_vars['ssn'] = defaults._DEFAULT_PARAMETERS['ssn']\n extra_vars['ssf'] = defaults._DEFAULT_PARAMETERS['ssf']\n extra_vars['hp_file'] = os.path.join(defaults._FIGURES, 'best_hps.npz')\n extra_vars['figure_name'] = 'size_tuning'\n extra_vars['return_var'] = 'O'\n extra_vars['contrasts'] = contrasts\n extra_vars['curvecols'] = sns.cubehelix_palette(ncontrasts)\n extra_vars['curvelabs'] = [\n 'Single-cell response at contrast %g' % (cst,) for cst in contrasts]\n optimize_model(cx, None, extra_vars, defaults)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"single_iteration_scripts/db_size_tuning.py","file_name":"db_size_tuning.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"239913027","text":"import heapq\n\nclass Solution:\n def kSmallestPairs(self, nums1, nums2, k):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n queue = []\n def push(i, j):\n if i < len(nums1) and j < len(nums2):\n heapq.heappush(queue, [nums1[i] + nums2[j], i, j])\n push(0, 0)\n pairs = []\n while queue and len(pairs) < k:\n _, i, j = heapq.heappop(queue)\n pairs.append([nums1[i], nums2[j]])\n push(i, j + 1)\n if j == 0:\n push(i + 1, 0)\n return pairs\n\nif __name__ == \"__main__\":\n sol = Solution()\n nums1 = [1,1,2]\n nums2 = [1,2,3]\n k = 10\n print(sol.kSmallestPairs(nums1, nums2, k))","sub_path":"373. Find K Pairs with Smallest Sums.py","file_name":"373. Find K Pairs with Smallest Sums.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"632680267","text":"import numpy as np\nimport time\nimport sys\nfrom matplotlib import rc\nrc('text', usetex=True)\nimport matplotlib.pyplot as plt\nimport math\nimport ctypes\nfrom scipy.optimize import curve_fit\nstart_time = time.time()\n\n# set up parameters \nphi0 = 0.1\nR_min = 5\nR_max = 500\ndata_root_path = \"/home/dc-bamb1/GRChombo/Analysis/data/Ylm_integration_data/\"\nnum = 800\nplot_interval = 10\nM = 1\nphi0 = 0.1\nlin_or_log = False\ncolours = ['r', 'b', 'g', 'm', 'c', 'y']\ncolours2 = [\"k\", \"m\", \"y\"]\nstyles = [\"-\", \"--\"]\n\nNphi=64\nNtheta=18\nTheta_max=1.0\n\nscale = \"\"\nif (lin_or_log):\n\tscale = \"linear\"\nelse:\n\tscale = \"log\"\n\nlog_y = True\n\nclass data_dir:\n\tdef __init__(self, num, l, m, a, mu, Al, nphi, ntheta, theta_max, l_, m_):\n\t\tself.num = num\n\t\tself.l = l\n\t\tself.m = m\n\t\tself.a = float(a)\n\t\tself.mu = float(mu)\n\t\tself.nphi = nphi\n\t\tself.ntheta = ntheta\n\t\tself.theta_max = float(theta_max)\n\t\tself.Al = Al\n\t\tself.l_ = l_\n\t\tself.m_ = m_\n\t\tself.name = \"run{:04d}_l{:d}_m{:d}_a{:s}_Al{:s}_mu{:s}_M1_IsoKerr\".format(num, l, m, a, Al, mu)\n\t#\n\tdef load_data(self, number):\n\t\tfile_name = self.name+\"_rho_Ylm_integral_{:s}_r_plus_to_{:d}_nphi{:d}_ntheta{:d}_theta_max{:.1f}_l={:d}_m={:d}.dat\".format(scale, R_max, self.nphi, self.ntheta, self.theta_max, self.l_, self.m_)\n\t\tdataset_path = data_root_path + file_name\n\t\tdata = np.genfromtxt(dataset_path, skip_header=1)\n\t\tprint(\"loaded \" + file_name)\n\t\tR = data[0,1:]\n\t\tr_plus = M*(1 + np.sqrt(1 - self.a**2))\n\t\tself.r = R*(1 + r_plus/(4*R))**2\n\t\trow = int(number/plot_interval)\n\t\tself.time = data[row,0]\n\t\trho = data[row,1:]\n\t\trho0 = 0.5*(phi0**2)*(self.mu)**2\n\t\tself.rho = rho/rho0\n\t\t\ndata_dirs = []\ndef add_data_dir(num, l, m, a, mu, l_, m_):\n\tx = data_dir(num, l, m, a, mu, \"0\", Nphi, Ntheta, Theta_max, l_, m_)\n\tdata_dirs.append(x)\n\n# choose datasets to compare\n\n\"\"\"run0002_l0_m0_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0005_l1_m1_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0006_l1_m1_a0.99_Al0_mu0.4_M1_IsoKerr\nrun0007_l2_m2_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0008_l4_m4_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0009_l1_m-1_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0010_l8_m8_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0011_l1_m1_a0.7_Al0_mu2.0_M1_IsoKerr\nrun0012_l1_m1_a0.7_Al0_mu0.01_M1_IsoKerr\nrun0013_l2_m2_a0.7_Al0_mu0.8_M1_IsoKerr\nrun0014_l8_m8_a0.7_Al0_mu3.2_M1_IsoKerr\nrun0015_l1_m1_a0.7_Al0.5_mu0.4_M1_IsoKerr\nrun0016_l1_m-1_a0.99_Al0_mu0.4_M1_IsoKerr\nrun0017_l1_m1_a0.99_Al0.5_mu0.4_M1_IsoKerr\nrun0018_l1_m1_a0.99_Al0.25_mu0.4_M1_IsoKerr\"\"\"\n\n#add_data_dir(5, 1, 1, \"0.7\", \"0.4\", 2, 0)\n#add_data_dir(5, 1, 1, \"0.7\", \"0.4\", 2, 1)\nadd_data_dir(5, 1, 1, \"0.7\", \"0.4\", 2, 2)\n\ndef plot_graph():\n\t# plot setup\n\tax1 = plt.axes()\n\tfig = plt.gcf()\n\tfig.set_size_inches(3.8,3)\n\tfont_size = 10\n\ttitle_font_size = 10\n\tlabel_size = 10\n\tlegend_font_size = 10\n\trc('xtick',labelsize=font_size)\n\trc('ytick',labelsize=font_size)\n\t#\t\n\tfor i in range(0, len(data_dirs)):\n\t\tdd = data_dirs[i]\n\t\tdd.load_data(num)\n\t\tif (lin_or_log):\n\t\t\tx = dd.r/M\n\t\telse:\n\t \t\tx = np.log10(dd.r/M)\n\t\tif log_y:\n\t\t\ty = np.log10(dd.rho*(dd.r/M)**2)\n\t\telse:\n\t\t\ty = dd.rho*(dd.r/M)**2\n\t\tlabel_=\"$l=${:d} $m=${:d}\".format(dd.l_, dd.m_)\n\t\tax1.plot(x, y, colours[i] + \"-\", label=label_, linewidth=1)\n\tif log_y:\n\t\tax1.set_ylabel(\"$\\\\log_{10}((\\\\rho_{2m}/\\\\rho_0)(r^2/M^2))$\", fontsize=label_size)\n\telse:\n\t\tax1.set_ylim((0, 2000))\n\t\tax1.set_ylabel(\"$(\\\\rho_{2m}/\\\\rho_0)(r^2/M^2)$\", fontsize=label_size)\n\tif (lin_or_log):\n\t\txlabel_ = \"$r_{BL}/M$\"\n\telse:\n\t\txlabel_ = \"$\\\\log_{10}(r_{BL}/M)$\"\n\tplt.xlabel(xlabel_, fontsize=label_size)\n\t#a_max = np.max([float(a_str) for a_str in a_list])\n\t#r_plus_min = 1 + np.sqrt(1 - a_max**2)\n\t#print(\"r_plus_min = \", r_plus_min)\n\t#if (lin_or_log) :\n\t#\tplt.xlim((r_plus_min, 100))\n\t#else :\n\t#\tplt.xlim(left=np.log10(r_plus_min))\n\tax1.legend(loc=\"best\", fontsize=legend_font_size, labelspacing=0.1, handletextpad=0.2, borderpad=0.4)\n\tplt.xticks(fontsize=font_size)\n\tplt.yticks(fontsize=font_size)\n\tdd0 = data_dirs[0]\n\ttitle = \"$\\\\rho$ quadrupole profile $M=1,\\\\mu=0.4,\\\\chi=0.7,l=m=1$\" \n\tax1.set_title(title, fontsize=title_font_size)\n\tplt.tight_layout()\n\tif log_y:\n\t\t\tsave_name = \"/home/dc-bamb1/GRChombo/Analysis/plots/IsoKerr_rho_profile_{:s}_Rmax={:d}_n={:d}_quadrupole_log_y.png\".format(scale, R_max, num)\n\telse:\n\t\t\tsave_name = \"/home/dc-bamb1/GRChombo/Analysis/plots/IsoKerr_rho_profile_{:s}_Rmax={:d}_n={:d}_quadrupole.png\".format(scale, R_max, num)\n\tprint(\"saved \" + save_name)\n\tplt.savefig(save_name, transparent=False)\n\tplt.clf()\n\t\nplot_graph()\n","sub_path":"Analysis/scripts/old_scripts/plot_radial_profile_rho_Ylm_quadrupole.py","file_name":"plot_radial_profile_rho_Ylm_quadrupole.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"70591734","text":"from django.shortcuts import render\nfrom .models import *\n\n# Create your views here.\ndef orcamentos_lista(request):\n orcamentos = Orcamento.objects.all()\n return render(request, 'mp_orcamento/orcamentos.html', {'orcamentos': orcamentos})\n\n\ndef orcamentos_estatisticas(request):\n maior_custo = 0\n menor_custo = 999999999999\n orcamento_maior_custo = None\n orcamento_menor_custo = None\n orcamentos = Orcamento.objects.all()\n somatorio_custo_total = 0\n for orcamento in orcamentos:\n somatorio = 0\n for peca in Peca.objects.filter(orcamento=orcamento):\n somatorio += peca.custo_de_producao_ajustado()\n orcamento.custo_total = somatorio * 1.25\n somatorio_custo_total += orcamento.custo_total\n if orcamento.custo_total >= maior_custo:\n orcamento_maior_custo = orcamento\n maior_custo = orcamento.custo_total\n if orcamento.custo_total <= menor_custo:\n orcamento_menor_custo = orcamento\n menor_custo = orcamento.custo_total\n quantidade = Orcamento.objects.count() \n media_custo_total = somatorio_custo_total / quantidade\n return render(request, 'mp_orcamento/estatisticas.html', \n {'quantidade': quantidade, \n 'orcamento_maior_custo': orcamento_maior_custo,\n 'orcamento_menor_custo': orcamento_menor_custo,\n 'media_custo_total': media_custo_total\n })\n\n\ndef orcamentos_clientes(request):\n clientes = Cliente.objects.all().first()\n orcamentos = Orcamento.objects.filter(cliente=clientes)\n return render (request,'mp_orcamento/clientes.html',\n {'clientes': clientes,\n 'orcamentos': orcamentos\n })\n \n\ndef orcamentos_clientes_estatisticas(request):\n clientes = Cliente.objects.all()\n maior_custo = 0\n menor_custo = 999999999999\n orcamento_maior_custo = None\n orcamento_menor_custo = None\n nome_maior = None\n nome_menor = None\n for cliente in clientes:\n somatorio = 0\n for orcamento in Orcamento.objects.filter(cliente=cliente):\n somatorio += orcamento.custo_total()\n orcamento_total = somatorio\n if orcamento_total >= maior_custo:\n orcamento_maior_custo = orcamento_total\n nome_maior = cliente.nome\n maior_custo = orcamento_total\n if orcamento_total <= menor_custo:\n orcamento_menor_custo = orcamento_total\n nome_menor = cliente.nome\n menor_custo = orcamento_total\n quantidade = Cliente.objects.count()\n return render(request, 'mp_orcamento/clientes_estatisticas.html',\n {'quantidade': quantidade,\n 'orcamento_maior_custo': orcamento_maior_custo,\n 'orcamento_menor_custo': orcamento_menor_custo,\n 'nome_maior': nome_maior,\n 'nome_menor': nome_menor\n })\n\n \n","sub_path":"mp_orcamento/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"118147368","text":"from rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom politician.factories import CongressServiceFactory\nfrom politician.services import PoliticianService\nfrom reports.utils import MONTHS\n\n\n@api_view()\ndef get_politician_total_expenses(request, politician_id):\n service = PoliticianService()\n politician = service.get_by_id(politician_id)\n\n total_expenses = 0\n congress_service = CongressServiceFactory(politician.role)\n for expense in congress_service.get_current_year_expenses(politician):\n total_expenses += expense[\"price\"]\n\n return Response({\n \"total\": total_expenses,\n \"total_formatted\": '{:,.2f}'.format(total_expenses)\n .replace(\",\", \"v\")\n .replace(\".\", \",\")\n .replace(\"v\", \".\")\n }, status.HTTP_200_OK)\n\n\n@api_view()\ndef get_politician_expenses_by_year(request, politician_id):\n service = PoliticianService()\n politician = service.get_by_id(politician_id)\n\n report = {\n \"xAxis\": {\n \"categories\": MONTHS\n },\n \"yAxis\": {\n \"min\": 0,\n \"title\": {\n \"text\": \"Gastos em R$\"\n }\n },\n\n \"series\": [{\n \"name\": \"Gastos\",\n \"color\": \"red\",\n \"data\": [0 for i in range(len(MONTHS))]\n }]\n }\n\n congress_service = CongressServiceFactory(politician.role)\n for expense in congress_service.get_current_year_expenses(politician):\n if not expense[\"date\"]:\n continue\n\n expense_month = int(expense[\"date\"].strftime(\"%m\")) - 1\n report[\"series\"][0][\"data\"][expense_month] += expense[\"price\"]\n\n return Response(report)\n\n\n@api_view()\ndef get_proposition_votes(request, proposition_at, proposition_id):\n service = CongressServiceFactory(proposition_at)\n votes, votes_by_party, votes_by_result = service.get_proposition_votes_by_id(\n proposition_id)\n\n reports = {\n \"votes\": votes,\n \"votes_by_party\": votes_by_party,\n \"votes_by_result\": votes_by_result\n }\n\n return Response(reports)\n","sub_path":"reports/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"465439537","text":"\r\nfrom math import *\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.cluster import DBSCAN\r\nfrom sklearn.cluster import SpectralClustering\r\nimport re\r\nfrom itertools import cycle\r\nimport urllib.request as ur\r\nimport requests\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n\"\"\"\r\n特征工程\r\n1.特征提炼\r\n2.聚类+plot图\r\n\"\"\"\r\n\r\n'''\r\n根据 url 提炼出具体的host\r\n'''\r\ndef extractHost(full_link):\r\n regex = '((http|ftp|https|\\s)://)[a-zA-Z\\.0-9]+(?=\\/)'\r\n pattern = re.compile(regex)\r\n match = pattern.match(str(full_link))\r\n if match:\r\n # print(match.group())\r\n return match.group()\r\n return None\r\n\r\n\r\n\r\n'''\r\n根据 url 提炼出具体的请求目标,排除非内部请求,处理资源文件请求\r\n'''\r\ndef extractReqTarget(full_link):\r\n\r\n if \"qunar\" not in str(full_link):\r\n return None\r\n if \"qrt=\" in str(full_link):\r\n return full_link.partition('qrt=')[2]\r\n if \"html.ng\" in str(full_link):\r\n return 'qde'\r\n proto, rest = ur.splittype(full_link)\r\n res, rest = ur.splithost(rest)\r\n return None if not res else res\r\n\r\n\r\n'''\r\n输出 url:count\r\n'''\r\ndef exportUrls(reqUrl_df):\r\n targetFile = open('../data/urls.txt', \"a\",encoding='UTF-8')\r\n reqUrl_df_value_counts = reqUrl_df.value_counts()\r\n data_len = len(reqUrl_df_value_counts.index)\r\n for i in range(data_len):\r\n targetFile.write(str(reqUrl_df_value_counts.index[i])+' '+str(reqUrl_df_value_counts.values[i])+'\\r')\r\n targetFile.close()\r\n\r\n'''\r\n输出文件,上传datav,用于可视化\r\n'''\r\ndef exportHttpCodeNot200(df):\r\n train_data_dropnan_not200 = df[df['httpCode'] != 200 ]\r\n train_data_dropnan_not200['type'] = 1 ##用于指定气泡样式\r\n train_data_dropnan_not200[['lat','lng','httpCode','hf','type']].to_csv(\"../data/httpcodenot200.csv\",index=False)\r\n\r\n\r\ndef drawPlotForDBScan(df):\r\n x = np.array(df[['lat','lng']], dtype=np.float)\r\n per_city = 467.0994 #按边长为467.0994公里对中国切片\r\n # kms_per_radian = 6371.0088\r\n epsilon = 10/ per_city #一直memoryError,网上按比例缩放后可运行\r\n db = DBSCAN(eps=epsilon,min_samples=10, algorithm='ball_tree', metric='haversine').fit(np.radians(x))\r\n labels = db.labels_\r\n unique_labels = set(labels)\r\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\r\n colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')\r\n markers = []\r\n for i in range(n_clusters_):\r\n markers.append('o')\r\n\r\n for k , col , mar in zip(unique_labels , colors , markers):\r\n if k == -1:\r\n col = 'r'\r\n members = (labels == k )\r\n print( x[members, 0],x[members,1])\r\n plt.plot( x[members, 0] , x[members,1] , 'w', markerfacecolor=col, marker='.',markersize=8)\r\n plt.title(u'number of clusters: %d' % n_clusters_)\r\n plt.xlabel('lat')\r\n plt.ylabel('lng')\r\n plt.grid()\r\n plt.show()\r\n\r\n\r\ndef locatebyLatLon(lat, lng, pois=0):\r\n '''\r\n 根据经纬度确定地址\r\n '''\r\n try:\r\n items = {'location': str(lat) + ',' + str(lng), 'ak': 'A9f77664caa0b87520c3708a6750bbdb', 'output': 'json'}\r\n if pois:\r\n items['pois'] = 1\r\n r = requests.get('http://api.map.baidu.com/geocoder/v2/', params=items)\r\n dictResult = r.json()\r\n return dictResult['result'] if not dictResult['status'] else None\r\n except Exception as e:\r\n print(str(e))\r\n return None\r\n\r\n\r\ndef toDateTime(ds):\r\n if '+' not in str(ds):\r\n return None\r\n clean_s = str(ds).split('+')[0]\r\n return pd.to_datetime(clean_s)\r\n\r\ndef getClusterId(dfdd,x):\r\n\r\n for loc_value,cluster_id_value in dfdd[['loc','cluster_id']].values:\r\n if x == loc_value:\r\n return cluster_id_value\r\n return -1\r\n\r\n\r\ndef spectralCluster(df):\r\n df_dropduplicates = df[['lat', 'lng','loc']].drop_duplicates()\r\n x = np.array(df_dropduplicates[['lat', 'lng']], dtype=np.float)\r\n sc = SpectralClustering(n_clusters=30, eigen_solver='arpack',\r\n affinity=\"nearest_neighbors\").fit(np.radians(x))\r\n labels = sc.labels_\r\n # print(labels)\r\n df_dropduplicates['cluster_id'] = labels\r\n df['cluster_id'] = df['loc'].apply(lambda x :getClusterId(df_dropduplicates,x))\r\n print(df[['loc','cluster_id']].values)\r\n\r\n newdf = df.groupby(\"cluster_id\").mean()\r\n cluster_dict = {}\r\n for i, j in newdf.iterrows():\r\n ret = locatebyLatLon(j['lng'], j['lat'])\r\n if ret:\r\n city = ret['addressComponent']['province'] + \",\" + ret['addressComponent']['city']\r\n cluster_dict[i] = city\r\n else:\r\n cluster_dict[i] = None\r\n print (cluster_dict)\r\n return df['cluster_id'].replace(cluster_dict)\r\n\r\n\r\n\r\nif __name__== \"__main__\":\r\n global defaultTrainData\r\n # try:\r\n # for i in range(3,25):\r\n\r\n # url = \"../data/data\"+str(i)+\".txt\" ##数据地址\r\n # print(url)\r\n # defaultTrainData = pd.read_csv(url,sep='$') ##读取文件\r\n # '''\r\n # 占时提取这些特征进行处理,后续可以自己加上, 将none值去除,以后可考虑进行填充\r\n # '''\r\n # train_data_dropnan = defaultTrainData[['loc','httpCode','reqUrl','reqTime','mno','resSize','netType','uid','pid','hf','X-Date']]\r\n\r\n # train_data_dropnan['httpCode'] = train_data_dropnan['httpCode'].fillna(200)\r\n\r\n # train_data_dropnan['hf'] = train_data_dropnan['hf'].apply(lambda x: None if str(x) else \"service_error\")\r\n # train_data_dropnan['hf'] = train_data_dropnan['hf'].dropna()\r\n\r\n\r\n # ##可能反了,但不影响具体训练\r\n # ##lat提取\r\n # train_data_dropnan['lat'] = train_data_dropnan['loc'].apply(lambda x: float(str(x).split(',')[0]) if ',' in str(x) else 0)\r\n # ##lng提取\r\n # train_data_dropnan['lng'] = train_data_dropnan['loc'].apply(lambda x: float(str(x).split(',')[1]) if ',' in str(x) else 0)\r\n # ##host提取\r\n # train_data_dropnan['host'] = train_data_dropnan['reqUrl'].apply(lambda x:extractHost(str(x)))\r\n # ##reqTarget提取\r\n # train_data_dropnan['reqTarget'] = train_data_dropnan['reqUrl'].apply(lambda x:extractReqTarget(str(x)))\r\n\r\n # train_data_dropnan['X-Date'] = train_data_dropnan['X-Date'].apply(lambda x: toDateTime(x))\r\n\r\n # train_data_dropnan['minute'] = train_data_dropnan['X-Date'].apply(lambda x: x.minute)\r\n\r\n # train_data_dropnan.sort(['X-Date'],ascending=True)\r\n\r\n # train_data_dropnan['city'] = None\r\n # for j in range(60):\r\n # print(j)\r\n # train_data_dropnan_permin = train_data_dropnan[train_data_dropnan['minute'] == j];\r\n # loc_data_permin = train_data_dropnan_permin[['loc', 'minute']].dropna()\r\n # loc_data_permin['lat'] = loc_data_permin['loc'].apply(lambda x: float(str(x).split(',')[0]))\r\n # ##lng提取\r\n # loc_data_permin['lng'] = loc_data_permin['loc'].apply(lambda x: float(str(x).split(',')[1]))\r\n # # for k in range(0, loc_data.size, 2000):\r\n # replace_item = spectralCluster(loc_data_permin)\r\n # train_data_dropnan_permin['city'] = replace_item\r\n # print(train_data_dropnan_permin['X-Date'].values)\r\n # file_name = train_data_dropnan_permin['X-Date'].iloc[0].strftime('%y-%m-%d-%H-%M')\r\n # print(file_name)\r\n # train_data_dropnan_permin.to_csv(\"../input/\"+str(file_name)+\".csv\",index=False,sep='$',encoding=\"utf-8\")\r\n\r\n # defaultTrainData = None\r\n # except Exception as e:\r\n # print(str(e)) \r\n url = \"../data/data0.txt\" ##数据地址\r\n print(url)\r\n defaultTrainData = pd.read_csv(url,sep='$') ##读取文件\r\n '''\r\n 占时提取这些特征进行处理,后续可以自己加上, 将none值去除,以后可考虑进行填充\r\n '''\r\n train_data_dropnan = defaultTrainData[['loc','httpCode','reqUrl','reqTime','mno','resSize','netType','uid','pid','hf','X-Date']]\r\n\r\n train_data_dropnan['httpCode'] = train_data_dropnan['httpCode'].fillna(200)\r\n\r\n train_data_dropnan['hf'] = train_data_dropnan['hf'].apply(lambda x: None if str(x) else \"service_error\")\r\n train_data_dropnan['hf'] = train_data_dropnan['hf'].dropna()\r\n\r\n\r\n ##可能反了,但不影响具体训练\r\n ##lat提取\r\n train_data_dropnan['lat'] = train_data_dropnan['loc'].apply(lambda x: float(str(x).split(',')[0]) if ',' in str(x) else 0)\r\n ##lng提取\r\n train_data_dropnan['lng'] = train_data_dropnan['loc'].apply(lambda x: float(str(x).split(',')[1]) if ',' in str(x) else 0)\r\n # ##host提取\r\n # train_data_dropnan['host'] = train_data_dropnan['reqUrl'].apply(lambda x:extractHost(str(x)))\r\n # ##reqTarget提取\r\n # train_data_dropnan['reqTarget'] = train_data_dropnan['reqUrl'].apply(lambda x:extractReqTarget(str(x)))\r\n\r\n # train_data_dropnan['X-Date'] = train_data_dropnan['X-Date'].apply(lambda x: toDateTime(x))\r\n\r\n # train_data_dropnan['minute'] = train_data_dropnan['X-Date'].apply(lambda x: x.minute)\r\n drawPlotForDBScan(train_data_dropnan)\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":"monitor-script/feature_analyze.py","file_name":"feature_analyze.py","file_ext":"py","file_size_in_byte":9352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"46765984","text":"import os\nfrom flask import Flask, request, jsonify\n\nUPLOAD_FOLDER = '/home/pi/context'\n\napp = Flask(__name__)\n\ndef save_reg(regs):\n\twith open(os.path.join(UPLOAD_FOLDER, \"context.txt\"), \"w\") as f:\n\t\tfor reg in regs:\n\t\t\tf.write(str(reg) + '\\n')\n\ndef save_code(code):\n\twith open(os.path.join(UPLOAD_FOLDER, \"instruction.s\"), \"w\") as f:\n\t\tf.write(code)\n\t\n\n@app.route('/', methods=['POST'])\ndef upload_files():\n\tdata = request.get_json()\n\t\n\tregisters = data['registers']\n\tcode = data['code']\n\n\tprint(request)\n\n\tif registers:\n\t\tsave_reg(registers)\n\telse:\n\t\treturn \"You should send context\", 400\n\n\tif code:\n\t\tsave_code(code)\n\telse:\n\t\treturn \"You should send instruction\", 400\n\n\tos.system(\"python3 readContext.py context/instruction.s context/context.txt\")\n\tos.system(\"gcc -o test test.s -mfpu=neon\")\n\n\tos.system(\"./test > response.txt\")\n\n\tout_regs = []\n\n\twith open(\"response.txt\") as f:\n\t\tfor line in f:\n\t\t\tout_regs.append(int(line))\n\n\tf.close()\n\n\tos.system(\"rm -rf test.s\")\n\tos.system(\"rm -rf test\")\n\tos.system(\"rm -rf response.txt\")\n\n\treturn jsonify({\"registers\": out_regs}), 200\n\napp.run(host='0.0.0.0', port=8080)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"497298631","text":"from PIL import Image\nimport numpy as np\n\nimage = Image.open(\"angelBW.jpg\")\n\npixels = np.asarray(image, dtype=np.float32)\na = pixels[:,:,0]\nx, y = a.shape\nprint(a.shape)\nprint(x, y)\nnewImage = []\ngx = 0\ngy = 0\ng = 0\ni = 0\nj= 0\nt = 50\nmatriz = []\nfor i in range(x-3):\n temp_array = []\n for j in range(y-3):\n temp = a[i:(i+3), j:(j+3)]\n gx = temp[1,1] - temp[0,0]\n gy = temp[1,0] - temp[0,1]\n g = (gx**2 + gy**2)**(0.5)\n if g > t:\n temp_array.append(255)\n else:\n temp_array.append(0)\n matriz.append(temp_array)\n\nmatriz = np.asarray(matriz, dtype=np.uint8)\nImage.fromarray(matriz.astype(np.uint8)).save(\"holaR.jpg\")\nimage.close()\n","sub_path":"procesamientoDeImagenes/mascaras/robert.py","file_name":"robert.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"624854077","text":"import numpy as np\n\nR = 2.5\nA = 4*R/70\nN = 15\n\nphi = np.arange(0, 2 * np.pi, 0.01)\nrho = R + A * np.sin(N * phi)\n\nsPnts = []\nfor p, r in zip(phi, rho):\n x = 2 * r * np.cos(p)\n y = r * np.sin(p)\n sPnts += [(x, y, 0)]\n\ns = cq.Workplane(\"XY\").moveTo(sPnts[0][0], sPnts[0][1])\nr = s.spline(sPnts[1:], includeCurrent = True).close()\nresult = r.workplane(offset = 10.0).ellipse(2.5, 1.25).loft(combine=True)","sub_path":"lattice_scripts/wavy_circle.py","file_name":"wavy_circle.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"636937917","text":"#Random으로 오늘의 점심메뉴를 추천해주는 프로그램\nimport random\n\nmenu = ['새마을식당', '초원삼겹살', '멀캠20층', '홍콩반점', '순남시래기']\n\n#dictionary\nphone_book = {\n '새마을식당':'010-2536-2563',\n '초원삼겹살':'010-5987-8359',\n '멀캠20층':'010-3134-1347',\n '홍콩반점':'010-2361-1234',\n '순남시래기':'010-1236-3457'\n} #json파일 형식과 같아보이는데 같은방식일 것 같다\nprint(phone_book['새마을식당'])\nlunch = random.choice(menu);\nprint(lunch);\n\n#해당 식당의 전화번호를 같이 출력\nprint(phone_book[lunch])","sub_path":"VR교육과정특강Python/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"136809164","text":"# By Ben Curnow\n# www.github.com/bencurnow\n# A pool ladder\n\n\nimport datetime\n\n\nladder = {}\nn = 3\ndate = datetime.datetime.now().date()\ntickcross = ['\\u2713', '\\u2717']\n\n\n# Converts a list to a string\ndef liststring(l):\n string = ''\n for i in l:\n string += str(i) + ' '\n return string[:-1]\n\n\n# Prints the ladder to the console\ndef prettyprint(dic):\n for i in dic:\n print(i, dic[i][0], tickcross[int(dic[i][2])])\n\n\n# Opens the ladder.txt file and stores in ladderlist\nwith open(\"ladder.txt\") as file:\n ladderlist = [i[:-1].split() for i in file]\n\n\n# Opens the challenge.txt file and stores in challenges\nwith open(\"challenge.txt\") as file:\n challenges = [(i.split()[0], i.split()[1], i.split()[2]) for i in file]\n\n\n# Opens the challengehist.txt file and stores in challengehist\nwith open(\"challengehist.txt\") as file:\n challengehist = [i for i in file]\n\n\n# Parses data from ladder list to the ladder dictionary\nfor i in ladderlist:\n ladder[int(i[0])] = []\n ladder[int(i[0])].append(liststring([str(k) for k in i[n:]]))\n for k in range(1, n):\n ladder[int(i[0])].append(i[k])\n\n\n# Hunts for a player in the ladder\ndef hunter(player):\n for i in range(1, len(ladder)):\n if ladder[i][0] == player:\n return i\n elif ladder[i][1] == player:\n return i\n\n\n# Swaps 2 people in the ladder\ndef swapentries(p1, p2):\n temp1, temp2 = ladder[p1], ladder[p2]\n ladder[p1], ladder[p2] = temp2, temp1\n\n\n# Promotes a player p1 to position p2\ndef promote(p1, p2):\n for i in range(p1 - p2):\n swapentries(p1 - i, p1 - i - 1)\n\n\n# Removes a challenge from the list\ndef remchallenge(player):\n print(challenges)\n for i in challenges:\n if i[0] == player or i[1] == player:\n ladder[hunter(i[0])][2], ladder[hunter(i[1])][2] = 0, 0\n challenges.remove(i)\n return True\n return False\n\n\n# Allows a result to be placed in the challenge history\ndef resulthandler(p1, result):\n for i in challenges:\n if i[0] == p1 or i[1] == p1:\n challengehist.append(str(i[0]) + ' ' + str(i[1]) + ' ' + str(i[2]) + ' ' + result + '\\n')\n remchallenge(p1)\n\n\n# Checks the challenge keys to update current challenges\ndef updatechallenges():\n for i in challenges:\n ladder[hunter(i[0])][2], ladder[hunter(i[1])][2] = 1, 1\n chaldate = datetime.datetime(int(i[2][:4]), int(i[2][5:7]), int(i[2][8:]))\n if (datetime.datetime.now() - chaldate).days > 3:\n if hunter(i[0]) < hunter(i[1]):\n promote(hunter(i[1]), hunter(i[0]))\n else:\n promote(hunter(i[0]), hunter(i[1]))\n resulthandler(i[0], 'Auto-Resign')\nupdatechallenges()\n\n\n# Allows a player to challenge\ndef challenge(p1, p2):\n if p1 - 3 > p2 or p1 <= p2:\n return False\n elif ladder[p1][2] == 1 or ladder[p2][2] == 1:\n return False\n else:\n challenges.append((ladder[p1][1], ladder[p2][1], str(date)))\n updatechallenges()\n return True\n\n\n# Functionality for challenging\ndef challengehandler(p1, p2):\n if challenge(p1, p2):\n print(\"Challenge successful\")\n else:\n print(\"Challenge unsuccessful\")\n\n\nprettyprint(ladder)\n\n\n# Writes the new ladder to the text document for next use\nwith open(\"newladder.txt\", 'w') as f:\n for i in ladder:\n f.write(str(i) + ' ' + str(ladder[i][1]) + ' ' + str(ladder[i][2]) + ' ' + str(ladder[i][0]) + '\\n')\n\n# Writes the challenges to the text document for next use\nwith open(\"challenge.txt\", 'w') as f:\n for i in challenges:\n f.write(str(i[0]) + ' ' + str(i[1]) + ' ' + str(i[2]) + '\\n')\n\n# Writes the challenge history to the text document for next use\nwith open(\"challengehist.txt\", 'w') as f:\n for i in challengehist:\n f.write(i)\n\n\n","sub_path":"ladder.py","file_name":"ladder.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"442446645","text":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python import debug as tf_debug\nfrom tqdm import *\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numbers\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom Visual import *\nfrom Utils import *\n\nclass UnitAutoencoder:\n \"\"\"\n A single autoencoder which can be either an ordinary or a denoising unit. Denoising autoencoder can be \n specified with Gaussian noises or dropout on the inputs.\n \"\"\"\n def __init__(self,\n name,\n n_inputs,\n n_neurons,\n noise_stddev = None,\n input_dropout_rate = None,\n hidden_dropout_rate = None,\n hidden_activation = tf.nn.softmax,\n output_activation = None,\n n_observable_hidden_neurons = 0,\n regularizer = tf.contrib.layers.l2_regularizer(0.01),\n initializer = tf.contrib.layers.variance_scaling_initializer(), # He initialization\n optimizer = tf.train.AdamOptimizer(0.001),\n tf_log_dir = \"../tf_logs\"):\n \"\"\"\n Ctor\n \n Arguments:\n - name: name of the unit\n - n_inputs: number of inputs; also the number of neurons in the output layer\n - n_neurons: number of neurons in the hidden layer\n - noise_stddev: standard deviation of the Gaussian noise; not used if None\n - dropout_rate: if specified a Dropout layer will be added after the input layer; not used if None\n - regularizer: kernel regularizers for hidden and output layers\n\n Return: None\n \"\"\"\n self.name = name\n self.n_inputs = n_inputs\n self.n_neurons = n_neurons\n self.noise_stddev = noise_stddev\n self.input_dropout_rate = input_dropout_rate\n self.hidden_dropout_rate = hidden_dropout_rate\n self.hidden_activation = hidden_activation\n self.output_activation = output_activation\n self.regularizer = regularizer\n self.initializer = initializer\n self.n_observable_hidden_neurons = 0\n if (n_observable_hidden_neurons > 0):\n if isinstance(n_observable_hidden_neurons, numbers.Integral):\n self.n_observable_hidden_neurons = min(n_observable_hidden_neurons, self.n_neurons)\n elif isinstance(n_observable_hidden_neurons, numbers.Real):\n assert(0.0 <= n_observable_hidden_neurons <= 1.0), \"Invalid ratio\"\n self.n_observable_hidden_neurons = int(n_observable_hidden_neurons * self.n_neurons)\n else:\n raise ValueError(\"Invalid type\")\n self.graph = tf.Graph()\n\n with self.graph.as_default():\n self.X = tf.placeholder(tf.float32, shape=[None, n_inputs], name=\"X\")\n self.training = tf.placeholder_with_default(False, shape=(), name='training')\n if (self.noise_stddev is not None):\n X_noisy = tf.cond(self.training,\n lambda: self.X + tf.random_normal(tf.shape(self.X), stddev = self.noise_stddev),\n lambda: self.X)\n elif (self.input_dropout_rate is not None):\n X_noisy = tf.layers.dropout(self.X, self.input_dropout_rate, training=self.training)\n else:\n X_noisy = self.X\n dense_hidden = tf.layers.dense(X_noisy, n_neurons, activation=hidden_activation, kernel_regularizer = regularizer, name=\"{}_hidden\".format(self.name))\n if self.hidden_dropout_rate is None:\n self.hidden = dense_hidden\n else:\n self.hidden = tf.layers.dropout(dense_hidden, self.hidden_dropout_rate, training=self.training)\n self.outputs = tf.layers.dense(self.hidden, n_inputs, activation=output_activation, kernel_regularizer = regularizer, name=\"{}_outputs\".format(self.name))\n self.reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n self.reconstruction_loss = tf.reduce_mean(tf.square(self.outputs - self.X))\n self.loss = tf.add_n([self.reconstruction_loss] + self.reg_losses)\n self.training_op = optimizer.minimize(self.loss)\n self.init = tf.global_variables_initializer()\n self.saver = tf.train.Saver()\n\n loss_str = \"Reconstruction_and_regularizer loss\" if regularizer else \"Reconstruction_loss\"\n self.loss_summary = tf.summary.scalar(loss_str, self.loss)\n # Ops to observe neurons\n if (self.n_observable_hidden_neurons > 0):\n trainable_vars = dict([(var.name, var) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n hidden_weights = trainable_vars[\"{}_hidden/kernel:0\".format(self.name)]\n assert(hidden_weights.shape == (n_inputs, n_neurons)), \"Invalid hidden weight shape\"\n hidden_biases = trainable_vars[\"{}_hidden/bias:0\".format(self.name)]\n if self.n_observable_hidden_neurons == self.n_neurons:\n # Optimization for corner case to avoid permutation\n neuron_indices = np.arange(self.n_neurons)\n else:\n neuron_indices = list(np.random.permutation(np.arange(n_neurons))[:self.n_observable_hidden_neurons])\n for neuron_idx in neuron_indices:\n self._variable_summaries(hidden_weights[:, neuron_idx], \"weights_hidden_neuron_{}\".format(neuron_idx))\n self._variable_summaries(hidden_biases[neuron_idx], \"bias_hidden_neuron_{}\".format(neuron_idx))\n self._variable_summaries(self.hidden[:, neuron_idx], \"activation_hidden_neuron_{}\".format(neuron_idx))\n \n self.summary = tf.summary.merge_all()\n tf_log_dir = \"{}/{}_run-{}\".format(tf_log_dir, self.name, timestr())\n self.train_file_writer = tf.summary.FileWriter(os.path.join(tf_log_dir, \"train\"), self.graph)\n self.valid_file_writer = tf.summary.FileWriter(os.path.join(tf_log_dir, \"valid\"), self.graph)\n \n # Dictionary of trainable parameters: key = variable name, values are their values (after training or\n # restored from a model)\n self.params = None\n\n # The trainable params with initial values (before traininig or restoration)\n self.initial_params = None\n\n # Stop file: if this file exists, the training will stop\n self.stop_file_path = os.path.join(tf_log_dir, \"stop\")\n \n def _variable_summaries(self, var, tag):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope(tag):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var) \n\n def save_untrained_model(self, model_path, seed = 42):\n with tf.Session(graph=self.graph) as sess:\n tf.set_random_seed(seed)\n self.init.run()\n self.initial_params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n self.saver.save(sess, model_path)\n \n def fit(self, X_train, X_valid, n_epochs, model_path, save_best_only = True, batch_size = 256, checkpoint_steps = 100, seed = 42, tfdebug = False):\n \"\"\"\n Train the unit autoencoder against a training set\n\n Params:\n - X_train: training set of shape (n_samples, n_features)\n - X_valid: validation set\n - n_epochs: number of epochs to train\n - batch_size: batch size\n - checkpoint_steps: number of steps to record checkpoint and logs\n - seed: random seed for tf\n - model_path: model full path file to be saved\n\n \"\"\"\n assert(self.X.shape[1] == X_train.shape[1]), \"Invalid input shape\"\n with tf.Session(graph=self.graph) as sess:\n if tfdebug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n if batch_size is None:\n batch_size = len(X_train)\n tf.set_random_seed(seed)\n self.init.run()\n self.initial_params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n best_loss_on_valid_set = 100000\n model_step = -1\n stop = False\n for epoch in tqdm(range(n_epochs)):\n X_train_indices = np.random.permutation(len(X_train))\n n_batches = len(X_train) // batch_size\n start_idx = 0\n for batch_idx in range(n_batches):\n indices = X_train_indices[start_idx : start_idx + batch_size]\n X_batch = X_train[indices]\n sess.run(self.training_op, feed_dict={self.X: X_batch, self.training: True}) \n step = epoch * n_batches + batch_idx\n if step % checkpoint_steps == 0:\n train_summary = sess.run(self.summary, feed_dict={self.X: X_batch})\n self.train_file_writer.add_summary(train_summary, step)\n loss_on_valid_set, loss_summary_on_valid_set = sess.run([self.loss, self.loss_summary], feed_dict={self.X: X_valid})\n self.valid_file_writer.add_summary(loss_summary_on_valid_set, step)\n model_to_save = (not save_best_only) or (loss_on_valid_set < best_loss_on_valid_set)\n if loss_on_valid_set < best_loss_on_valid_set:\n best_loss_on_valid_set = loss_on_valid_set\n if model_to_save:\n self.saver.save(sess, model_path)\n model_step = step\n # Check if stop signal exists\n if os.path.exists(self.stop_file_path):\n stop = True\n start_idx += batch_size\n if stop:\n print(\"Stopping command detected: {}\".format(self.stop_file_path))\n break\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n self.train_file_writer.close()\n self.valid_file_writer.close()\n assert(model_step >= 0), \"Invalid model step\"\n all_steps = n_epochs * n_batches\n return model_step, all_steps\n \n def hidden_weights(self, file_path = None):\n assert(self.params is not None), \"Invalid self.params\"\n w = self.params[\"{}_hidden/kernel:0\".format(self.name)]\n if file_path is not None:\n W = np.array(w)\n columns = [\"neuron_{}\".format(idx) for idx in range(W.shape[1])]\n df = pd.DataFrame(data=W, columns=columns)\n df.to_csv(file_path)\n return w\n\n def hidden_biases(self, file_path = None):\n assert(self.params is not None), \"Invalid self.params\"\n w = self.params[\"{}_hidden/bias:0\".format(self.name)]\n if file_path is not None:\n W = np.array(w)\n columns = [\"neuron_{}\".format(idx) for idx in range(W.shape[1])]\n df = pd.DataFrame(data=W, columns=columns)\n df.to_csv(file_path)\n return w\n \n def output_weights(self):\n assert(self.params is not None), \"Invalid self.params\"\n return self.params[\"{}_output/kernel:0\".format(self.name)]\n\n def output_biases(self):\n assert(self.params is not None), \"Invalid self.params\"\n return self.params[\"{}_output/bias:0\".format(self.name)]\n \n def restore(self, model_path):\n if self.params is not None:\n print(\">> Warning: self.params not empty and will be replaced\")\n with tf.Session(graph=self.graph) as sess:\n self.saver.restore(sess, model_path)\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n\n def eval(self, X, varlist):\n assert(self.params), \"Invalid self.params\"\n with tf.Session(graph=self.graph) as sess:\n varmap = {\"loss\": self.loss,\n \"reconstruction_loss\": self.reconstruction_loss,\n \"hidden_outputs\": self.hidden,\n \"outputs\": self.outputs}\n vars_to_eval = []\n for var in varlist:\n # The order of var in the list needs to be kept, thus this for-loop\n if var == \"loss\":\n vars_to_eval += [self.loss]\n elif var == \"reconstruction_loss\":\n vars_to_eval += [self.reconstruction_loss]\n elif var == \"hidden_outputs\":\n vars_to_eval += [self.hidden]\n elif var == \"outputs\":\n vars_to_eval += [self.outputs]\n else:\n raise ValueError(\"Unrecognized variable {} to evaluate\".format(var))\n return sess.run(vars_to_eval, feed_dict={self.X: X})\n \n def restore_and_eval(self, X, model_path, varlist, tfdebug = False):\n \"\"\"\n Restore model's params and evaluate variables\n\n Params:\n - model_path: full path to the model file\n - varlist: list of variables to evaluate. Valid values: \"loss\", \"reconstruction_loss\", \"hidden_outputs\", \"outputs\"\n\n Return: a list of evaluated variables\n \"\"\"\n assert(self.graph), \"Invalid graph\"\n with tf.Session(graph=self.graph) as sess:\n self.saver.restore(sess, model_path)\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n if tfdebug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n varmap = {\"loss\": self.loss,\n \"reconstruction_loss\": self.reconstruction_loss,\n \"hidden_outputs\": self.hidden,\n \"outputs\": self.outputs}\n vars_to_eval = []\n for var in varlist:\n # The order of var in the list needs to be kept, thus this for-loop\n if var == \"loss\":\n vars_to_eval += [self.loss]\n elif var == \"reconstruction_loss\":\n vars_to_eval += [self.reconstruction_loss]\n elif var == \"hidden_outputs\":\n vars_to_eval += [self.hidden]\n elif var == \"outputs\":\n vars_to_eval += [self.outputs]\n return sess.run(vars_to_eval, feed_dict={self.X: X})\n\n##################################################################################\n##\n## StackAutoencoders class\n##\n##################################################################################\nclass StackedAutoencoders:\n def __init__(self,\n name,\n cache_dir = \"../cache\",\n tf_log_dir = \"../tf_logs\"):\n self.name = name\n self.stacked_units = []\n self.graph = None\n self.initial_params = None\n self.params = None\n self.cache_dir = cache_dir\n self.tf_log_dir = tf_log_dir\n\n self.X = None\n self.training = None\n self.loss = None\n self.hidden = [] # outputs of all hidden layers\n self.outputs = None # the final output layer\n self.encoders = []\n self.decoders = []\n self.training_op = None\n self.saver = None\n self.loss_summary = None\n self.summary = None\n self.train_file_writer = None \n self.stop_file_path = os.path.join(cache_dir, \"stop\")\n \n def _add_hidden_layer(self, input_tensor, unit, layer_name,\n regularizer,\n input_dropout_rate,\n hidden_dropout_rate):\n assert(unit.params), \"Invalid unit.params\"\n with tf.name_scope(layer_name):\n input_drop = input_tensor if input_dropout_rate is None else tf.layers.dropout(input_tensor, rate=input_dropout_rate, training=self.training)\n weights = tf.Variable(unit.hidden_weights(), name = \"weights\")\n assert(weights.shape == (unit.n_inputs, unit.n_neurons)), \"Wrong assumption about weight's shape\"\n biases = tf.Variable(unit.hidden_biases(), name = \"biases\")\n assert(biases.shape == (unit.n_neurons,)), \"Wrong assumption about bias's shape\"\n pre_activations = tf.matmul(input_drop, weights) + biases\n if unit.hidden_activation is not None:\n hidden_outputs = unit.hidden_activation(pre_activations, name = \"hidden_outputs\")\n else:\n hidden_outputs = pre_activations\n hidden_drop = hidden_outputs if hidden_dropout_rate is None else tf.layers.dropout(hidden_outputs, rate=hidden_dropout_rate, training=self.training)\n reg_loss = regularizer(weights) if regularizer else None\n return hidden_drop, reg_loss\n\n def _add_output_layer(self, input_tensor, unit, layer_name,\n regularizer,\n input_dropout_rate,\n output_dropout_rate):\n assert(unit.params), \"Invalid unit.params\"\n with tf.name_scope(layer_name):\n input_drop = input_tensor if input_dropout_rate is None else tf.layers.dropout(input_tensor, rate=input_dropout_rate, training=self.training)\n weights = tf.Variable(unit.output_weights(), name = \"weights\")\n assert(weights.shape == (unit.n_inputs, unit.n_neurons)), \"Wrong assumption about weight's shape\"\n biases = tf.Variable(unit.output_biases(), name = \"biases\")\n assert(biases.shape == (unit.n_neurons,)), \"Wrong assumption about bias's shape\"\n pre_activations = tf.matmul(input_drop, weights) + biases\n if unit.output_activation is not None:\n outputs = unit.output_activation(pre_activations, name = \"hidden_outputs\")\n else:\n outputs = pre_activations\n outputs_drop = outputs if output_dropout_rate is None else tf.layers.dropout(outputs, rate=output_dropout_rate, training=self.training)\n reg_loss = regularizer(weights) if regularizer else None\n return outputs_drop, reg_loss\n \n def stack_encoder(self, unit, layer_name,\n regularizer = None,\n input_dropout_rate = 0,\n hidden_dropout_rate = 0):\n self.graph = tf.Graph() if self.graph is None else self.graph\n with self.graph.as_default():\n intput_tensor = None\n if not self.hidden: # empty hidden layers\n self.X = tf.placeholder(tf.float32, shape=(None, unit.n_inputs), name=\"X\")\n self.y = tf.placeholder(tf.int64, shape=(None), name=\"y\")\n self.training = tf.placeholder_with_default(False, shape=(), name=\"training\")\n input_tensor = self.X\n else:\n input_tensor = self.hidden[-1]\n hidden, reg_loss = self._add_hidden_layer(input_tensor, unit, layer_name,\n regularizer, input_dropout_rate, hidden_dropout_rate)\n self.hidden += [hidden]\n self.encoders += [hidden]\n self.stacked_units += [unit]\n if reg_loss is not None:\n self.loss = tf.add_n([self.loss, reg_loss]) if self.loss is not None else reg_loss\n\n def stack_decoder(self, unit, layer_name,\n is_reconstruction_layer = False,\n regularizer = None,\n input_dropout_rate = 0,\n output_dropout_rate = 0):\n self.graph = tf.Graph() if self.graph is None else self.graph\n with self.graph.as_default():\n assert(self.hidden), \"Empty encoder layers\"\n input_tensor = self.hidden[-1]\n outputs, reg_loss = self._add_output_layer(input_tensor, unit, layer_name,\n regularizer, input_dropout_rate, output_dropout_rate)\n if reg_loss is not None:\n self.loss = tf.add_n([self.loss, reg_loss]) if self.loss is not None else reg_loss\n if is_reconstruction_layer:\n self.outputs = outputs\n reconstruction_loss = tf.reduce_mean(tf.square(self.outputs - self.X))\n self.loss = tf.add_n([self.loss, reconstruction_loss]) if self.loss is not None else reconstruction_loss\n else:\n self.hidden += [outputs]\n self.decoders += [outputs]\n \n def stack_softmax_output_layer(self,\n layer_name,\n kernel_regularizer = None,\n kernel_initializer = tf.contrib.layers.variance_scaling_initializer(),\n bias_initializer = tf.zeros_initializer()):\n assert(self.hidden), \"Empty hidden layers\"\n assert(self.graph), \"Empty graph\"\n with self.graph.as_default():\n with tf.variable_scope(layer_name):\n weights = tf.get_variable(name=\"weights\",\n shape=(self.hidden[-1].shape[1], self.X.shape[1]),\n initializer=kernel_initializer)\n biases = tf.get_variable(name=\"biases\",\n shape=(self.X.shape[1], ),\n initializer=bias_initializer)\n self.outputs = tf.matmul(self.hidden[-1], weights) + biases\n with tf.variable_scope(\"loss\"):\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.y, logits=self.outputs)\n entropy_loss = tf.reduce_mean(cross_entropy, name=\"entropy_loss\")\n self.loss = tf.add_n([self.loss, entropy_loss]) if self.loss is not None else entropy_loss\n self.loss = tf.add_n([self.loss, kernel_regularizer(weights)]) if kernel_regularizer is not None else self.loss\n \n def finalize(self, optimizer):\n assert(self.graph), \"Empty graph\"\n with self.graph.as_default():\n with tf.variable_scope(\"training\"):\n self.training_op = optimizer.minimize(self.loss)\n with tf.variable_scope(\"testing\"):\n self.correct = tf.nn.in_top_k(self.outputs, self.y, 1)\n self.accuracy = tf.reduce_mean(tf.cast(self.correct, tf.float32))\n with tf.variable_scope(\"summary\"):\n self.loss_summary = tf.summary.scalar(\"Loss\", self.loss)\n self.summary = tf.summary.merge_all()\n tf_log_dir = \"{}/{}_run-{}\".format(self.tf_log_dir, self.name, timestr())\n self.train_file_writer = tf.summary.FileWriter(os.path.join(tf_log_dir, \"train\"), self.graph)\n self.valid_file_writer = tf.summary.FileWriter(os.path.join(tf_log_dir, \"valid\"), self.graph)\n with tf.variable_scope(\"global_initializer\"):\n self.init = tf.global_variables_initializer()\n with tf.variable_scope(\"saver\"):\n self.saver = tf.train.Saver()\n\n def save(self, model_path):\n with tf.Session(graph=self.graph) as sess:\n self.init.run()\n self.saver.save(sess, model_path)\n\n def restore(self, model_path):\n \"\"\"\n Restore model's params\n \"\"\"\n assert(self.graph), \"Invalid graph\"\n with tf.Session(graph=self.graph) as sess:\n self.saver.restore(sess, model_path)\n self.initial_params = {}\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n \n def fit(self, X_train, X_valid, y_train, y_valid, model_path, save_best_only = True, n_epochs = 1000, batch_size = 256, checkpoint_steps = 100, seed = 42, tfdebug = False):\n assert(self.training_op is not None), \"Invalid self.training_op\"\n assert(self.X.shape[1] == X_train.shape[1]), \"Invalid input shape\"\n with tf.Session(graph=self.graph) as sess:\n if tfdebug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n if batch_size is None:\n batch_size = len(X_train)\n tf.set_random_seed(seed)\n self.init.run()\n self.initial_params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n best_loss_on_valid_set = 100000\n model_step = -1\n stop = False\n for epoch in tqdm(range(n_epochs)):\n X_train_indices = np.random.permutation(len(X_train))\n n_batches = len(X_train) // batch_size\n start_idx = 0\n for batch_idx in range(n_batches):\n indices = X_train_indices[start_idx : start_idx + batch_size]\n X_batch = X_train[indices]\n y_batch = y_train[indices]\n sess.run(self.training_op, feed_dict={self.X: X_batch, self.y: y_batch, self.training: True}) \n step = epoch * n_batches + batch_idx\n if step % checkpoint_steps == 0:\n train_summary = sess.run(self.summary, feed_dict={self.X: X_batch, self.y: y_batch})\n self.train_file_writer.add_summary(train_summary, step)\n loss_on_valid_set, loss_summary_on_valid_set = sess.run([self.loss, self.loss_summary],\n feed_dict={self.X: X_valid, self.y: y_valid})\n self.valid_file_writer.add_summary(loss_summary_on_valid_set, step)\n model_to_save = (not save_best_only) or (loss_on_valid_set < best_loss_on_valid_set)\n if loss_on_valid_set < best_loss_on_valid_set:\n best_loss_on_valid_set = loss_on_valid_set\n if model_to_save:\n self.saver.save(sess, model_path)\n model_step = step\n if os.path.exists(self.stop_file_path):\n stop = True\n start_idx += batch_size\n if stop:\n print(\"Stopping command detected: {}\".format(self.stop_file_path))\n break\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n self.train_file_writer.close()\n self.valid_file_writer.close()\n assert(model_step >= 0), \"Invalid model step\"\n all_steps = n_epochs * n_batches\n return model_step, all_steps\n\n def restore_and_eval(self, model_path, X, y = None, varlist = [], tfdebug = False):\n \"\"\"\n Restore model's params and evaluate variables\n\n Arguments:\n - X: the input to be fed into the network\n - varlist: list of variables to evaluate. Valid values: \"loss\", \"reconstruction_loss\", \"hidden_outputs\", \"outputs\"\n\n Return: a list of evaluated variables\n\n TODO: extend X to also accept a list of inputs; useful when evaluate with training and test sets so that \n the network needs to be restored once\n \"\"\"\n assert(self.graph), \"Invalid graph\"\n with tf.Session(graph=self.graph) as sess:\n self.saver.restore(sess, model_path)\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n if tfdebug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n if not varlist:\n return []\n assert(X is not None), \"Invalid input samples\"\n varmap = {\"loss\": self.loss,\n \"hidden_outputs\": self.hidden[-1],\n \"outputs\": self.outputs,\n \"accuracy\": self.accuracy}\n vars_to_eval = []\n for var in varlist:\n # The order of var in the list needs to be kept, thus this for-loop\n if var == \"loss\":\n vars_to_eval += [self.loss]\n elif var == \"codings\":\n vars_to_eval += [self.encoders[-1]]\n elif var == \"outputs\":\n vars_to_eval += [self.outputs]\n elif var == \"accuracy\":\n assert(len(X) == len(y)), \"Invalid examples and targets sizes\"\n vars_to_eval += [self.accuracy]\n y = np.zeros((len(X), 1)) if y is None else y\n return sess.run(vars_to_eval, feed_dict={self.X: X, self.y: y})\n \n def get_codings(self, model_path, X, file_path = None):\n \"\"\"\n Compute the codings of an input by the network\n\n Arguments:\n - X: the input to be fed into the network with shape (n_examples, n_features)\n - file_path (optional): path to a csv file for storing the resulting codings\n\n Return: the codings of X with shape (n_examples, n_new_features)\n \"\"\"\n [X_codings] = self.restore_and_eval(model_path, X, varlist=[\"codings\"])\n assert(X.shape[0] == X_codings.shape[0]), \"Invalid number of rows in the codings\"\n if file_path is not None:\n columns = [\"f_{}\".format(idx) for idx in range(X_codings.shape[1])]\n df = pd.DataFrame(data=X_codings, columns=columns)\n df.to_csv(file_path)\n return X_codings\n\n \n##################################################################################\n##\n## StackBuilder class\n##\n##################################################################################\nclass StackBuilder:\n \"\"\"\n Utility class to build a stacked autoencoder with predefined specification\n \"\"\"\n def __init__(self,\n name,\n preceding_units = [],\n preceding_unit_model_paths = [],\n n_neurons_per_layer = [],\n unit_regularizer = [],\n unit_noise_stddev = [],\n unit_input_dropout_rate = [],\n unit_hidden_dropout_rate = [],\n stack_regularizer=None,\n stack_input_dropout_rate = 0,\n stack_hidden_dropout_rate = [],\n unit_hidden_activations = tf.nn.softmax, # of hidden layers\n unit_output_activations = None, # of hidden layers\n output_activation = tf.nn.softmax, # of output layer\n output_kernel_regularizer = None,\n output_kernel_initializer = tf.contrib.layers.variance_scaling_initializer(),\n output_bias_initializer = tf.zeros_initializer(),\n adam_lr = 5*1e-6,\n cache_dir = \"../cache\",\n tf_log_dir = \"../tf_logs\"):\n \"\"\"\n Ctor\n \n Arguments:\n - name: name of the stack\n - preceding_units: units that have been trained and will be reused\n - preceding_units_model_path: paths to model file of preceding units\n - n_neurons_per_layer: array of number of hidden neurons after the reused units\n - noise_stddev: array of noise_stddev to be used for new units after the reused ones\n - dropout_rate: similar to noise_stddev array\n\n \"\"\"\n self.name = name\n self.preceding_units = preceding_units\n self.preceding_unit_model_paths = preceding_unit_model_paths # for reuse trained unit autoencoders\n assert(len(self.preceding_units) == len(self.preceding_unit_model_paths)), \"Invalid preceding units\"\n self.n_neurons_per_layer = n_neurons_per_layer\n self.unit_regularizer = unit_regularizer\n self.unit_noise_stddev = unit_noise_stddev\n self.unit_input_dropout_rate = unit_input_dropout_rate\n self.unit_hidden_dropout_rate = unit_hidden_dropout_rate\n self.n_hidden_layers = len(self.n_neurons_per_layer) + len(self.preceding_units)\n if self.n_hidden_layers <= 0:\n raise ValueError(\"Stack cannot be created empty\")\n assert(len(self.unit_regularizer) == len(self.n_neurons_per_layer)), \"Invalid noise_stddev array\"\n assert(len(self.unit_noise_stddev) == len(self.n_neurons_per_layer)), \"Invalid noise_stddev array\"\n assert(len(self.unit_input_dropout_rate) == len(self.n_neurons_per_layer)), \"Invalid input dropout rate array\"\n assert(len(self.unit_hidden_dropout_rate) == len(self.n_neurons_per_layer)), \"Invalid hidden dropout rate array\"\n self.stack_regularizer=stack_regularizer\n self.stack_input_dropout_rate = stack_input_dropout_rate\n self.stack_hidden_dropout_rate = stack_hidden_dropout_rate\n assert(len(self.stack_hidden_dropout_rate) <= self.n_hidden_layers), \"Invalid hidden dropout rate\" \n self.unit_model_paths = [None] * self.n_hidden_layers\n self.units = [None] * self.n_hidden_layers\n self.unit_hidden_activations = unit_hidden_activations\n self.unit_output_activations = unit_output_activations\n self.output_activation = output_activation\n self.output_kernel_regularizer = output_kernel_regularizer\n self.output_kernel_initializer = output_kernel_initializer\n self.output_bias_initializer = output_bias_initializer\n self.adam_lr = adam_lr \n self.cache_dir = cache_dir\n self.tf_log_dir = tf_log_dir\n self.stack_cache_dir = os.path.join(self.cache_dir, \"stack\")\n self.stack_tf_log_dir = os.path.join(self.tf_log_dir, \"stack\")\n self.stack_model_path = os.path.join(self.stack_cache_dir, self.name) + \".model\"\n self.stack = None\n\n def _save_X(self, X, file_path):\n columns = [\"f_{}\".format(idx) for idx in range(X.shape[1])]\n df = pd.DataFrame(data=X, columns=columns)\n df.to_csv(file_path)\n\n def get_stack(self):\n return self.stack\n\n def get_units_and_model_paths(self):\n return self.units, self.unit_model_paths\n \n def build_pretrained_stack(self,\n X_train,\n X_valid,\n y_train,\n ordinary_stack = False,\n n_observable_hidden_neurons_per_layer = 0,\n n_hidden_neurons_to_plot = 20,\n n_reconstructed_examples_per_class_to_plot = 20,\n n_epochs = 10000,\n batch_size = 64,\n checkpoint_steps = 1000,\n pretrained_weight_initialization = True,\n restore_stack_model = True,\n seed = 42):\n assert(X_train.shape[1] == X_valid.shape[1]), \"Invalid input shapes\"\n units = []\n X_train_current = X_train\n X_valid_current = X_valid\n rows = {}\n for hidden_layer in range(self.n_hidden_layers):\n unit_name = \"Unit_{}\".format(hidden_layer)\n unit_cache_dir = os.path.join(self.cache_dir, unit_name)\n if not os.path.exists(unit_cache_dir):\n os.makedirs(unit_cache_dir)\n unit_tf_log_dir = os.path.join(self.tf_log_dir, unit_name)\n if not os.path.exists(unit_tf_log_dir):\n os.makedirs(unit_tf_log_dir)\n n_inputs = X_train_current.shape[1]\n is_preceding_unit = hidden_layer < len(self.preceding_units)\n n_neurons = self.preceding_units[hidden_layer].n_neurons if is_preceding_unit else self.n_neurons_per_layer[hidden_layer - len(self.preceding_units)]\n regularizer = self.preceding_units[hidden_layer].regularizer if is_preceding_unit else self.unit_regularizer[hidden_layer - len(self.preceding_units)]\n noise_stddev = self.preceding_units[hidden_layer].noise_stddev if is_preceding_unit else self.unit_noise_stddev[hidden_layer - len(self.preceding_units)]\n input_dropout_rate = self.preceding_units[hidden_layer].input_dropout_rate if is_preceding_unit else self.unit_input_dropout_rate[hidden_layer - len(self.preceding_units)]\n hidden_dropout_rate = self.preceding_units[hidden_layer].hidden_dropout_rate if is_preceding_unit else self.unit_hidden_dropout_rate[hidden_layer - len(self.preceding_units)]\n unit = UnitAutoencoder(unit_name,\n n_inputs,\n n_neurons,\n regularizer=regularizer,\n noise_stddev=noise_stddev,\n input_dropout_rate=input_dropout_rate,\n hidden_dropout_rate=hidden_dropout_rate,\n hidden_activation = self.unit_hidden_activations,\n output_activation = self.unit_output_activations,\n n_observable_hidden_neurons = n_observable_hidden_neurons_per_layer,\n optimizer = tf.train.AdamOptimizer(self.adam_lr),\n tf_log_dir = unit_tf_log_dir)\n \n # Try to reuse trained model if specified\n unit_model_path = self.preceding_unit_model_paths[hidden_layer] if hidden_layer < len(self.preceding_units) else os.path.join(unit_cache_dir, \"{}.model\".format(unit_name))\n if not os.path.exists(\"{}.meta\".format(unit_model_path)):\n if pretrained_weight_initialization:\n print(\"Training {} for hidden layer {}...\\n\".format(unit_name, hidden_layer))\n model_step, all_steps = unit.fit(X_train_current,\n X_valid_current,\n n_epochs=n_epochs,\n model_path=unit_model_path,\n batch_size=batch_size,\n checkpoint_steps=checkpoint_steps,\n seed=seed)\n print(\">> Done\\n\")\n print(\">> Best model saved at step {} out of {} total steps\\n\".format(model_step, all_steps))\n else:\n print(\"Randomly initialized weights and save model to {}...\\n\".format(unit_model_path))\n unit.save_untrained_model(model_path=unit_model_path, seed=seed)\n model_step, all_steps = (0, 0)\n print(\">> Done\\n\")\n print(\"Plotting reconstructed outputs of unit at hidden layer {}...\\n\".format(hidden_layer))\n unit_plot_dir = os.path.join(unit_cache_dir, \"plots\")\n [X_recon] = unit.restore_and_eval(X_train_current, unit_model_path, [\"outputs\"])\n assert(X_recon.shape == X_train_current.shape), \"Invalid output shape\"\n unit_reconstructed_dir = os.path.join(unit_plot_dir, \"reconstructed\")\n plot_reconstructed_outputs(X_train_current, y_train, X_recon, size_per_class=n_reconstructed_examples_per_class_to_plot,\n plot_dir_path=unit_reconstructed_dir, seed=seed+10)\n print(\">> Done\\n\")\n print(\"Plotting hidden weights of unit at hidden layer {}...\\n\".format(hidden_layer))\n hidden_weights = unit.hidden_weights()\n unit_hidden_weights_dir = os.path.join(unit_plot_dir, \"hidden_weights\")\n plot_hidden_weights(hidden_weights, n_hidden_neurons_to_plot, unit_hidden_weights_dir, seed =seed+20)\n print(\">> Done\\n\")\n else:\n print(\"Reloading model {} of {} for hidden layer {}...\\n\".format(unit_model_path, unit_name, hidden_layer))\n unit.restore(unit_model_path)\n model_step, all_steps = 0, 0\n print(\">> Done\\n\")\n self.unit_model_paths[hidden_layer] = unit_model_path # This can be passed to subsequent stack built upon this one\n self.units[hidden_layer] = unit\n self._save_X(X_train_current, os.path.join(unit_cache_dir, \"X_train_layer_{}.csv\".format(hidden_layer)))\n self._save_X(X_valid_current, os.path.join(unit_cache_dir, \"X_valid_layer_{}.csv\".format(hidden_layer)))\n [train_reconstruction_loss, X_train_current] = unit.restore_and_eval(X_train_current, unit_model_path, [\"reconstruction_loss\", \"hidden_outputs\"])\n [valid_reconstruction_loss, X_valid_current] = unit.restore_and_eval(X_valid_current, unit_model_path, [\"reconstruction_loss\", \"hidden_outputs\"])\n rows[hidden_layer] = [train_reconstruction_loss, valid_reconstruction_loss, model_step, all_steps, unit_model_path]\n \n print(\"Stacking up pretrained units...\\n\")\n self.stack = StackedAutoencoders(name=self.name, cache_dir=self.stack_cache_dir, tf_log_dir=self.stack_tf_log_dir)\n if (not ordinary_stack):\n stack_hidden_layer_names = [\"{}_hidden_{}\".format(self.name, str(idx)) for idx in range(len(self.units))]\n for idx, unit in enumerate(self.units):\n stack_input_dropout_rate = self.stack_input_dropout_rate if idx == 0 else 0\n stack_hidden_dropout_rate = self.stack_hidden_dropout_rate[idx] if idx < len(self.stack_hidden_dropout_rate) else 0\n stack_regularizer = self.stack_regularizer\n self.stack.stack_encoder(unit, stack_hidden_layer_names[idx],\n regularizer=stack_regularizer,\n input_dropout_rate=stack_input_dropout_rate,\n hidden_dropout_rate=stack_hidden_dropout_rate)\n self.stack.stack_softmax_output_layer(layer_name=\"{}_softmax_outputs\".format(self.name),\n kernel_regularizer=self.output_kernel_regularizer,\n kernel_initializer=self.output_kernel_initializer,\n bias_initializer=self.output_bias_initializer)\n else:\n assert(False), \"Not implemented\"\n stack_encoder_layer_names = [\"{}_encoder_{}\".format(self.name, str(idx)) for idx in range(len(self.units))]\n for idx, unit in enumerate(self.units):\n self.stack.stack_encoder(unit, stack_encoder_layer_names[idx])\n stack_decoder_layer_names = [\"{}_decoder_{}\".format(self.name, str(idx)) for idx in range(len(self.units))]\n for idx, unit in enumerate(reversed(self.units)):\n is_reconstruction_layer = (idx == len(self.units) - 1)\n self.stack.stack_decoder(unit, stack_decoder_layer_names[idx], is_reconstruction_layer=is_reconstruction_layer)\n self.stack.finalize(optimizer=tf.train.AdamOptimizer(self.adam_lr))\n print(\">> Done\\n\")\n if (not restore_stack_model):\n print(\"Saving stack model to {}...\\n\".format(self.stack_model_path))\n self.stack.save(self.stack_model_path)\n print(\">> Done\\n\")\n else:\n assert(os.path.exists(\"{}.meta\".format(self.stack_model_path))), \"Stack model path not found\"\n print(\"Restoring stack model from {}...\\n\".format(self.stack_model_path))\n self.stack.restore(self.stack_model_path)\n print(\">> Done\\n\")\n \n result_file_path = os.path.join(self.stack_cache_dir, \"hidden_layer_units.csv\")\n print(\"Saving results of building hidden layer units to {}...\\n\".format(result_file_path))\n columns = [\"train_reconstruction_loss\", \"valid_reconstruction_loss\", \"step_of_best_model\", \"all_steps\", \"unit_model_path\"]\n df = pd.DataFrame.from_dict(rows, orient=\"index\")\n df.index.name = \"hidden_layer\"\n df.columns = columns\n df.sort_index(inplace=True)\n df.to_csv(result_file_path)\n print(\">> Done\\n\")\n \n \n##################################################################################\n##\n## Supporting functions\n##\n##################################################################################\ndef generate_unit_autoencoders(X_train,\n X_valid,\n y_train,\n y_valid,\n scaler,\n n_neurons_range,\n n_folds = 10,\n noise_stddev = None,\n dropout_rate = None,\n hidden_activation = tf.nn.softmax,\n output_activation = None,\n regularizer_value = None,\n initializer = tf.contrib.layers.variance_scaling_initializer(),\n optimizer = tf.train.AdamOptimizer(0.001),\n n_epochs = 5000,\n batch_size = 256,\n checkpoint_steps = 100,\n n_observable_hidden_neurons = 1.0,\n n_hidden_neurons_to_plot = 1.0,\n n_reconstructed_examples_per_class_to_plot = 20,\n seed = 0, \n cache_dir = \"../cache\",\n tf_log_dir = \"../tf_logs\"):\n n_inputs = X_train.shape[1]\n if not os.path.exists(cache_dir):\n os.makedirs(cache_dir)\n if noise_stddev is not None:\n prefix = \"denoise\"\n elif dropout_rate is not None:\n prefix = \"dropout\"\n else:\n prefix = \"ordinary\"\n all_run_rows = {}\n all_run_idx = 0\n avg_recon_loss_rows = {}\n all_indices = list(np.random.permutation(len(X_train)))\n fold_sz = len(all_indices) // n_folds\n for n_neurons in n_neurons_range:\n avg_recon_loss = 0\n for fold_idx in range(n_folds):\n unit_name = config_str(prefix,\n n_epochs=n_epochs,\n n_inputs=n_inputs,\n n_neurons=n_neurons,\n hidden_activation=hidden_activation,\n regularizer_value=regularizer_value,\n noise_stddev=noise_stddev,\n dropout_rate=dropout_rate)\n unit_name += \"_fold{}\".format(fold_idx)\n print(\"\\n\\n*** Constructing and training unit {}, fold {}/{} ***\".format(unit_name, fold_idx+1, n_folds))\n unit_cache_dir = os.path.join(cache_dir, unit_name)\n if not os.path.exists(unit_cache_dir):\n os.makedirs(unit_cache_dir)\n unit_tf_log_dir = tf_log_dir\n if not os.path.exists(unit_tf_log_dir):\n os.makedirs(unit_tf_log_dir)\n unit_regularizer = tf.contrib.layers.l2_regularizer(regularizer_value) if regularizer_value is not None else None\n unit = UnitAutoencoder(unit_name,\n n_inputs,\n n_neurons,\n n_observable_hidden_neurons=n_observable_hidden_neurons,\n noise_stddev=noise_stddev,\n dropout_rate=dropout_rate,\n hidden_activation=hidden_activation,\n output_activation=output_activation,\n regularizer=unit_regularizer,\n initializer=initializer,\n optimizer=optimizer, \n tf_log_dir=unit_tf_log_dir)\n unit_model_path = os.path.join(unit_cache_dir, \"{}.model\".format(unit_name))\n fold_start_idx = int(fold_idx * fold_sz)\n fold_end_idx = min(fold_start_idx + fold_sz, len(all_indices))\n if fold_end_idx - fold_start_idx == len(all_indices):\n X_train_indices = range(len(all_indices))\n else:\n X_train_indices = all_indices[:fold_start_idx] + all_indices[fold_end_idx:]\n X_train_scaled = scaler.fit_transform(X_train[X_train_indices])\n X_valid_scaled = scaler.transform(X_valid)\n model_step = unit.fit(X_train_scaled,\n X_valid_scaled,\n n_epochs=n_epochs,\n model_path=unit_model_path,\n batch_size=batch_size,\n checkpoint_steps=checkpoint_steps,\n seed=seed)\n print(\"\\n>> Model {} saved at step {}\\n\".format(unit_model_path, model_step))\n [reconstruction_loss, outputs] = unit.restore_and_eval(X_train_scaled, unit_model_path, [\"reconstruction_loss\", \"outputs\"])\n all_run_row = [n_neurons, fold_idx, reconstruction_loss, unit_name]\n all_run_rows[all_run_idx] = all_run_row\n all_run_idx += 1\n assert(outputs.shape == X_train_scaled.shape), \"Invalid output shape\"\n unit_plot_dir = os.path.join(unit_cache_dir, \"plots\")\n unit_reconstructed_dir = os.path.join(unit_plot_dir, \"reconstructed\")\n X_recon = scaler.inverse_transform(outputs)\n plot_reconstructed_outputs(X_train[X_train_indices], y_train[X_train_indices], X_recon, size_per_class=n_reconstructed_examples_per_class_to_plot,\n plot_dir_path=unit_reconstructed_dir, seed=seed+10)\n hidden_weights = unit.hidden_weights()\n unit_hidden_weights_dir = os.path.join(unit_plot_dir, \"hidden_weights\")\n plot_hidden_weights(hidden_weights, n_hidden_neurons_to_plot, unit_hidden_weights_dir, seed =seed+20)\n\n # Cross validation on the remaining examples\n X_remaining_indices = all_indices[fold_start_idx:fold_end_idx]\n X_remaining_scaled = scaler.transform(X_train[X_remaining_indices])\n [valid_reconstruction_loss] = unit.restore_and_eval(X_remaining_scaled, unit_model_path, [\"reconstruction_loss\"])\n avg_recon_loss += valid_reconstruction_loss\n avg_recon_loss /= n_folds\n avg_recon_loss_rows[n_neurons] = [avg_recon_loss]\n \n columns = [\"n_neurons\", \"fold_idx\", \"reconstruction_loss\", \"model_name\"]\n all_runs_df = pd.DataFrame.from_dict(all_run_rows, orient=\"index\")\n all_runs_df.index.name = \"Idx\"\n all_runs_df.columns = columns\n result_file_path = os.path.join(cache_dir, \"results_all_runs.csv\")\n if os.path.exists(result_file_path):\n existing_df = pd.DataFrame.from_csv(result_file_path, index_col = 0)\n all_runs_df = all_runs_df.append(existing_df)\n all_runs_df.sort_index(inplace=True)\n all_runs_df.to_csv(result_file_path)\n\n columns = [\"reconstruction_loss\"]\n avg_df = pd.DataFrame.from_dict(avg_recon_loss_rows, orient=\"index\")\n avg_df.index.name = \"n_neurons\"\n avg_df.columns = columns\n result_file_path = os.path.join(cache_dir, \"results_avg.csv\")\n if os.path.exists(result_file_path):\n existing_df = pd.DataFrame.from_csv(result_file_path, index_col = 0)\n avg_df = avg_df.append(existing_df)\n avg_df.sort_index(inplace=True)\n avg_df.to_csv(result_file_path)\n \n","sub_path":"report_submit/StackedAutoencoders.py","file_name":"StackedAutoencoders.py","file_ext":"py","file_size_in_byte":52251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"555185082","text":"#!/usr/bin/env python\n#Monday, January 2 2017\n# Code for parsing raw data (raw_responses_2016.csv) to gexf file\n\nimport json\nimport random\n\n\nmyfile = open('data.txt', 'r')\nlines = myfile.readlines()\nmyfile.close()\n\nnodes = []\nedges = []\nindexDict = {}\n#use this to keep track of matches that have already occured \nmatchesEntered = {}\nfor nodeIndex, line in enumerate(lines):\t\n\t# unpack values\n\tline = line.strip('\\n')\n\tsplits = line.split(':')\n\tId = splits[0]\n\tyear = splits[1]\n\thouse = splits[2]\n\tgender = splits[3] \n\tinterestedIn = splits[4] #gender\n\t# create dictionary\n\tnode_dict = {'Id' : Id, 'Year' : year, 'House' : house, 'Gender' : gender, 'Interest' : interestedIn}\n\t# Add dictionary to list\n\tnodes.append(node_dict)\n\tmatches = splits[5:len(splits)]\n\t# keep track of the node's index\n\tindexDict[Id] = {}\n\tindexDict[Id]['matches'] = matches\n\tindexDict[Id]['index'] = nodeIndex\n\t# create an array to hold all the connections that have been added\n\tmatchesEntered[Id] = []\n\n\n\n### MAKE SPOOF DICTIONARY\nspoofDict = dict()\noptions = set(indexDict.keys())\nfor key in indexDict:\n\tspoofId = key\n\twhile(spoofId == key):\n\t\tspoofId = random.sample(options, 1)[0]\n\t\tif (len(options) == 1):\n\t\t\tbreak\n\toptions.remove(spoofId)\n\tspoofDict[key] = spoofId\n\n### Change the nodes array \nnewNodes =[]\nfor j in nodes: \n\tnewId = spoofDict[j['Id']]\n\t#print(\"OLD ID: \" + str(j['Id']) + \"\\t NEW ID\\t \" + str(newId) + \"\\n\")\n\tj['Id'] = newId\n\tnewNodes.append(j)\n\n# Once we've finished building this indexDict, loop through to build edges\nfor key in indexDict:\n\t# Only take the first 3 matches\n\tmatches = indexDict[key]['matches'][0:3]\n\t# Only take the first match\n\t# matches = indexDict[key]['matches'][0:1]\n\tsourceIndex = indexDict[key]['index']\n\tfor match in matches:\n\t\t#q1 is eligible\n\t\t#q2 means this person wants to match\n\t\t#q3 means the other person wants to match\n\t\ttarget, q1, q2, q3 = match.split(\",\")\n\t\tsourceNode = key\n\t\ttargetNode = target\n\t\tif targetNode in matchesEntered.keys():\n\t\t\t# Filter out edges we've already tracked\n\t\t\tif sourceNode not in matchesEntered[targetNode]:\n\t\t\t\t# Keep track of this so we can filter in the future\n\t\t\t\tmatchesEntered[sourceNode].append(targetNode)\n\n\t\t\t\t# Get the target's key\n\t\t\t\tif target in indexDict.keys():\n\t\t\t\t\ttargetIndex = indexDict[target]['index']\n\t\t\t\t\t# Source ndoe and target node \n\t\t\t\t\t# Changing this so that it's by source node and target node..\n\t\t\t\t\t# To change back: sourceIndex and targetIndex \n\t\t\t\t\tconnection_dict = {'source':int(spoofDict[sourceNode]), 'target':int(spoofDict[targetNode]), 'eligible':q1, 'interested':q2, 'reverse interest':q3}\n\t\t\t\t\tedges.append(connection_dict)\nmyOutput = {'nodes':newNodes, 'edges':edges}\nprint(json.dumps(myOutput))\n","sub_path":"pyscripts/parse_network.py","file_name":"parse_network.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"5765588","text":"\"\"\"\nThis script will report on the data from the 'Regelgeving' and any possibility from Uitwisselingsplatform.\n\"\"\"\n# Allow lib to library import path.\nimport os\nimport sys\n(pp, cd) = os.path.split(os.getcwd())\nsys.path.append(pp)\n\n# import logging\nfrom lib import my_env\nfrom lib import mysqlstore as mysql\nfrom lib.mysqlstore import *\n\n\ndef list_of_tx(arcomp, comp_id, prev_comp=None):\n \"\"\"\n This function will get all the translations for a specific Archief component. In case there is one or more\n translation in the Uitwisselingsplatform, a list of all translations will be provided.\n In case there is no translation, then a list with a single value (\" . \") will be provided. This way we are sure\n that the Archief Component is listed.\n @param arcomp: Class for the Archief Component (ArType, ArFase, ArStap, ArDocument)\n @param comp_id: ID for the Archief component\n @param prev_comp: If previous component is not translated, then this component does not need to be translated\n @return: List of translations.\n \"\"\"\n not_translated = \" . \"\n list_tx = []\n if prev_comp != not_translated:\n for upcomps in cons_sess.query(arcomp).filter_by(id=comp_id).filter(arcomp.upcomps.any()):\n for upcomp in upcomps.upcomps:\n list_tx.append(upcomp.naam)\n if len(list_tx) == 0:\n list_tx.append(not_translated)\n return list_tx\n\n\nif __name__ == \"__main__\":\n\n cfg = my_env.init_env(\"convert_protege\", __file__)\n\n # Get session for Consolidation Database\n cons_sess = mysql.init_session(db=cfg[\"ConsolidationDB\"][\"db\"],\n user=cfg[\"ConsolidationDB\"][\"user\"],\n pwd=cfg[\"ConsolidationDB\"][\"pwd\"],\n echo=False)\n\n fn = os.path.join(cfg['Main']['reportdir'], \"dn3_platform_archief.csv\")\n with open(fn, 'w') as fh:\n fh.write(\"dossiertype;fase;stap;;dossiertype;fase;stap\\n\")\n for artype in cons_sess.query(ArType).filter(ArType.fases.any()):\n for uptype in list_of_tx(ArType, artype.id):\n for arfase in artype.fases:\n for upfase in list_of_tx(ArFase, arfase.id, prev_comp=uptype):\n for arstap2fase in cons_sess.query(ArFase).filter_by(id=arfase.id).filter(ArFase.stappen.any()):\n for arstap in arstap2fase.stappen:\n for upstap in list_of_tx(ArStap, arstap.id, prev_comp=upfase):\n fh.write(\"{d};{f};{s};;{uptype};{upfase};{upstap}\\n\"\n .format(d=artype.naam, f=arfase.naam, s=arstap.naam,\n uptype=uptype, upfase=upfase, upstap=upstap))\n\n fn = os.path.join(cfg['Main']['reportdir'], \"dn4_platform_archief.csv\")\n with open(fn, 'w') as fh:\n fh.write(\"dossiertype;fase;stap;document;;dossiertype;fase;stap;document\\n\")\n for artype in cons_sess.query(ArType).filter(ArType.fases.any()):\n for uptype in list_of_tx(ArType, artype.id):\n for arfase in artype.fases:\n for upfase in list_of_tx(ArFase, arfase.id, prev_comp=uptype):\n for arstap2fase in cons_sess.query(ArFase).filter_by(id=arfase.id).filter(ArFase.stappen.any()):\n for arstap in arstap2fase.stappen:\n for upstap in list_of_tx(ArStap, arstap.id, prev_comp=upfase):\n for ardocument2stap in cons_sess.query(ArStap).filter_by(id=arstap.id)\\\n .filter(ArStap.documenten.any()):\n for ardocument in ardocument2stap.documenten:\n for updocument in list_of_tx(ArDocument, ardocument.id, prev_comp=upstap):\n fh.write(\"{d};{f};{s};{ardoc};;{uptype};{upfase};{upstap};{updoc}\\n\"\n .format(d=artype.naam, f=arfase.naam, s=arstap.naam,\n ardoc=ardocument.naam,\n uptype=uptype, upfase=upfase, upstap=upstap,\n updoc=updocument))\n\nlogging.info('End Application')\n","sub_path":"Python/source_consolidation/report_archief_platform.py","file_name":"report_archief_platform.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"359081773","text":"# Copyright (C) 2014 Canonical Ltd.\n# Author: Michael Vogt <michael.vogt@ubuntu.com>\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; version 3 of the License.\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 <http://www.gnu.org/licenses/>.\n\n\"\"\"Integration tests for the click chroot feature.\"\"\"\n\nimport subprocess\nimport unittest\n\nfrom .helpers import (\n require_network,\n require_root,\n ClickTestCase,\n)\n\n# architectures present in 14.04 (current default framework)\nALLOW_ARCHITECTURES = [\n \"amd64\", \"arm64\", \"armhf\", \"i386\", \"powerpc\", \"ppc64el\"]\n\n\ndef skipUnlessAllowedArchitecture():\n system_arch = subprocess.check_output(\n [\"dpkg\", \"--print-architecture\"], universal_newlines=True).strip()\n if system_arch in ALLOW_ARCHITECTURES:\n return lambda func: func\n else:\n return unittest.skip(\"%s does not exist in 14.04\")\n\n\n@skipUnlessAllowedArchitecture()\nclass TestChroot(ClickTestCase):\n\n @classmethod\n def command(cls, arch, *args):\n return [cls.click_binary, \"chroot\", \"-a\", arch] + list(args)\n\n @classmethod\n def setUpClass(cls):\n super(TestChroot, cls).setUpClass()\n require_root()\n require_network()\n cls.arch = subprocess.check_output(\n [\"dpkg\", \"--print-architecture\"], universal_newlines=True).strip()\n subprocess.check_call(cls.command(cls.arch, \"create\"))\n\n @classmethod\n def tearDownClass(cls):\n subprocess.check_call(cls.command(cls.arch, \"destroy\"))\n\n def test_upgrade(self):\n subprocess.check_call(self.command(self.arch, \"upgrade\"))\n\n def test_install(self):\n subprocess.check_call(self.command(self.arch, \"install\", \"apt-utils\"))\n\n def test_run(self):\n output = subprocess.check_output(\n self.command(self.arch, \"run\", \"echo\", \"hello world\"),\n universal_newlines=True)\n self.assertEqual(output, \"hello world\\n\")\n\n def test_maint(self):\n output = subprocess.check_output(\n self.command(self.arch, \"maint\", \"id\"),\n universal_newlines=True)\n self.assertEqual(output, \"uid=0(root) gid=0(root) groups=0(root)\\n\")\n\n def test_exists_ok(self):\n subprocess.check_call(self.command(self.arch, \"exists\"))\n\n def test_exists_no(self):\n with self.assertRaises(subprocess.CalledProcessError):\n subprocess.check_call(\n self.command(\"arch-that-does-not-exist\", \"exists\"))\n\n\nclass TestChrootName(TestChroot):\n \"\"\"Run the chroot tests again with a different --name.\"\"\"\n\n @classmethod\n def command(cls, arch, *args):\n return super(TestChrootName, cls).command(\n arch, \"-n\", \"testname\", *args)\n\n def test_exists_different_name_fails(self):\n # \"click chroot exists\" fails for a non-existent name.\n with self.assertRaises(subprocess.CalledProcessError):\n subprocess.check_call(super(TestChrootName, self).command(\n self.arch, \"-n\", \"testname2\", \"exists\"))\n","sub_path":"click/tests/integration/test_chroot.py","file_name":"test_chroot.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"92024670","text":"#! /usr/bin/env python2\n\ndef main():\n\n #\n # Imports & globals\n #\n global args, summaryInstance, sys, time, pysam\n import pysam, sys, time\n\n #\n # Argument parsing\n #\n argumentsInstance = readArgs()\n processor_count = readArgs.processors(argumentsInstance)\n\n #\n # Initials\n #\n summaryInstance = Summary()\n window = args.window_size\n past_unpaired_reads = dict()\n\n currentPhaseBlocks = CurrentPhaseBlocks()\n rp_max_dist = 50000\n\n current_limit = 1000000\n\n report_progress('Fetching cache reads')\n\n with pysam.AlignmentFile(args.sort_tag_bam, 'rb') as infile:\n\n for chromosome_header in infile.header['SQ']:\n\n chromosome_name = chromosome = chromosome_header['SN']\n chromosome_length = chromosome_header['LN']\n\n for read in infile.fetch(chromosome_name, 0, chromosome_length):\n\n summaryInstance.reads += 1\n\n if summaryInstance.reads >= current_limit:\n report_progress(\"{:,}\".format(summaryInstance.reads) + ' reads fetched')\n current_limit += 1000000\n\n # Stores read until its mate occurs in file\n # NB: mate will always be upstream of read!\n try: mate = past_unpaired_reads[read.query_name]\n except KeyError:\n past_unpaired_reads[read.query_name] = read\n continue\n\n # Drop read from tmp storage when mate is found\n del past_unpaired_reads[read.query_name]\n\n # Fetch positions\n mate_start, mate_stop = mate.get_reference_positions()[0], mate.get_reference_positions()[-1]\n read_start, read_stop = read.get_reference_positions()[0], read.get_reference_positions()[-1]\n\n # Standardise read positions according to refernce instead of read direction.\n mate_start, mate_stop = direct_read_pairs_to_ref(mate_start, mate_stop)\n read_start, read_stop = direct_read_pairs_to_ref(read_stop, read_start)\n\n # If read pairs are ridiculously far apart (50 kb), just count reads as unpaired\n if mate_stop + rp_max_dist < read_start:\n summaryInstance.unpaired_reads += 2\n summaryInstance.unpaired_reads_in_same_chr += 2\n continue\n\n # Calculates % read bases of insert, aka (bp_r1 + bp_r2) / (bp_r1 + bp_r2 + bp_btw_rp)\n percent_coverage = read_pair_coverage(mate_start, mate_stop, read_start, read_stop)\n barcode_id = read.get_tag('RG')\n\n # Intitates phase blocks with name = barcode_ID, if not that phase block exist, then fetches last pos(phase block)\n try: last_pos_of_phase_block = currentPhaseBlocks.dictionary[barcode_id]['stop']\n except KeyError:\n # Initiate new entry with (start, stop, # reads)\n currentPhaseBlocks.initiatePhaseBlock(name=barcode_id, start=mate_start, stop=read_stop, rp_coverage=percent_coverage)\n continue\n\n # If last position of phase block is withing window (100 kb) distance of current read, then add this read to phase block.\n if (last_pos_of_phase_block+window) >= mate_start:\n currentPhaseBlocks.addReadPairToPhaseBlock(phase_block=barcode_id, rp_start=mate_start, rp_stop=read_stop, rp_coverage=percent_coverage)\n\n # If read is outside range of window from last position, then report the old phase block and initate a new one.\n else:\n\n # Normalises average coverage for number of reads when grand total is known.\n summaryInstance.reportPhaseBlock(currentPhaseBlocks.dictionary[barcode_id], barcode_id)\n currentPhaseBlocks.terminatePhaseBlock(phase_block=barcode_id)\n\n # Initiate new entry with (start, stop, # reads)\n currentPhaseBlocks.initiatePhaseBlock(name=barcode_id, start=mate_start, stop=read_stop, rp_coverage=percent_coverage)\n\n # Will rinse/count unpaired reads in between chromosomes\n summaryInstance.unpaired_reads += len(past_unpaired_reads.keys())\n past_unpaired_reads = dict()\n\n # Report phase blocks when switching to new chromosome, as not to confuse positions\n currentPhaseBlocks.commitAndRemoveAll()\n\n report_progress('Phase blocks analysed')\n\n summaryInstance.writeResultFiles()\n\n # GREPFRICK: move to summary somewhere\n sys.stderr.write('\\nReads found (not read pairs) in bam:\\t' + \"{:,}\".format(summaryInstance.reads) + '\\n')\n sys.stderr.write('\\nUnpaired reads (removed from analysis):\\t' + \"{:,}\".format(summaryInstance.unpaired_reads) + '\\n')\n sys.stderr.write('In the same chromosome:\\t' + \"{:,}\".format(summaryInstance.unpaired_reads_in_same_chr) + '\\n')\n sys.stderr.write('(Defined as being ' + \"{:,}\".format(rp_max_dist) + ' bp apart)\\n')\n sys.stderr.write('\\nPhase blocks identified:\\t' + \"{:,}\".format(summaryInstance.phase_block_counter) + '\\n')\n sys.stderr.write('Phase blocks with only one read:\\t' + \"{:,}\".format(summaryInstance.phase_block_with_only_one_read_pair) + '\\n')\n\ndef direct_read_pairs_to_ref(read_start, read_stop):\n \"\"\"\n Reads can be aligned in forward and backwards direction, this puts all start/stops according to reference positions\n \"\"\"\n\n # if read backwards, turn it the other way\n if read_start > read_stop:\n return read_stop, read_start\n # Otherwise, return it as is\n else:\n return read_start, read_stop\n\ndef read_pair_coverage(mate_start, mate_stop, read_start, read_stop):\n \"\"\"\n This function calculates the percentage of read bases in the insert.\n \"\"\"\n\n # If reads overlap, cov = 1\n if mate_stop >= read_start:\n percent_coverage = 1\n # Otherwise, calc. % covered bases\n else:\n mate_bp = mate_stop - mate_start\n read_bp = read_stop - read_start\n uncovered_bases = read_start - mate_stop\n percent_coverage = (mate_bp + read_bp) / (uncovered_bases + mate_bp + read_bp)\n\n return percent_coverage\n\ndef report_progress(string):\n \"\"\"\n Writes a time stamp followed by a message (=string) to standard out.\n Input: String\n Output: [date] string\n \"\"\"\n sys.stderr.write(time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) + '\\t' + string + '\\n')\n\nclass CurrentPhaseBlocks(object):\n \"\"\"\n Tmp storage for phase blocks which might still get more reads assigned to them. Basically a dict with customised functions.\n \"\"\"\n\n def __init__(self):\n self.dictionary = dict()\n\n def initiatePhaseBlock(self, name, start, stop, rp_coverage):\n\n summaryInstance.phase_block_counter += 1\n\n self.dictionary[name] = dict()\n self.dictionary[name]['start'] = start\n self.dictionary[name]['stop'] = stop\n self.dictionary[name]['coverage'] = rp_coverage\n self.dictionary[name]['number_of_reads'] = 2\n self.dictionary[name]['insert_bases'] = stop - start\n self.dictionary[name]['bases_btw_inserts'] = 0\n\n def addReadPairToPhaseBlock(self, phase_block, rp_start, rp_stop, rp_coverage):\n self.dictionary[phase_block]['insert_bases'] += rp_stop - rp_start\n self.dictionary[phase_block]['bases_btw_inserts'] += rp_start - self.dictionary[phase_block]['stop']\n self.dictionary[phase_block]['stop'] = rp_stop\n self.dictionary[phase_block]['coverage'] += rp_coverage\n self.dictionary[phase_block]['number_of_reads'] += 2\n\n def terminatePhaseBlock(self, phase_block):\n\n del self.dictionary[phase_block]\n\n def commitAndRemoveAll(self):\n\n for phase_block in self.dictionary.copy().keys():\n summaryInstance.reportPhaseBlock(self.dictionary[phase_block], phase_block)\n del self.dictionary[phase_block]\n\nclass ProgressBar(object):\n \"\"\"\n Writes a progress bar to stderr\n \"\"\"\n\n def __init__(self, name, min, max, step):\n # Variables\n self.min = min\n self.max = max\n self.current_position = min\n self.step = step\n\n # Metadata\n self.two_percent = (self.max-self.min)/50\n self.current_percentage = self.two_percent\n\n # Printing\n report_progress(name)\n sys.stderr.write('\\n' + str(name))\n sys.stderr.write('\\n|------------------------------------------------|\\n')\n\n def update(self):\n # If progress is over 2%, write '#' to stdout\n self.current_position += self.step\n if self.current_percentage < self.current_position:\n sys.stderr.write('#')\n sys.stderr.flush()\n time.sleep(0.001)\n self.current_percentage += self.two_percent\n\n def terminate(self):\n sys.stderr.write('\\n')\n\nclass readArgs(object):\n \"\"\"\n Reads arguments and handles basic error handling like python version control etc.\n \"\"\"\n\n def __init__(self):\n\n readArgs.parse(self)\n readArgs.pythonVersion(self)\n\n def parse(self):\n\n #\n # Imports & globals\n #\n import argparse, multiprocessing\n global args\n\n parser = argparse.ArgumentParser(description=__doc__)\n\n # Arguments\n parser.add_argument(\"sort_tag_bam\", help=\".bam file tagged with @RG tags and duplicates marked (not taking \"\n \"cluster id into account).\")\n parser.add_argument(\"output_prefix\", help=\"prefix for results files (.read_pair_coverage, .coupling_efficiency, \"\n \".reads_per_molecule, .molecule_per_barcode and .phase_block_lengths\")\n\n # Options\n parser.add_argument(\"-F\", \"--force_run\", action=\"store_true\", help=\"Run analysis even if not running python 3. \"\n \"Not recommended due to different function \"\n \"names in python 2 and 3.\")\n parser.add_argument(\"-p\", \"--processors\", type=int, default=multiprocessing.cpu_count(),\n help=\"Thread analysis in p number of processors. \\nDEFAULT: all available\")\n parser.add_argument(\"-w\", \"--window_size\", type=int, default=100000, help=\"Window size cutoff for maximum distance \"\n \"in between two reads in one phase block. \"\n \"DEFAULT: 100,000 bp\")\n\n args = parser.parse_args()\n\n def pythonVersion(self):\n \"\"\" Makes sure the user is running python 3.\"\"\"\n\n #\n # Version control\n #\n import sys\n if sys.version_info.major == 3:\n pass\n else:\n sys.stderr.write('\\nWARNING: you are running python ' + str(\n sys.version_info.major) + ', this script is written for python 3.')\n if not args.force_run:\n sys.stderr.write('\\nAborting analysis. Use -F (--Force) to run anyway.\\n')\n sys.exit()\n else:\n sys.stderr.write('\\nForcing run. This might yield inaccurate results.\\n')\n\n def processors(self):\n\n #\n # Processors\n #\n import multiprocessing\n processor_count = args.processors\n max_processor_count = multiprocessing.cpu_count()\n if processor_count == max_processor_count:\n pass\n elif processor_count > max_processor_count:\n sys.stderr.write(\n 'Computer does not have ' + str(processor_count) + ' processors, running with default (' + str(\n max_processor_count) + ')\\n')\n processor_count = max_processor_count\n else:\n sys.stderr.write('Running with ' + str(processor_count) + ' processors.\\n')\n\n return processor_count\n\nclass Summary(object):\n\n def __init__(self):\n\n # Just defining numbers which will be assigned later\n self.reads = int()\n self.phase_blocks = int()\n self.bc_clusters = int()\n\n self.phase_block_lengths = dict()\n self.phase_blocks_per_cluster = dict()\n self.reads_per_phase_block = dict()\n\n self.ave_coverage_phase_block = int()\n self.ave_bases_read_in_read_pair = int()\n\n self.phase_block_result_dict = dict()\n\n self.unpaired_reads = int()\n self.unpaired_reads_in_same_chr = int()\n\n self.phase_block_with_only_one_read_pair = int()\n self.phase_block_counter = int()\n\n def reportPhaseBlock(self, phase_block, barcode_id):\n\n start = phase_block['start']\n stop = phase_block['stop']\n length = stop-start\n num_reads = phase_block['number_of_reads']\n ave_read_pair_coverage = phase_block['coverage'] / num_reads\n\n # Don't want ZeroDivision error\n if phase_block['bases_btw_inserts'] == 0:\n ave_phase_block_cov = 1\n else:\n ave_phase_block_cov = phase_block['insert_bases']/(phase_block['bases_btw_inserts'] + phase_block['insert_bases'])\n\n # Tries to append to list of tuples, otherwise creates a tuple list as value for given barcode id\n try: self.phase_block_result_dict[barcode_id]\n except KeyError:\n self.phase_block_result_dict[barcode_id] = list()\n\n # Save in summary dictionary\n self.phase_block_result_dict[barcode_id].append((start, stop, length, num_reads, ave_read_pair_coverage, ave_phase_block_cov))\n\n def writeResultFiles(self):\n\n # Opening all files\n molecules_per_bc_out = open((args.output_prefix + '.molecules_ber_bc'), 'w')\n coupling_out = open((args.output_prefix + '.coupling_efficiency'), 'w')\n ave_read_pair_coverage_out = open((args.output_prefix + '.ave_read_pair_coverage_in_phase_block'), 'w')\n reads_per_phase_block_out = open((args.output_prefix + '.reads_per_molecule'), 'w')\n phase_block_len_out = open((args.output_prefix + '.phase_block_lengths'), 'w')\n\n progressBar = ProgressBar(name='Writing output', min=0, max = summaryInstance.phase_block_counter, step = 1)\n\n # Writing outputs\n for barcode_id in self.phase_block_result_dict.keys():\n\n molecules_per_bc_out.write(str(len(self.phase_block_result_dict[barcode_id])) + '\\n')\n\n for phase_block in self.phase_block_result_dict[barcode_id]:\n\n reads_per_phase_block_out.write(str(phase_block[3]) + '\\n')\n ave_read_pair_coverage_out.write(str(phase_block[4]) + '\\n')\n\n # Not interesting if number of reads found are 1\n if phase_block[3] > 2:\n summaryInstance.phase_block_with_only_one_read_pair += 1\n phase_block_len_out.write(str(phase_block[2]) + '\\n')\n coupling_out.write(str(phase_block[5]/0.5) + '\\n')\n\n progressBar.update()\n\n # Close files\n for output_file in (molecules_per_bc_out, coupling_out, ave_read_pair_coverage_out, reads_per_phase_block_out, phase_block_len_out):\n output_file.close()\n\n progressBar.terminate()\n\nif __name__==\"__main__\": main()","sub_path":"python scripts/cluster_stats.py","file_name":"cluster_stats.py","file_ext":"py","file_size_in_byte":15408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27457575","text":"def xor(state, inputs, length, invert):\n \"\"\"Computes XOR digital logic\n\n Parameters:\n\n :param str state : Current state of the register\n :param list inputs: Position to tap inputs from register\n Returns:\n\n :return output: Output of the XOR gate digital logic\n :rtype int :\n \"\"\"\n\n # Obtain bits to feed into Xor gate given index value\n input_a = int(state[inputs[0]])\n input_b = int(state[inputs[1]])\n\n result = bool((input_a & ~input_b) | (~input_a & input_b))\n\n # Checks if an XNOR is needed\n if invert is True: result = not result\n\n # Shift result of xor to MSB\n return result << length\n\n\nif __name__ == \"__main__\":\n\n current_state = \"001\"\n\n # Position to tap for Xor gate\n index_inputs = [0, 2]\n max_clock = 100\n invert = False\n\n for clock in range(0, max_clock + 1):\n\n print(clock, current_state)\n\n xor_output = xor(current_state, index_inputs, len(current_state) - 1,\n invert)\n\n shift = int(current_state, 2) >> 1\n\n # Re-assign the current state and pad with zeroes\n current_state = format(xor_output | shift, '0{}b'.format(len(\n current_state)))\n","sub_path":"LFSR.py","file_name":"LFSR.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"77000877","text":"\"\"\"\nModule with a B+tree implementation.\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Generic\nfrom typing import Optional\nfrom typing import Tuple\n\nfrom pystrukts._types.basic import Endianness\nfrom pystrukts._types.basic import StrPath\nfrom pystrukts._types.comparable import KT\nfrom pystrukts._types.comparable import VT\nfrom pystrukts.trees.bplustree.memory import PagedFileMemory\nfrom pystrukts.trees.bplustree.node import BPTNode\nfrom pystrukts.trees.bplustree.node import InnerRecord\nfrom pystrukts.trees.bplustree.node import LeafRecord\nfrom pystrukts.trees.bplustree.serializers import DefaultSerializer\nfrom pystrukts.trees.bplustree.serializers import Serializer\nfrom pystrukts.trees.bplustree.settings import INNER_NODE_HEADERS_SPACE\nfrom pystrukts.trees.bplustree.settings import LEAF_NODES_HEADERS_SPACE\nfrom pystrukts.trees.bplustree.settings import NODE_POINTER_BYTE_SPACE\n\n\nclass BPlusTree(Generic[KT, VT]):\n \"\"\"\n Class that represents a B+tree.\n \"\"\"\n\n root: BPTNode[KT, VT]\n memory: PagedFileMemory\n inner_degree: int\n leaf_degree: int\n\n key_serializer: Serializer[KT]\n value_serializer: Serializer[VT]\n endianness: Endianness = \"big\"\n\n def __init__(\n self,\n tree_file: Optional[StrPath] = None,\n key_serializer: Optional[Serializer[KT]] = None,\n value_serializer: Optional[Serializer[VT]] = None,\n page_size: int = 4096,\n max_key_size: int = 8,\n max_value_size: int = 32,\n ) -> None:\n self.key_serializer = key_serializer if key_serializer is not None else DefaultSerializer[KT]()\n self.value_serializer = value_serializer if value_serializer is not None else DefaultSerializer[VT]()\n self.memory = PagedFileMemory(page_size, max_key_size, max_value_size, self.endianness, tree_file)\n self.inner_degree = self._compute_inner_degree()\n self.leaf_degree = self._compute_leaf_degree()\n\n if self.memory.is_new_file:\n self.root = self._create_root()\n else:\n self.root = self._read_root()\n\n def insert(self, key: KT, value: VT) -> None:\n \"\"\"\n Inserts a new key and value on the B+tree. Splits the root node or children nodes\n as the max number of keys are exceeded on the nodes according to the tree's degree.\n \"\"\"\n if self._is_full(self.root):\n old_root = self.root\n\n # new root is never a leaf node\n new_root = self._create_node(is_leaf=False)\n self.root = new_root\n self._swap_pages(old_root, new_root) # swap disk pages so that the new root stays on page 1\n\n # first node pointer is always created upon inner split\n new_root.first_node = old_root\n new_root.first_node_page = old_root.disk_page\n\n # splits the new root's child (old root) which is full to add the new key/value\n self._split_child(new_root, old_root, 0)\n self._insert_non_full(new_root, key, value)\n else:\n self._insert_non_full(self.root, key, value)\n\n def get(self, key: KT) -> Optional[VT]:\n \"\"\"\n Looks for a key on the B+tree. If it's not found, returns None.\n \"\"\"\n result = self._get(self.root, key)\n\n if result is not None:\n node, i = result # only leaf nodes can contain values, so we have a leaf node\n return node.leaf_records[i].value\n\n return None\n\n def _get(self, node: BPTNode[KT, VT], key: KT) -> Optional[Tuple[BPTNode[KT, VT], int]]:\n \"\"\"\n Finds a leaf node along with it's corresponding index int of its 'leaf_records' array\n containg the record with the value associated with the given key. If no such node is found,\n returns None.\n \"\"\"\n i = 0\n\n if node.is_leaf:\n while i < node.records_count and key > node.leaf_records[i].key:\n i += 1\n\n if i < node.records_count and key == node.leaf_records[i].key:\n return node, i\n\n return None\n\n # inner node searching\n while i < node.records_count and key > node.inner_records[i].key:\n i += 1\n\n # here we have an inner node, if i == 0, it's smaller than all keys\n # so look at the first child page (out of the inner_records)\n if i == 0:\n next_node_page = node.first_node_page\n next_node = node.first_node\n else:\n i -= 1 # [!]: key is bigger than first page keys, but inner_records starts at i == 0\n\n next_node_page = node.inner_records[i].next_node_page\n next_node = node.inner_records[i].next_node\n\n # check if the next inner node is in memory\n if next_node is not None:\n return self._get(next_node, key)\n\n # if not in memory, read it from disk and perform recursion\n return self._get(self._disk_read(next_node_page), key)\n\n def _disk_write(self, node: BPTNode[KT, VT]) -> None:\n \"\"\"\n Writes a given node to disk according to its page attribute by calling the memory allocator.\n \"\"\"\n node_page = node.disk_page\n node_data = node.to_page(\n self.memory.page_size, self.memory.max_key_size, self.memory.max_value_size, self.endianness\n )\n self.memory.write_page(node_page, node_data)\n\n def _disk_read(self, node_page: int) -> BPTNode[KT, VT]:\n \"\"\"\n Reads a given node from disk according to its page attribute by calling the memory allocator.\n \"\"\"\n page_data = self.memory.read_page(node_page)\n\n node_from_disk: BPTNode[KT, VT] = BPTNode(True, node_page, self.key_serializer, self.value_serializer)\n node_from_disk.load_from_page(page_data, self.memory.max_key_size, self.memory.max_value_size, self.endianness)\n\n return node_from_disk\n\n def _is_full(self, node: BPTNode[KT, VT]) -> bool:\n \"\"\"\n Checks if the given node is full of keys according to the tree's degree which takes\n into account the disk page sizes.\n \"\"\"\n degree = self.leaf_degree if node.is_leaf else self.inner_degree\n\n return node.records_count == 2 * degree - 1\n\n def _insert_non_full(self, node: BPTNode[KT, VT], key: KT, value: VT) -> None:\n \"\"\"\n Inserts a new key into a non-full node or raise an exception.\n \"\"\"\n # starts at the end of the inserted keys so far\n i = node.records_count - 1\n\n if node.is_leaf:\n new_record = LeafRecord(key, value)\n\n # finds final sorted position of the key (notice we need to do i + 1 after the loop)\n while i >= 0 and key < node.leaf_records[i].key:\n i -= 1\n\n # shift keys right to find a new spot for the new key\n node.leaf_records.insert(i + 1, new_record)\n\n self._disk_write(node)\n else:\n while i >= 0 and key < node.inner_records[i].key:\n i -= 1\n\n child_node_page = node.inner_records[i].next_node_page\n child_node = self._disk_read(child_node_page)\n node.inner_records[i].next_node = child_node\n\n if self._is_full(child_node):\n self._split_child(node, child_node, i)\n if key > node.inner_records[i].key:\n i += 1\n\n # as splitting adds a new key in the current node, refetch child\n child_node_page = node.inner_records[i].next_node_page\n child_node = self._disk_read(child_node_page)\n node.inner_records[i].next_node = child_node\n\n self._insert_non_full(child_node, key, value)\n\n def _split_child(self, parent_node: BPTNode[KT, VT], child_node: BPTNode[KT, VT], i: int) -> None:\n \"\"\"\n Splits the child according to whether it is a leaf or inner node. Notice that the parent node must\n be an inner node or it would not have children.\n \"\"\"\n if child_node.is_leaf:\n self._split_leaf_child(parent_node, child_node, i)\n else:\n self._split_inner_child(parent_node, child_node, i)\n\n def _split_inner_child(self, parent_node: BPTNode[KT, VT], child_node: BPTNode[KT, VT], i: int) -> None:\n \"\"\"\n Splits the i-th full child of the given parent node. Notice that the parent node, as it has a child, is\n an inner node (non-leaf) but the child itself can either be a leaf or an inner-node.\n \"\"\"\n new_node = self._create_node(is_leaf=False) # creates a new inner node\n degree = self.inner_degree\n\n # copies lower part of the full child node to the new node\n for j in range(0, degree - 1):\n record = child_node.inner_records[degree + j]\n new_node.inner_records.append(InnerRecord(record.key, record.next_node_page, record.next_node))\n\n # removes copied nodes from child node\n child_node.leaf_records.pop(degree + j)\n\n # inserts new key into the non-full inner node parent and make it point to the new node\n parent_node.inner_records.insert(\n i, InnerRecord(child_node.inner_records[degree - 1].key, new_node.disk_page, new_node)\n )\n child_node.inner_records.pop(degree - 1) # removes the split key from the child to 'pass' it to the parent\n\n # disk persistance of the split\n self._disk_write(child_node)\n self._disk_write(new_node)\n self._disk_write(parent_node)\n\n def _split_leaf_child(self, parent_node: BPTNode[KT, VT], child_node: BPTNode[KT, VT], i: int) -> None:\n \"\"\"\n Splits the i-th full child of the given parent node. Notice that the parent node, as it has a child, is\n an inner node and never a leaf node.\n \"\"\"\n new_node = self._create_node(is_leaf=True)\n degree = self.leaf_degree\n\n # copies lower part of the full child node to the new node\n for j in range(0, degree - 1):\n record = child_node.leaf_records[degree + j]\n new_node.leaf_records.append(LeafRecord(record.key, record.value))\n\n # removes copied nodes from child node\n child_node.leaf_records.pop(degree + j)\n\n # inserts new key into the non-full inner node parent and make it point to the new node\n parent_node.inner_records.insert(\n i, InnerRecord(child_node.leaf_records[degree - 1].key, new_node.disk_page, new_node)\n )\n\n # disk persistance of the split\n self._disk_write(child_node)\n self._disk_write(new_node)\n self._disk_write(parent_node)\n\n def _compute_inner_degree(self) -> int:\n \"\"\"\n Computes the degree (t) of the B+tree in order to use to decide when a given node is full or not. Here\n the degree of the tree is computed based on the amount of records that are able to fit a single disk page.\n\n Maximum allowed keys for any node: (2*t - 1) keys and 2*t children\n Minimum allowed keys for any node: (t - 1) keys and t children\n\n 2*t - 1 == \"max keys in node on a single page\" -> 2*t - 1 == free_page_size / each_record_size and solve for t\n \"\"\"\n page_headers_size = INNER_NODE_HEADERS_SPACE\n each_record_size = NODE_POINTER_BYTE_SPACE + self.memory.max_key_size\n free_page_size = self.memory.page_size - page_headers_size\n degree = int((free_page_size / each_record_size + 1) / 2) # max amount of keys in inner nodes\n\n if degree <= 0:\n raise ValueError(\n \"Impossible disk page memory layout for inner nodes: B+tree's degree <= 0! Please, \"\n \"increase the page size or reduce the max key value size.\"\n )\n\n return degree\n\n def _compute_leaf_degree(self) -> int:\n \"\"\"\n Computes the degree (t) of the B+tree for leaf nodes as their memory layout is different than inner nodes as\n key values take up more space. As a consequence, a leaf node becomes full with less records than an inner\n code and, as such, has a different degree.\n \"\"\"\n page_headers_size = LEAF_NODES_HEADERS_SPACE\n each_record_size = self.memory.max_key_size + self.memory.max_value_size\n free_page_size = self.memory.page_size - page_headers_size\n degree = int((free_page_size / each_record_size + 1) / 2)\n\n if degree <= 0:\n raise ValueError(\n \"Impossible disk page memory layout for leaf nodes: B+tree's degree <= 0! Please, \"\n \"increase the page size or reduce the max key value size.\"\n )\n\n return degree\n\n def _create_node(self, is_leaf: bool) -> BPTNode[KT, VT]:\n \"\"\"\n Allocates a new free disk page and instantiates a new node instance. The new node contains reference to\n its new disk page.\n \"\"\"\n new_page_number = self.memory.allocate_page()\n new_empty_node: BPTNode[KT, VT] = BPTNode(is_leaf, new_page_number, self.key_serializer, self.value_serializer)\n\n return new_empty_node\n\n def _swap_pages(self, node_1: BPTNode[KT, VT], node_2: BPTNode[KT, VT]) -> None:\n \"\"\"\n Swaps disk pages between two nodes. Notice that this mutates the two node's disk_page property.\n \"\"\"\n disk_page_1 = node_1.disk_page\n node_1.disk_page = node_2.disk_page\n node_2.disk_page = disk_page_1\n\n self._disk_write(node_1)\n self._disk_write(node_2)\n\n def _create_root(self) -> BPTNode[KT, VT]:\n \"\"\"\n Creates a new root for the B+tree (when the B+tree's file is new).\n \"\"\"\n page_number = self.memory.allocate_page()\n\n root = BPTNode(True, page_number, self.key_serializer, self.value_serializer)\n self._disk_write(root)\n\n return root\n\n def _read_root(self) -> BPTNode[KT, VT]:\n \"\"\"\n Reads a previous root of the B+tree from it's B+tree file.\n \"\"\"\n return self._disk_read(1) # root is always stored on page 1 (page 0 for tree metadata)\n","sub_path":"pystrukts/trees/bplustree/bplustree.py","file_name":"bplustree.py","file_ext":"py","file_size_in_byte":14013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568359333","text":"import numpy as np\n\n#raiz de 2 está entre 1 y 2, se escoge un initial guess entre ellos\nx = 1.1\n\nn_max = 100\ni = 0\nwhile i < n_max:\n\n x_ant = x\n x = (x + 2/x)/2\n print(x)\n if x_ant == x:\n break\n i += 1\n","sub_path":"Python/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167660250","text":"import global_config as G\nimport numpy as np\n\nfrom astropy.io import fits as pyfits\nfrom astropy.coordinates import Angle\nimport os.path as op\n\n#log = G.logging.getLogger('hetdex_logger')\n#log.setLevel(G.logging.DEBUG)\nlog = G.Global_Logger('hetdex_logger')\nlog.setlevel(G.logging.DEBUG)\n\nclass HetdexFits:\n '''A single HETDEX fits file ... 2D spectra, expected to be science file'''\n\n #needs open with basic validation\n #\n\n def __init__(self,fn,e_fn,fe_fn,dither_index=-1,panacea=False):\n self.okay = True\n self.filename = fn\n self.err_filename = e_fn\n self.fe_filename = fe_fn\n\n self.panacea = panacea\n\n self.tel_ra = None\n self.tel_dec = None\n self.parangle = None\n self.ifuid = None # reminder this is the cable\n self.ifuslot = None # reminder this is the position (slot) on the fplane\n self.side = None\n self.amp = None\n self.specid = None\n self.obs_date = None\n self.obs_ymd = None\n self.mjd = None\n self.obsid = None\n self.expid = None\n self.imagetype = None\n #self.exptime = None #don't need these right now\n #self.dettemp = None #don't need these right now\n\n self.data = None\n self.data_sky = None #sky NOT subtracted\n self.err_data = None\n self.fe_data = None #fiber extracted counts\n self.wave_data = None #matched wavelengths\n self.trace_data = None\n self.fiber_to_fiber = None\n self.error_analysis = None\n self.pixflat_data = None\n self.fiber_centers = None\n self.fe_crval1 = None\n self.fe_cdelt1 = None\n\n self.dither_index = dither_index\n\n #build basic info from filename\n\n #determine if 'cure'-style fits or panacea fits\n #stupid simple just for now\n #even for annulus, go ahead an read. Don't know if we are going to want the fits files, but may as well get them\n if \"multi_\" in self.filename: # example: multi_020_095_004_LU.fits\n self.read_panacea_fits()\n else:\n self.read_fits(use_cosmic_cleaned=G.PreferCosmicCleaned)\n self.read_efits(use_cosmic_cleaned=G.PreferCosmicCleaned)\n self.read_fefits()\n\n def read_fits(self,use_cosmic_cleaned=False):\n\n if not self.filename:\n return None\n\n if not op.exists(self.filename):\n log.error(\"Error. FITS file does not exist: \" + self.filename)\n return None\n\n try:\n f = pyfits.open(self.filename)\n except:\n log.error(\"could not open file \" + self.filename, exc_info=True)\n return None\n\n c = None\n try:\n if use_cosmic_cleaned:\n base = op.basename(self.filename)\n if base[0] != 'c':\n path = op.dirname(self.filename)\n\n cosmic = op.join(path,\"c\"+base)\n log.info(\"Attempting to open cosmic cleaned version of file: \" + cosmic)\n c = pyfits.open(cosmic)\n except:\n log.error(\"could not open file \" + cosmic, exc_info=True)\n c = None\n\n\n if c is not None:\n self.data = np.array(c[0].data)\n else:\n self.data = np.array(f[0].data)\n #clean up any NaNs\n self.data[np.isnan(self.data)] = 0.0\n\n try:\n self.tel_ra = float(Angle(f[0].header['TELRA']+\"h\").degree) #header is in hour::mm:ss.arcsec\n self.tel_dec = float(Angle(f[0].header['TELDEC']+\"d\").degree) #header is in deg:hh:mm:ss.arcsec\n self.parangle = f[0].header['PARANGLE']\n except:\n log.error(\"Cannot translate RA and/or Dec from FITS format to degrees in \" + self.filename, exc_info=True)\n\n try:\n self.ifuid = str(f[0].header['IFUID']).zfill(3)\n self.ifuslot = str(f[0].header['IFUSLOT']).zfill(3)\n self.side = f[0].header['CCDPOS']\n self.specid = str(f[0].header['SPECID']).zfill(3)\n self.obs_date = f[0].header['DATE-OBS']\n\n if '-' in self.obs_date: #expected format is YYYY-MM-DD\n self.obs_ymd = self.obs_date.replace('-','')\n self.mjd = f[0].header['MJD']\n self.obsid = f[0].header['OBSID']\n self.imagetype = f[0].header['IMAGETYP']\n #self.exptime = f[0].header['EXPTIME']\n #self.dettemp = f[0].header['DETTEMP']\n except:\n log.error(\"Cannot read expected keywords in fits header: \" + self.filename,exc_info=True)\n self.okay = False\n\n try:\n f.close()\n except:\n log.error(\"could not close file \" + self.filename, exc_info=True)\n\n if c is not None:\n try:\n c.close()\n except:\n log.error(\"could not close file cosmic file version of \" + self.filename, exc_info=True)\n return\n\n def read_efits(self,use_cosmic_cleaned=False):\n\n if self.err_filename is None:\n return None\n\n try:\n f = pyfits.open(self.err_filename)\n except:\n log.error(\"could not open file \" + self.err_filename, exc_info=True)\n return None\n\n c = None\n try:\n if use_cosmic_cleaned:\n #for simplicity, using self.filename instead of self.err_filename\n #since will assume err_filename = \"e.\" + self.filename\n base = op.basename(self.filename)\n if base[0] != 'c':\n path = op.dirname(self.err_filename)\n\n cosmic = op.join(path, \"e.c\" + base)\n log.info(\"Attempting to open cosmic cleaned version of file: \" + cosmic)\n c = pyfits.open(cosmic)\n except:\n log.error(\"could not open file \" + cosmic, exc_info=True)\n c = None\n\n if c is not None:\n self.err_data = np.array(c[0].data)\n else:\n self.err_data = np.array(f[0].data)\n\n # clean up any NaNs\n self.err_data[np.isnan(self.err_data)] = 0.0\n\n try:\n f.close()\n except:\n log.error(\"could not close file \" + self.err_filename, exc_info=True)\n\n if c is not None:\n try:\n c.close()\n except:\n log.error(\"could not close file cosmic file version of \" + self.filename, exc_info=True)\n\n return\n\n def read_fefits(self):\n\n if self.fe_filename is None:\n return None\n\n try:\n f = pyfits.open(self.fe_filename)\n except:\n log.error(\"could not open file \" + self.fe_filename, exc_info=True)\n return None\n\n try:\n self.fe_data = np.array(f[0].data)\n # clean up any NaNs\n self.fe_data[np.isnan(self.fe_data)] = 0.0\n self.fe_crval1 = f[0].header['CRVAL1']\n self.fe_cdelt1 = f[0].header['CDELT1']\n except:\n log.error(\"could not read values or data from file \" + self.fe_filename, exc_info=True)\n\n try:\n f.close()\n except:\n log.error(\"could not close file \" + self.fe_filename, exc_info=True)\n\n return\n\n def read_panacea_fits(self):\n #this represents one AMP\n #15+ hdus, different header keys\n\n if not self.filename:\n return None\n\n tarfile = None\n file = None\n if not op.exists(self.filename):\n # todo: try to find .tar file and load that way\n tar_fn = self.filename.split(\"/exp\")[0] + \".tar\"\n\n try:\n if op.exists(tar_fn):\n if tar.is_tarfile(tar_fn):\n tarfile = tar.open(name=tar_fn)\n\n #search for name first? or just try to extract it ... just extract ... if not there it will throw\n #an exception and it will be trapped\n #todo: if the naming of the path becomes irregular\n #todo: then substring search for the \"exp01/virus/multi_xxx.fits\" part (should still be exactly one match)\n #todo: and return the entire string in which it matches as the fits_fn\n #fqdn = tarfile.getnames() # list of all conents (as full paths) includes directories\n\n # remember, no leading '/' in tarfile contents\n # fits_fn = \"exp\" + self.filename.split(\"/exp\")[1]\n # i.e. = \"exp01/virus/multi_038_096_014_RU.fits\"\n\n fits_fn = \"virus\" + self.filename.split(\"/virus/virus\")[1]\n # ie. = \"virus0000001/exp01/virus/multi_038_096_014_RU.fits\"\n\n file = tarfile.extractfile(fits_fn)\n # remember do not close the tarfile until we are done\n else:\n log.info(\"Could not open tarfile:fits (%s: %s)\" %(tar_fn,fits_fn))\n\n except:\n log.error(\"Error. Could not open tarfile:fits (%s: %s)\" %(tar_fn,fits_fn), exc_info=True)\n tarfile = None\n file=None\n\n if file == None:\n log.error(\"Error. FITS file does not exist: \" + self.filename)\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n\n return None\n else:\n file = self.filename\n\n try:\n log.info(\"Loading %s ...\" %self.filename)\n f = pyfits.open(file) #file maybe a file name or a .tar file object\n except:\n log.error(\"could not open file \" + self.filename, exc_info=True)\n\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n return None\n\n try:\n #build idx\n #the position of each extention within the multi-frame panacea FITS is not fixed,\n #so need to build the index (dictionary) for each one we load\n hdu_idx = {}\n for i in range(len(f)):\n try:\n if f[i].header['EXTNAME'] in hdu_idx:\n log.warning(\"WARNING! Duplicate frame 'EXTNAME' found. ['%s'] at index %d and %d in file: %s\"\n %(f[i].header['EXTNAME'],hdu_idx[f[i].header['EXTNAME']], i,self.filename))\n else:\n hdu_idx[f[i].header['EXTNAME']] = i\n except:\n pass\n\n #use the cleaned image for display\n self.data = np.array(f[hdu_idx['clean_image']].data)\n self.data[np.isnan(self.data)] = 0.0 # clean up any NaNs\n\n if self.data.shape != (1032,1032):\n log.error(\"ERROR!! Unexpected data shape for [clean_image]. Expected (1032,1032), got (%d,%d)\" %(self.data.shape))\n\n #with the sky NOT subtracted\n try:\n self.data_sky = np.array(f[0].data)\n self.data_sky[np.isnan(self.data_sky)] = 0.0 # clean up any NaNs\n except: #error, but not fatal, just keep going\n log.error(\"Could not load sky NOT subtracted fits data from multi*fits\")\n\n if self.data_sky.shape != (1032,1032):\n log.error(\"ERROR!! Unexpected data shape for [0] (data_sky). Expected (1032,1032), got (%d,%d)\"\n %(self.data_sky.shape))\n\n\n #get error equivalent\n self.err_data = np.array(f[hdu_idx['error']].data)\n if self.err_data.shape != (1032, 1032):\n print(\"TEMPORARY!!! using [1] for ['error'] frame until name correctd.\")\n self.err_data = np.array(f[1].data)\n\n self.err_data[np.isnan(self.err_data)] = 0.0\n if self.err_data.shape != (1032,1032):\n log.error(\"ERROR!! Unexpected data shape for [error]. Expected (1032,1032), got (%d,%d)\"\n %(self.err_data.shape))\n\n #get fe equivalent\n self.fe_data = np.array(f[hdu_idx['sky_subtracted']].data)\n self.fe_data[np.isnan(self.fe_data)] = 0.0\n if self.fe_data.shape != (112,1032):\n log.error(\"ERROR!! Unexpected data shape for [sky_subtracted]. Expected (112,1032), got (%d,%d)\"\n %(self.fe_data.shape))\n\n # get fe equivalent (need also the matching wavelengths)\n self.wave_data = np.array(f[hdu_idx['wavelength']].data)\n self.wave_data[np.isnan(self.wave_data)] = 0.0\n if self.wave_data.shape != (112,1032):\n log.error(\"ERROR!! Unexpected data shape for [wavelength]. Expected (112,1032), got (%d,%d)\"\n %(self.wave_data.shape))\n\n self.trace_data = np.array(f[hdu_idx['trace']].data)\n self.trace_data[np.isnan(self.trace_data)] = 0.0\n if self.trace_data.shape != (112,1032):\n log.error(\"ERROR!! Unexpected data shape for [trace]. Expected (112,1032), got (%d,%d)\"\n %(self.trace_data.shape))\n\n self.fiber_to_fiber = np.array(f[hdu_idx['fiber_to_fiber']].data)\n self.fiber_to_fiber[np.isnan(self.fiber_to_fiber)]\n if self.fiber_to_fiber.shape != (112,1032):\n log.error(\"ERROR!! Unexpected data shape for [fiber_to_fiber]. Expected (112,1032), got (%d,%d)\"\n %(self.fiber_to_fiber.shape))\n\n #[0] = wavelength, [1] = empirical? [2] = expected or estimated?\n self.error_analysis = np.array(f[hdu_idx['error_analysis']].data)\n self.error_analysis[np.isnan(self.error_analysis)]\n if self.error_analysis.shape != (3,512):\n log.error(\"ERROR!! Unexpected data shape for [error_analysis]. Expected (3,512), got (%d,%d)\"\n %(self.error_analysis.shape))\n\n #note: (this is done by IFU in build_fibers for each fiber that is constructed)\n #closest thing to error is the error_analysis * fiber_to_fiber (for the fiber in question)\n #take spectra (\"clean image\") and divide by fiber_to_fiber for the fiber in question\n #note fiber to fiber is the deviation from the average of fibers\n #when getting the data for a fiber, need to interpolate the error_analysis to be on same grid\n # as the wave_data for that fiber and then do the multiply and divide as needed\n\n\n # get fiber centers\n # the fits representation is backward (with grid x,y: 1,112 and 2,112 (i.e at the top) == fiber 1))\n self.fiber_centers = np.array(f[hdu_idx['ifupos']].data)\n if self.fiber_centers.shape != (112, 2):\n log.error(\"ERROR!! Unexpected data shape for [ifupos]. Expected (112,2), got (%d,%d)\"\n % (self.fiber_centers.shape))\n\n #self.pixflat_data = np.array(f[hdu_idx['flat_image']].data)\n #self.pixflat_data[np.isnan(self.pixflat_data)] = 0.0\n\n self.panacea = True\n\n #most complete header in the raw image\n #todo: at some point in late 2017, the 'image' header was dropped ... as this becomes common,\n #todo: should stop trying to read the 'image' header and just always assume the 0th is PRIMARY?\n #todo: (is always TRUE ... or at least always after a re-reduction?)\n try:\n idx = hdu_idx['image']\n except:\n log.debug(\"[image] header not found. Will assume 0th header is the PRIMARY.\")\n idx = 0\n\n except:\n log.error(\"Cannot read fits header. Missing expected keywords. \" + self.filename, exc_info=True)\n self.okay = False\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n return\n\n try:\n self.tel_ra = float(f[idx].header['RA']) * 15.0 # header is in decimal hours\n self.tel_dec = float(f[idx].header['DEC']) # header is in decimal degs\n self.parangle = f[idx].header['PA']\n except:\n log.error(\"Non-fatal: Cannot translate RA and/or Dec from FITS format to degrees in \" + self.filename, exc_info=True)\n #might be okay, depeding on if the individual emission lines have the weighted RA and Dec Specified\n\n try:\n self.ifuid = str(f[idx].header['IFUSID']).zfill(3)\n self.ifuslot = str(f[idx].header['IFUSLOT']).zfill(3)\n self.specid = str(f[idx].header['SPECID']).zfill(3)\n self.amp = f[idx].header['AMP']\n self.side = f[idx].header['AMP'][0] #the L or R ... probably don't need this anyway\n #self.exptime = f[idx].header['EXPTIME']\n except:\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n\n log.error(\"Cannot read fits header. Missing expected keywords. Will attempt to pull from filename.\" + self.filename, exc_info=True)\n #try to get info from the filename\n self.parse_panacea_fits_name(self.filename)\n return\n\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n\n try:\n f.close()\n except:\n log.error(\"could not close file \" + self.filename, exc_info=True)\n\n return\n\n def parse_panacea_fits_name(self,name):\n if name is not None:\n if \"multi_\" in name: #multi_037_073_031_LL.fits\n toks = name.split(\"_\") #multi_fits_basename = \"multi_\" + self.specid + \"_\" + self.ifu_slot_id + \"_\" + self.ifu_id + \"_\"\n if len(toks) == 5:\n try:\n self.specid = toks[1].zfill(3)\n self.ifuslot = toks[2].zfill(3)\n self.ifuid = toks[3].zfill(3)\n self.amp = toks[4][0:2]\n self.side =toks[4][0]\n except:\n log.error(\"Cannot parse panaces fits filename: %s\" %name,exc_info=True)\n self.okay = False\n\n\n\n def cleanup(self):\n #todo: close fits handles, etc\n pass\n\n","sub_path":"hetdex_fits.py","file_name":"hetdex_fits.py","file_ext":"py","file_size_in_byte":18623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"396920325","text":"\n\nfrom xai.brain.wordbase.nouns._alliteration import _ALLITERATION\n\n#calss header\nclass _ALLITERATIONS(_ALLITERATION, ):\n\tdef __init__(self,): \n\t\t_ALLITERATION.__init__(self)\n\t\tself.name = \"ALLITERATIONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"alliteration\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_alliterations.py","file_name":"_alliterations.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300425488","text":"\"\"\"\nFunctions that aid definition of fourier transform processing.\n\"\"\"\n\nimport astropy.constants as constants\n\nfrom arl.data.data_models import *\nfrom arl.data.parameters import *\nfrom arl.fourier_transforms.convolutional_gridding import anti_aliasing_calculate, w_kernel\nfrom arl.image.iterators import *\n\nlog = logging.getLogger(__name__)\n\n\ndef get_frequency_map(vis, im=None, **kwargs):\n \"\"\" Map channels from visibilities to image\n\n \"\"\"\n \n # Find the unique frequencies in the visibility\n ufrequency = numpy.unique(vis.frequency)\n vnchan = len(ufrequency)\n\n if im is None:\n spectral_mode = 'channel'\n vfrequencymap = get_rowmap(vis.frequency, ufrequency)\n assert min(vfrequencymap) >= 0, \"Invalid frequency map: visibility channel < 0\"\n\n\n elif im.data.shape[0] == 1 and vnchan >= 1:\n spectral_mode = 'mfs'\n vfrequencymap = numpy.zeros_like(vis.frequency, dtype='int')\n\n else:\n # We can map these to image channels\n v2im_map = im.wcs.sub(['spectral']).wcs_world2pix(ufrequency, 0)[0].astype('int')\n \n spectral_mode = 'channel'\n nrows = len(vis.frequency)\n row2vis = numpy.array(get_rowmap(vis.frequency, ufrequency))\n vfrequencymap = [v2im_map[row2vis[row]] for row in range(nrows)]\n \n assert min(vfrequencymap) >= 0, \"Invalid frequency map: image channel < 0\"\n assert max(vfrequencymap) < im.shape[0], \"Invalid frequency map: image channel > number image channels\"\n \n return spectral_mode, vfrequencymap\n\n\ndef get_polarisation_map(vis: Visibility, im: Image=None, **kwargs):\n \"\"\" Get the mapping of visibility polarisations to image polarisations\n \n \"\"\"\n if vis.polarisation_frame == im.polarisation_frame:\n if vis.polarisation_frame == PolarisationFrame('stokesI'):\n return \"stokesI->stokesI\", lambda pol: 0\n elif vis.polarisation_frame == PolarisationFrame('stokesIQUV'):\n return \"stokesIQUV->stokesIQUV\", lambda pol: pol\n\n return \"unknown\", lambda pol: pol\n\n\ndef get_rowmap(col, ucol=None):\n \"\"\" Map to unique cols\n \n :param col: Data column\n :param ucol: Unique values in col\n \"\"\"\n pdict = {}\n \n def phash(f):\n return numpy.round(f).astype('int')\n \n if ucol is None:\n ucol = numpy.unique(col)\n \n for i, f in enumerate(ucol):\n pdict[phash(f)] = i\n vmap = []\n for p in col:\n vmap.append(pdict[phash(p)])\n\n return vmap\n\n\ndef get_uvw_map(vis, im, **kwargs):\n \"\"\" Get the generators that map channels uvw to pixels\n\n \"\"\"\n # Transform parameters\n padding = get_parameter(kwargs, \"padding\", 2)\n \n # Model image information\n inchan, inpol, ny, nx = im.data.shape\n shape = (1, int(round(padding * ny)), int(round(padding * nx)))\n # UV sampling information\n uvwscale = numpy.zeros([3])\n uvwscale[0:2] = im.wcs.wcs.cdelt[0:2] * numpy.pi / 180.0\n assert uvwscale[0] != 0.0, \"Error in uv scaling\"\n fov = int(round(padding * nx)) * numpy.abs(uvwscale[0])\n \n vuvwmap = uvwscale * vis.uvw\n uvw_mode = \"2d\"\n \n return uvw_mode, shape, padding, vuvwmap\n\n\ndef standard_kernel_list(vis, shape, oversampling=8, support=3):\n \"\"\"Return a lambda function to calculate the standard visibility kernel\n\n :param vis: visibility\n :param shape: tuple with 2D shape of grid\n :param oversampling: Oversampling factor\n :param support: Support of kernel\n :returns: Function to look up gridding kernel\n \"\"\"\n return [anti_aliasing_calculate(shape, oversampling, support)[1]]\n\n\ndef w_kernel_list(vis, shape, fov, oversampling=4, wstep=100.0, npixel_kernel=16):\n \"\"\"Return a generator for the w kernel for each row\n\n This function is called once. It uses an LRU cache to hold the convolution kernels. As a result,\n initially progress is slow as the cache is filled. Then it speeds up.\n\n :param vis: visibility\n :param shape: tuple with 2D shape of grid\n :param fov: Field of view in radians\n :param oversampling: Oversampling factor\n :param wstep: Step in w between cached functions\n :returns: Function to look up gridding kernel as function of row, and cache\n \"\"\"\n wmax = numpy.max(numpy.abs(vis.w))\n log.debug(\"w_kernel_list: Maximum w = %.1f , step is %.1f wavelengths\" % (wmax, wstep))\n \n def digitise_w(w):\n return numpy.round(w / wstep).astype('int')\n \n # Use a dictionary but look at performance\n kernels = {}\n wint_list = numpy.unique(digitise_w(vis.w))\n for wint in wint_list:\n kernels[wint] = w_kernel(field_of_view=fov, w=wstep * wint, npixel_farfield=shape[0],\n npixel_kernel=npixel_kernel, kernel_oversampling=oversampling)\n # We will return a generator that can be instantiated at the last moment. The memory for\n # the kernels is needed but the pointer per row can be deferred.\n w_kernels = (kernels[digitise_w(w)] for w in vis.w)\n \n return w_kernels\n\n\ndef get_kernel_list(vis: Visibility, im, **kwargs):\n \"\"\"Get the list of kernels, one per visibility\n \n \"\"\"\n \n shape = im.data.shape\n npixel = shape[3]\n cellsize = numpy.pi * im.wcs.wcs.cdelt[1] / 180.0\n \n kernelname = get_parameter(kwargs, \"kernel\", \"2d\")\n oversampling = get_parameter(kwargs, \"oversampling\", 8)\n padding = get_parameter(kwargs, \"padding\", 2)\n \n gcf, _ = anti_aliasing_calculate((padding * npixel, padding * npixel), oversampling)\n\n wabsmax = numpy.max(numpy.abs(vis.w))\n if kernelname == 'wprojection' and wabsmax > 0.0:\n \n # wprojection needs a lot of commentary!\n log.debug(\"get_kernel_list: Using wprojection kernel\")\n \n # The field of view must be as padded!\n fov = cellsize * npixel * padding\n r_f = (cellsize * npixel / 2) ** 2 / abs(cellsize)\n log.debug(\"get_kernel_list: Fresnel number = %f\" % (r_f))\n delA = get_parameter(kwargs, 'wloss', 0.02)\n \n advice = advise_wide_field(vis, delA)\n wstep = get_parameter(kwargs, \"wstep\", advice['w_sampling_primary_beam'])\n \n log.debug(\"get_kernel_list: Using w projection with wstep = %f\" % (wstep))\n \n # Now calculate the maximum support for the w kernel\n npixel_kernel = get_parameter(kwargs, \"kernelwidth\", (2 * int(round(numpy.sin(0.5 * fov) * npixel/4.0))))\n assert npixel_kernel % 2 == 0\n log.debug(\"get_kernel_list: Maximum w kernel full width = %d pixels\" % (npixel_kernel))\n kernel_list = w_kernel_list(vis, (npixel, npixel), fov, wstep=wstep,\n npixel_kernel=npixel_kernel, oversampling=oversampling)\n else:\n kernelname = '2d'\n kernel_list = standard_kernel_list(vis, (padding * npixel, padding * npixel), oversampling=8, support=3)\n \n return kernelname, gcf, kernel_list\n\ndef advise_wide_field(vis, delA=0.02, oversampling_synthesised_beam=3.0, guard_band_image=6.0, facets=1.0):\n \"\"\" Advise on parameters for wide field imaging.\n \n For example::\n \n advice = advise_wide_field(vis, delA)\n wstep = get_parameter(kwargs, \"wstep\", advice['w_sampling_primary_beam'])\n\n \n :param vis:\n :param delA: Allowed coherence loss (def: 0.02)\n :param oversampling_synthesised_beam: Oversampling of the synthesized beam (def: 3.0)\n :param guard_band_image: Number of primary beam half-widths-to-half-maximum to image (def: 6)\n :returns: dict of advice\n \"\"\"\n maximum_baseline = numpy.max(numpy.abs(vis.uvw)) # Wavelengths\n log.info(\"advise_wide_field: Maximum baseline %.1f (wavelengths)\" % (maximum_baseline))\n \n diameter = numpy.min(vis.configuration.diameter)\n log.info(\"advise_wide_field: Station/antenna diameter %.1f (meters)\" % (diameter))\n\n wavelength = constants.c.to('m/s').value / numpy.min(vis.frequency)\n log.info(\"advise_wide_field: Maximum wavelength %.3f (meters)\" %(wavelength))\n\n primary_beam_fov = wavelength / diameter\n log.info(\"advise_wide_field: Primary beam %s\" % (rad_and_deg(primary_beam_fov)))\n\n image_fov = primary_beam_fov * guard_band_image\n log.info(\"advise_wide_field: Image field of view %s\" % (rad_and_deg(image_fov)))\n\n facet_fov = primary_beam_fov * guard_band_image / facets\n log.info(\"advise_wide_field: Facet field of view %s\" % (rad_and_deg(facet_fov)))\n\n synthesized_beam = 1.0 / (maximum_baseline)\n log.info(\"advise_wide_field: Synthesized beam %s\" % (rad_and_deg(synthesized_beam)))\n\n cellsize = synthesized_beam/oversampling_synthesised_beam\n log.info(\"advise_wide_field: Cellsize %s\" % (rad_and_deg(cellsize)))\n\n npixels = int(round(image_fov/cellsize))\n log.info(\"advice_wide_field: Npixels per side = %d\" % (npixels))\n\n # Following equation is from Cornwell, Humphreys, and Voronkov (2012) (equation 24)\n # We will assume that the constraint holds at one quarter the entire FOV i.e. that\n # the full field of view includes the entire primary beam\n\n w_sampling_image = numpy.sqrt(2.0 * delA) / (numpy.pi * image_fov ** 2)\n log.info(\"advice_wide_field: W sampling for full image = %.1f (wavelengths)\" % (w_sampling_image))\n\n w_sampling_facet = numpy.sqrt(2.0 * delA) / (numpy.pi * facet_fov ** 2)\n log.info(\"advice_wide_field: W sampling for facet = %.1f (wavelengths)\" % (w_sampling_image))\n\n w_sampling_primary_beam = numpy.sqrt(2.0 * delA) / (numpy.pi * primary_beam_fov ** 2)\n log.info(\"advice_wide_field: W sampling for primary beam = %.1f (wavelengths)\" % (w_sampling_primary_beam))\n\n time_sampling_image = 86400.0 * w_sampling_image / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Time sampling for full image = %.1f (s)\" % (time_sampling_image))\n\n time_sampling_facet = 86400.0 * w_sampling_facet / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Time sampling for facet = %.1f (s)\" % (time_sampling_facet))\n\n time_sampling_primary_beam = 86400.0 * w_sampling_primary_beam / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Time sampling for primary beam = %.1f (s)\" % (time_sampling_primary_beam))\n\n freq_sampling_image = numpy.max(vis.frequency) * w_sampling_image / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Frequency sampling for full image = %.1f (Hz)\" % (freq_sampling_image))\n\n freq_sampling_facet = numpy.max(vis.frequency) * w_sampling_facet / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Frequency sampling for facet = %.1f (Hz)\" % (freq_sampling_facet))\n\n freq_sampling_primary_beam = numpy.max(vis.frequency) * w_sampling_primary_beam / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Frequency sampling for primary beam = %.1f (Hz)\" % (freq_sampling_primary_beam))\n\n return locals()\n\ndef rad_and_deg(x):\n \"\"\" Stringify x in radian and degress forms\n \n \"\"\"\n return \"%.6f (rad) %.3f (deg)\" % (x, 180.0 * x / numpy.pi)\n\n","sub_path":"arl/fourier_transforms/ftprocessor_params.py","file_name":"ftprocessor_params.py","file_ext":"py","file_size_in_byte":10950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550558852","text":"t=int(input())\nfor test in range(t):\n string, S = input().split()\n S = int(S)\n A = [int(i) for i in string]\n length = len(A)\n array = [0] * (length + 1)\n summm = total = 0\n\n for i in range(length):\n summm += A[i]\n if summm >= S:\n total += array[summm - S]\n if summm == S:\n total += 1\n array[summm] += 1\n print(total)","sub_path":"Code/CodeRecords/2617/60785/276684.py","file_name":"276684.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119544928","text":"# encoding: utf-8\n\nimport os\nfrom gvsig.libs.formpanel import FormPanel\nfrom javax.swing.table import DefaultTableModel\nfrom javax.swing import JTable\nfrom javax.swing import SwingConstants\nfrom org.gvsig.app import ApplicationLocator\nfrom gvsig import commonsdialog\nfrom studentscreator import StudentsCreatorPanel\nfrom studentsupdater import StudentsUpdaterPanel\nfrom studentsdeleter import StudentsDeleterPanel\n\nclass StudentsEditorPanel(FormPanel):\n \n def __init__(self):\n FormPanel.__init__(self, os.path.join(os.path.dirname(__file__), \"studentseditor.xml\"))\n self.setPreferredSize(646, 285)\n tableModel = DefaultTableModel(0, 3)\n self.tableStudents.setModel(tableModel)\n self.tableStudents.getColumnModel().getColumn(0).setHeaderValue(\"Id\")\n self.tableStudents.getColumnModel().getColumn(0).setPreferredWidth(154)\n self.tableStudents.getColumnModel().getColumn(1).setHeaderValue(\"Password\")\n self.tableStudents.getColumnModel().getColumn(1).setPreferredWidth(154)\n self.tableStudents.getColumnModel().getColumn(2).setHeaderValue(\"Name\")\n self.tableStudents.getColumnModel().getColumn(2).setPreferredWidth(305)\n self.tableStudents.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)\n self.tableStudents.getTableHeader().getDefaultRenderer().setHorizontalAlignment(SwingConstants.CENTER)\n self.tableStudents.getTableHeader().setResizingAllowed(0)\n self.tableStudents.getTableHeader().setReorderingAllowed(0)\n self.loadStudents()\n \n def btnCreate_click(self, *args):\n create = commonsdialog.confirmDialog(\"Do you want to create students?\", \"Create\", commonsdialog.YES_NO, commonsdialog.QUESTION)\n if create == 0:\n studentsCreatorPanel = StudentsCreatorPanel()\n studentsCreatorPanel.showWindow(\"Create\")\n \n def btnUpdate_click(self, *args):\n rowCount = self.tableStudents.getRowCount()\n if rowCount != 0:\n update = commonsdialog.confirmDialog(\"Do you want to update students?\", \"Update\", commonsdialog.YES_NO, commonsdialog.QUESTION)\n if update == 0:\n studentsUpdaterPanel = StudentsUpdaterPanel()\n studentsUpdaterPanel.showWindow(\"Update\")\n else:\n commonsdialog.msgbox(\"Zero students!\", \"Update\", commonsdialog.IDEA)\n \n def btnDelete_click(self, *args):\n rowCount = self.tableStudents.getRowCount()\n if rowCount != 0:\n delete = commonsdialog.confirmDialog(\"Do you want to delete students?\", \"Delete\", commonsdialog.YES_NO, commonsdialog.QUESTION)\n if delete == 0:\n studentsDeleterPanel = StudentsDeleterPanel()\n studentsDeleterPanel.showWindow(\"Delete\")\n else:\n commonsdialog.msgbox(\"Zero students!\", \"Delete\", commonsdialog.IDEA)\n \n def btnExit_click(self, *args):\n exit = commonsdialog.confirmDialog(\"Do you want to exit?\", \"Exit\", commonsdialog.YES_NO, commonsdialog.QUESTION)\n if exit == 0:\n self.hide()\n \n def loadStudents(self):\n studentsFilePath = os.path.join(os.path.dirname(__file__), \"..\", \"data\", \"students.dbf\")\n store = self.loadDbf(studentsFilePath)\n features = store.features()\n tableModel = self.tableStudents.getModel()\n for feature in features:\n row = [feature.get(\"ID\"), feature.get(\"PASSWORD\"), feature.get(\"NAME\")]\n tableModel.addRow(row)\n features.dispose()\n store.dispose()\n \n @staticmethod\n def loadDbf(dbfFilePath):\n manager = ApplicationLocator.getManager()\n datamanager = manager.getDataManager()\n storeparameters = datamanager.createStoreParameters(\"DBF\")\n storeparameters.setDynValue(\"DbfFile\", dbfFilePath)\n store = datamanager.openStore(\"DBF\", storeparameters)\n return store\n\ndef main(*args):\n pass\n '''\n # testing\n studentsEditorPanel = StudentsEditorPanel()\n studentsEditorPanel.showWindow(\"Testing panel\")\n '''","sub_path":"GSoC_2017/EducationalGames/Games/editors/studentseditor.py","file_name":"studentseditor.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"227185992","text":"from collections import namedtuple\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport pdb\n\nfrom parse_path import constituency_path, dependency_path\ndp = dependency_path()\ncp = constituency_path()\ndef convert_mask_index(masks):\n '''\n Find the indice of none zeros values in masks, namely the target indice\n '''\n target_indice = []\n for mask in masks:\n indice = torch.nonzero(mask == 1).squeeze(1).cpu().numpy()\n target_indice.append(indice)\n return target_indice\n\ndef get_dependency_weight(tokens, targets, max_len):\n '''\n Dependency weight\n tokens: texts\n max_len: max length of texts\n '''\n weights = np.zeros([len(tokens), max_len])\n for i, token in enumerate(tokens):\n try:\n graph = dp.build_graph(token)\n mat = dp.compute_node_distance(graph, max_len)\n except:\n print('Error!!!!!!!!!!!!!!!!!!')\n print(text)\n\n try:\n max_w, _, _ = dp.compute_soft_targets_weights(mat, targets[i])\n weights[i, :len(max_w)] = max_w\n except:\n print('text process error')\n print(text, targets[i])\n break\n return weights\n\ndef get_context_weight(texts, targets, max_len):\n '''\n Constituency weight\n '''\n weights = np.zeros([len(texts), max_len])\n for i, token in enumerate(texts):\n #print('Original word num')\n #print(len(token))\n #text = ' '.join(token)#Connect them into a string\n #stanford nlp cannot identify the abbreviations ending with '.' in the sentences\n\n try:\n max_w, min_w, a_v = cp.proceed(token, targets[i])\n weights[i, :len(max_w)] = max_w\n except Exception as e:\n print(e)\n print(token, targets[i])\n return weights\n\ndef get_target_emb(sent_vec, masks, is_average=True):\n '''\n '''\n batch_size, max_len, embed_dim = sent_vec.size()\n masks = masks.type_as(sent_vec)\n masks = masks.expand(embed_dim, batch_size, max_len)\n masks = masks.transpose(0, 1).transpose(1, 2)#The same size as sentence vector\n target_emb = sent_vec * masks\n if is_average:\n target_emb_avg = torch.sum(target_emb, 1)/torch.sum(masks, 1)#Batch_size*embedding\n return target_emb_avg\n return target_emb\n\ndef to_scalar(var):\n # returns a python float\n return var.view(-1).data.tolist()[0]\n\ndef argmax(vec):\n # vec is only 1d vec\n # return the argmax as a python int\n _, idx = torch.max(vec, 0)\n return to_scalar(idx)\n\n# the input is 2d dim tensor\n# output 1d tensor\ndef argmax_m(mat):\n ret_v, ret_ind = [], []\n m, n = mat.size()\n for i in range(m):\n ind_ = argmax(mat[i])\n ret_ind.append(ind_)\n ret_v.append(mat[i][ind_])\n if type(ret_v[0]) == Variable or type(ret_v[0]) == torch.Tensor:\n return ret_ind, torch.stack(ret_v)\n else:\n return ret_ind, torch.Tensor(ret_v)\n\n# Compute log sum exp in a numerically stable way for the forward algorithm\n# vec is n * n, norm in row\ndef log_sum_exp_m(mat):\n row, column = mat.size()\n ret_l = []\n for i in range(row):\n vec = mat[i]\n max_score = vec[argmax(vec)]\n max_score_broadcast = max_score.view( -1).expand(1, vec.size()[0])\n ret_l.append( max_score + \\\n torch.log(torch.sum(torch.exp(vec - max_score_broadcast))))\n return torch.stack(ret_l)\n\ndef log_sum_exp(vec_list):\n tmp_mat = torch.stack(vec_list, 0)\n m,n = tmp_mat.size()\n # value may be nan because of gradient explosion\n try:\n max_score = torch.max(tmp_mat)\n except:\n pdb.set_trace()\n max_expand = max_score.expand(m, n)\n max_ex_v = max_score.expand(1, n)\n # sum along dim 0\n ret_val = max_ex_v + torch.log(torch.sum(torch.exp(tmp_mat - max_expand), 0))\n return ret_val\n\n# vec1 and vec2 both 1d tensor\n# return 1d tensor\ndef add_broad(vec1, vec2):\n s_ = vec1.size()[0]\n vec1 = vec1.expand(3, s_).transpose(0,1)\n vec2 = vec2.expand(s_, 3)\n new_vec = vec1 + vec2\n return new_vec.view(-1)\n\n# transform a list to 1d vec\ndef to_1d(vec_list):\n ret_v = vec_list[0].clone()\n v_l = len(vec_list)\n for i in range(1, v_l):\n ret_v = add_broad(ret_v, vec_list[i])\n return ret_v\n\ndef to_ind(num, logit):\n ret_l = []\n for i in reversed(range(logit)):\n tmp = num / 3 ** i\n num = num - tmp * 3 ** i\n ret_l.append(tmp)\n return list(reversed(ret_l))\n\ndef create_empty_var(if_gpu):\n if if_gpu:\n loss = Variable(torch.Tensor([0]).cuda())\n else:\n loss = Variable(torch.Tensor([0])) \n return loss","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"253680965","text":"# -*- coding: utf-8 -*-\nfrom distutils.core import setup\nfrom setuptools import find_packages\n\nwith open('docs/requirements.txt') as f:\n required = f.read().splitlines()\n\nsetup(\n name='tango-happenings',\n version='0.7.2',\n author=u'Tim Baxter',\n author_email='mail.baxter@gmail.com',\n url='https://github.com/tBaxter/django-happenings',\n license='LICENSE',\n description='Reusable Django events and calendaring.',\n long_description=open('README.md').read(),\n packages=find_packages(),\n install_requires=required,\n zip_safe=False,\n include_package_data=True,\n dependency_links = [\n 'http://github.com/tBaxter/vobject/tarball/master#egg=vobject',\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"434850776","text":"\"\"\"\n filename: bieberhash.py\n problem: using hash tables and handling collisions\n author: Elijah Kliot\ndescription: reads a .txt file with patron names and tabs and then\n populates a hash table corresponding to their seats\n and tab amounts\n\"\"\"\n\nfrom hashtable import *\n\ndef create_bills( file, cap ):\n \"\"\"\n simulates the seating and billing of concert patrons\n using a hash table\n\n file -- .txt to be read with patron names and tabs in format:\n {str} ${int}\n cap -- the maximum seating capacity of the concert\n\n returns None\n \"\"\"\n cap = int( cap )\n bills = createHashTable( cap )\n txt = open( file )\n print( \"YARR, WELCOME.\\n\" )\n \n for line in txt:\n s = line.split()\n name = s[ 0 ]\n tab = int( s[ 1 ][ 1:: ] )\n\n if bills.size > cap:\n print( \"THAR BE NOT ENOUGH SEATS, CAP'N\" )\n quit()\n\n if has( bills, name ):\n print( \"FOUND YA,\", name + \", AT SEAT NUMBER\", indexOf( bills, name ) )\n cur = get( bills, name )\n print( \"YA GOT\", cur, \"DUBLOONS ON YER TAB\" )\n print( \"AND NOW YA GOT\", tab, \"MORE, FER A TOTAL OF\",\n ( cur + tab ), \"DUBLOONS\\n\" )\n put( bills, name, cur + tab )\n\n else:\n print( name + \", YER PRIMARY SEAT NUMBER BE\", primHash( name, cap ),\n \"AND YER SECONDARY SEAT NUMBER BE\", secHash( name, cap ) )\n\n if bills.table[ primHash( name, cap ) ] == None:\n put( bills, name, tab )\n print( \"YA'VE BEEN SEATED,\", name + \", AT SEAT NUMBER\",\n indexOf( bills, name ), \"AND YER TAB IS FER\", tab, \"DUBLOONS\\n\" )\n\n else:\n seat = primHash( name, cap )\n occu = bills.table[ seat ].key\n print( \"IT SEEMS YER PRIMARY SEAT,\", str( seat ) + \", AIN'T VACANT,\",\n name + \". \\nWE'LL BE BOOTIN'\", occu, \"TA THEIR SECONDARY SEAT AT SEAT\",\n str( secHash( occu, cap ) ) + \". \\nMEANWHILE, TAKE A SEAT AT\",\n str( seat ), \"AND YER TAB IS\", tab, \"DUBLOONS.\\n\" )\n put( bills, name, tab )\n\n print( \"\\n++++++\\nYARR HARR FIDDLE DEE DEE\\nDO WHAT YA WANT 'CAUSE A PIRATE IS FREE\\n++++++\",\n \"\\n\\n\\nTH' CONCERT IS OVER, ALL YOU BETTER PAY YER TABS.\" )\n print( \"NOW LET'S SEE WHO OWES WOT:\\n\" )\n\n for pat in bills.table:\n if pat != None:\n name = pat.key\n seat = indexOf( bills, name )\n tab = pat.value\n print( name + \", YER IN SEAT NUMBER\", seat, \"AND YA OWE\", tab, \"DUBLOONS\" )\n\n print( \"\\nNOW GET OUT, YA BARNACLE-LICKING MONGRELS\\n\\n\\n\" )\n print( HashTableToStr( bills ) ) #plain-ish english output\n\ndef main():\n \"\"\"\n prompts for concert seating capacity and text file\n then runs simulation\n\n returns None\n \"\"\"\n size = input( \"Size of hash table: \" )\n## size = 100\n file = input( \"Filename: \" )\n## file = \"test.txt\"\n create_bills( file, size )\n\nmain()\n","sub_path":"Labs/LabI [100]/bieberhash.py","file_name":"bieberhash.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"306722471","text":"# %load tmax.py\r\nimport os\r\nfrom matplotlib import pyplot as plt\r\nimport cv2\r\nimport numpy as np\r\nfrom scipy.linalg import circulant\r\nfrom scipy.linalg import solve\r\nfrom scipy import signal\r\nfrom BaselineRemoval import BaselineRemoval\r\nimport copy\r\nfrom scipy.signal import find_peaks\r\nfrom skimage import data, filters\r\nfrom skimage import transform, exposure\r\n\r\n\r\n# Compute IRF:\r\ndef sparse_matrix(matrix_array):\r\n # matrix_array_c = circulant(matrix_array)\r\n matrix_c_list = matrix_array.tolist()\r\n\r\n matrix_sparse = np.zeros(shape=matrix_array.shape)\r\n n1 = 1\r\n for r in matrix_c_list:\r\n n2 = 1\r\n for i in r:\r\n if n2 > n1:\r\n matrix_sparse[n1 - 1, n2 - 1] = 0\r\n else:\r\n matrix_sparse[n1 - 1, n2 - 1] = i\r\n n2 += 1\r\n n1 += 1\r\n matrix_array_sparse = np.array(matrix_sparse)\r\n return matrix_array_sparse\r\n\r\n\r\ndef deconv_circulant_matrix_fourier(array_ct_value_aif, array_ct_value_tissue):\r\n \"\"\"\r\n aif * r = tissue,\r\n r = solve(aif, tissue)\r\n \"\"\"\r\n\r\n # residual_func = solve_circulant(array_ct_value_aif, array_ct_value_tissue, singular='lstsq')\r\n array_ct_value_aif = svd_denoising(array_ct_value_aif)\r\n residual_func = solve(circulant(array_ct_value_aif), array_ct_value_tissue)\r\n # residual_func = ifft(fft(array_ct_value_tissue) / fft(array_ct_value_aif))\r\n return residual_func\r\n\r\n\r\ndef svd_denoising(array_1d):\r\n \"\"\"\r\n \"\"\"\r\n matrix_cir = circulant(array_1d)\r\n matrix_cir_sparse = sparse_matrix(matrix_cir)\r\n u, sigma, vt = np.linalg.svd(matrix_cir_sparse)\r\n\r\n threshold = sigma[2] * 0.10\r\n\r\n sigma_denoised = np.zeros([len(array_1d), len(array_1d)])\r\n for i in range(len(array_1d)):\r\n if sigma[i] > threshold:\r\n sigma_denoised[i][i] = sigma[i]\r\n else:\r\n sigma_denoised[i][i] = 0\r\n\r\n matrix_cir_sparse_new = np.dot(np.dot(u, sigma_denoised), vt)\r\n array_1d_new = matrix_cir_sparse_new[:, 0]\r\n return array_1d_new\r\n\r\n\r\ndef deconv_nonparam_alg_tikhonov_svd(array_ct_value_aif, array_ct_value_tissue, lamdaa):\r\n \"\"\"Deconvolution-based / Non-parametric / Tikhonov SVD\r\n \"\"\"\r\n a = array_ct_value_aif\r\n c = array_ct_value_tissue\r\n\r\n a_pad = np.pad(a, (0, len(a)))\r\n c_pad = np.pad(c, (0, len(a)))\r\n\r\n I = np.identity(2 * len(a))\r\n\r\n A = circulant(a_pad)\r\n A_T = A.T\r\n\r\n block_cirMat = np.dot(A_T, A) + (lamdaa ** 2) * I\r\n b = solve(block_cirMat, A_T @ c_pad)\r\n\r\n b = b[0:len(a)]\r\n return b\r\n\r\n\r\ndef drive_singal(seq):\r\n power = np.zeros_like(seq)\r\n for i in range(len(power) - 1):\r\n res = seq[i + 1] - seq[i]\r\n if res > 0:\r\n power[i] = 1\r\n elif res == 0:\r\n power[i] = 0\r\n else:\r\n power[i] = -1\r\n\r\n for j in range(len(power) - 1):\r\n res = power[j]\r\n if j - 1 < 0:\r\n continue\r\n if res == 0 and power[j - 1] > 0:\r\n power[j] = 1\r\n elif res == 0 and power[j - 1] < 0:\r\n power[j] = -1\r\n return power\r\n\r\n\r\ndef find_valley_peak(seq):\r\n '''\r\n Input:\r\n signal sequence\r\n Output:\r\n power signal\r\n '''\r\n # take the derivative twice for getting movement trend\r\n fir_p = drive_singal(seq)\r\n sec_p = drive_singal(fir_p)\r\n return sec_p\r\n\r\n\r\ndef find_mostRight(seq, target=-1):\r\n max_idx = 0\r\n max_len = 0\r\n temp = 0\r\n for i in range(len(seq)):\r\n if seq[i] == target:\r\n temp += 1\r\n else:\r\n if temp > max_len:\r\n max_idx = i - 1\r\n max_len = temp\r\n temp = 0\r\n return max_idx\r\n\r\n\r\ndef find_longestLine(seq, target=-1):\r\n '''\r\n Input:\r\n Power signal\r\n Output:\r\n start and end valley around peak\r\n Descirbe:\r\n Shift windows, O(n)\r\n '''\r\n q_p = 0\r\n s_p = 0\r\n max_len = 0\r\n max_r = 0\r\n while s_p < len(seq):\r\n if seq[s_p] == target:\r\n q_p = s_p\r\n while q_p + 1 < len(seq) and seq[q_p + 1] == target:\r\n q_p += 1\r\n if (q_p - s_p) >= max_len:\r\n max_len = q_p - s_p\r\n max_r = q_p\r\n s_p = q_p + 1\r\n else:\r\n s_p += 1\r\n return max(max_r - max_len, 0), max_r\r\n\r\n\r\ndef truncate_tissue(signal_seq):\r\n '''\r\n input:\r\n signal sequence\r\n output:\r\n the left and right boundary indexes of peak\r\n '''\r\n # peak is -1, valley is 1\r\n sec_power = find_valley_peak(signal_seq) # power signal\r\n left_side = np.min(np.where(sec_power == 1))\r\n peak_p = np.argmax(signal_seq[left_side:]) + left_side\r\n\r\n _, right_side = find_longestLine(sec_power[peak_p:], target=-1) + peak_p\r\n\r\n return left_side, right_side\r\n\r\n\r\ndef truncate_aif(signal_seq):\r\n sec_power = find_valley_peak(signal_seq) # power signal\r\n left_side = np.min(np.where(sec_power == 1)) + 1 # get first 1 in power signal\r\n right_side = find_mostRight(sec_power)\r\n\r\n return left_side, right_side\r\n\r\n\r\ndef baseline_correction(signal_seq, name=\"tissue\"):\r\n '''\r\n input :\r\n signal sequence\r\n output :\r\n res : peak of signal\r\n base_signal: signal sequence without baseline shift\r\n\r\n '''\r\n base_signal = BaselineRemoval(signal_seq).IModPoly(2) # getting off baseline shift\r\n\r\n if name == \"tissue\":\r\n left_side, right_side = truncate_tissue(base_signal) # get the left and right boundary of peak indexes\r\n else:\r\n left_side, right_side = truncate_aif(base_signal)\r\n\r\n res = copy.deepcopy(base_signal)\r\n\r\n # --- pick peak ---\r\n res[:left_side] = 0\r\n res[right_side + 1:] = 0\r\n res[res < 0] = 0\r\n return res, base_signal\r\n\r\n\r\ndef filter_lp(data, cutoff_l, cutoff_h, ftype):\r\n \"\"\"\r\n low pass filter\r\n \"\"\"\r\n if ftype == \"lowpass\":\r\n b, a = signal.butter(9, cutoff_h, 'lowpass')\r\n elif ftype == \"bandpass\":\r\n b, a = signal.butter(7, [cutoff_l, cutoff_h], 'bandpass')\r\n filtedData = signal.filtfilt(b, a, data)\r\n return filtedData\r\n\r\n\r\ndef deconvolution(array_ct_value_aif, array_ct_value_tissue, show=False):\r\n cir_aif = circulant(array_ct_value_aif)\r\n inv_sig = regulSig(cir_aif)\r\n # print('Condition Num:',np.linalg.cond(inv_sig))\r\n irf = inv_sig @ array_ct_value_tissue\r\n if show:\r\n return irf, inv_sig[0]\r\n else:\r\n return irf\r\n\r\n\r\ndef regulSig(cir_mat):\r\n size = cir_mat.shape[0]\r\n peakposi = np.argmax(cir_mat[:, 0])\r\n cir_mat = np.linalg.inv(cir_mat)\r\n\r\n for ii in range(size):\r\n head = cir_mat[ii][:ii]\r\n tail = cir_mat[ii][ii:]\r\n cir_mat[ii, :] = np.r_[tail, head]\r\n ans = cir_mat.mean(0)\r\n\r\n peaks, properties = find_peaks(ans, prominence=0, width=[0, 2])\r\n left_bases = properties['left_bases']\r\n right_bases = properties['right_bases']\r\n idex = np.argmax(ans[peaks])\r\n\r\n left = left_bases[idex] if abs(left_bases[idex] - peakposi) < abs(right_bases[idex - 1] - peakposi) else \\\r\n right_bases[idex - 1]\r\n right = right_bases[idex] if abs(right_bases[idex] - peakposi) < abs(left_bases[idex + 1] - peakposi) else \\\r\n left_bases[idex + 1]\r\n\r\n leftpart = ans[:left]\r\n rightpart = ans[right:]\r\n midpart = ans[left: right]\r\n\r\n leftpart = cv2.GaussianBlur(leftpart, (1, 3), 0.7)\r\n rightpart = cv2.GaussianBlur(rightpart, (1, 3), 0.7)\r\n ans = np.r_[leftpart.squeeze(-1), midpart, rightpart.squeeze(-1)]\r\n return circulant(ans).T\r\n\r\n\r\ndef show_signal(mat, tissue):\r\n size = len(mat)\r\n plt.figure(figsize=(15, 7))\r\n col_num = 8\r\n row_num = np.ceil(size / col_num)\r\n for i in range(size):\r\n plt.subplot(row_num, col_num, i + 1)\r\n plt.plot(mat[i, :])\r\n plt.plot(tissue)\r\n plt.show()\r\n\r\n\r\ndef get_center(mask):\r\n index = np.where(mask != 0)\r\n center_y = int(index[0].mean())\r\n center_x = int(index[1].mean())\r\n return center_y, center_x\r\n\r\n\r\ndef extract_cbf(cbf_img, seed, brain_mask):\r\n '''\r\n Input:\r\n 1.the cbf image getting from Ais-system\r\n 2.seed is the location of maximal lesion value in irf image\r\n 3.brain_mask is the main matter of brain\r\n Output:\r\n lesion core extracted from cbf image\r\n\r\n Describe:\r\n 1. Enhence the contrast ratio of Input Image using Clahe.\r\n 2. Calculate the power image at x and y directions, and conbine together.\r\n 3. Enhencing the contrast ratio by expanding distribution between [0, 1] using log correction function, a * log(1 + x).\r\n 4. Split the power image into two parts, basin and ridge, using otsu or cluster.\r\n 5. Locating the target basin area through seed location, the ridge around target basin is contour of lesion in cbf image.\r\n 6. Mapping pixel location into distance from seed location.\r\n 7. Spliting brain into three parts, drop off the part farthest away from target area and select the part closest to seed location.\r\n\r\n '''\r\n h, w = cbf_img.shape\r\n x, y = seed\r\n aeh_img = exposure.equalize_adapthist(cbf_img / 255, kernel_size=None, clip_limit=0.01, nbins=256)\r\n sobel_x = cv2.Sobel(aeh_img, cv2.CV_64F, 1, 0, ksize=3)\r\n sobel_y = cv2.Sobel(aeh_img, cv2.CV_64F, 0, 1, ksize=3)\r\n sobel_xy = np.sqrt(sobel_x ** 2 + sobel_y ** 2)\r\n\r\n log_img = exposure.adjust_log(sobel_xy)\r\n otsu = filters.threshold_otsu(log_img[brain_mask != 0])\r\n log_img[log_img < otsu] = 0\r\n\r\n def distance(x1, y1, x2, y2):\r\n return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\r\n\r\n dist_map = np.zeros((h, w))\r\n for row in range(h):\r\n for col in range(w):\r\n if log_img[row, col] == 0:\r\n continue\r\n dist_map[row, col] = distance(x, y, col, row)\r\n\r\n maxV = dist_map.max()\r\n minV = dist_map.min()\r\n dist_map[dist_map != 0] = maxV - dist_map[dist_map != 0] # pixel inversion\r\n\r\n dist_map = ((dist_map - minV) / (maxV - minV)) * 255\r\n res = dist_map.copy()\r\n\r\n maxV = dist_map.max()\r\n minV = dist_map[dist_map != 0].min()\r\n\r\n middle = maxV - 1 * (maxV - minV) // 3\r\n print(maxV, minV, middle)\r\n\r\n otsu = filters.threshold_otsu(dist_map[dist_map > middle])\r\n dist_map[dist_map < otsu] = 0\r\n\r\n # kernel = np.ones((2,2), 'uint8')\r\n # lesion_dilation = cv2.dilate(dist_map, kernel, iterations = 1)\r\n # lesion_erode = cv2.erode(lesion_dilation, kernel, iterations = 1)\r\n # lesion_dilation = cv2.dilate(lesion_erode, kernel, iterations = 1)\r\n\r\n ret, mask = cv2.threshold(dist_map, 127, 255, 0)\r\n # mask = cv2.drawContours(mask, sys.mask_contours, 0, (255, 0, 0), 1)\r\n # cv2.rectangle(mask, (max(0, x - 2), max(y - 2, 0)),\r\n # (min(256, x + 2),min(256, y + 2)), (227,23,13), 1)\r\n\r\n plt.figure(figsize=(15, 7))\r\n plt.subplot(1, 5, 1)\r\n plt.imshow(cbf_img)\r\n plt.title('Input Image')\r\n plt.subplot(1, 5, 2)\r\n plt.imshow(sobel_xy)\r\n plt.title('Sobel Power Image')\r\n plt.subplot(1, 5, 3)\r\n plt.imshow(log_img)\r\n plt.title('Enhance Image with Log')\r\n plt.subplot(1, 5, 4)\r\n plt.imshow(res)\r\n plt.title('Distance Image')\r\n plt.subplot(1, 5, 5)\r\n plt.imshow(mask)\r\n plt.title('Output Image')\r\n plt.show()\r\n\r\n return dist_map\r\n\r\n","sub_path":"Project/AIS System/Computation.py","file_name":"Computation.py","file_ext":"py","file_size_in_byte":11286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"86612795","text":"import torch\r\nfrom torch import nn\r\n\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n\r\nclass TransformerTTSLoss(nn.Module):\r\n \"\"\" TransformerTTS Loss \"\"\"\r\n\r\n def __init__(self):\r\n super(TransformerTTSLoss, self).__init__()\r\n\r\n def forward(self, mel_output, mel_output_postnet, gate_predicted, mel_target, gate_target):\r\n\r\n mel_target.requires_grad = False\r\n mel_loss = torch.abs(mel_output - mel_target)\r\n mel_loss = torch.mean(mel_loss)\r\n\r\n mel_postnet_loss = torch.abs(mel_output_postnet - mel_target)\r\n mel_postnet_loss = torch.mean(mel_postnet_loss)\r\n\r\n gate_loss = nn.BCEWithLogitsLoss()(gate_predicted, gate_target)\r\n\r\n return mel_loss, mel_postnet_loss, gate_loss\r\n","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"135488387","text":"import feedparser\nimport requests\nfrom actstream import action\nfrom dateutil.parser import *\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.template.defaultfilters import slugify\nfrom django_bleach.models import BleachField\nfrom taggit.managers import TaggableManager\n\n\nclass Channel(models.Model):\n channel_title = models.CharField(max_length=100)\n channel_description = BleachField(allowed_tags=['', ], strip_tags=True)\n channel_image = models.URLField(blank=True)\n channel_border_color = models.TextField(default='grey')\n channel_slug = models.SlugField(unique=True)\n channel_rss_feed = models.URLField(null=True, blank=True)\n channel_tags = TaggableManager(blank=True)\n\n def __str__(self):\n return self.channel_title\n\n def get_absolute_url(self):\n return reverse(\"ChannelView\", kwargs={\"channel_slug\": self.channel_slug})\n\n\nclass Item(models.Model):\n channel = models.ForeignKey(Channel, on_delete=models.CASCADE)\n item_title = models.CharField(max_length=100)\n item_description = BleachField(allowed_tags=['p', 'b', 'i', 'em', 'strong', 'a'],\n allowed_attributes=['href', 'title', 'style', ], strip_tags=True)\n item_published = models.DateTimeField(null=True, blank=True)\n item_slug = models.SlugField(null=True, blank=True)\n item_image = models.URLField(blank=True)\n item_tags = TaggableManager(blank=True)\n\n @property\n def activity_actor_attr(self):\n return self.channel\n\n def __str__(self):\n return self.item_title\n\n def get_absolute_url(self):\n return reverse(\"ItemView\", kwargs={\"channel_slug\": self.channel.channel_slug, \"item_slug\": self.item_slug})\n\n def save(self, *args, **kwargs):\n super().save(*args, **kwargs)\n action.send(self.channel, verb='released', action_object=self, timestamp=self.item_published)\n\n\nclass FeedURL(models.Model):\n url = models.URLField()\n\n def save(self, *args, **kwargs):\n try:\n url = requests.get(self.url)\n feed = feedparser.parse(url.content)\n feed_channel_title = feed.feed.title\n\n if Channel.objects.filter(channel_title=feed_channel_title).exists():\n channel_title = Channel.objects.get(channel_title=feed_channel_title)\n for item in feed.entries:\n item_title = item.title\n if Item.objects.filter(item_title=item_title).exists():\n pass\n else:\n max_length = Item._meta.get_field('item_slug').max_length\n item_slug = slugify(item.title)[:max_length]\n item_description = item.description\n datestring = item.published\n item_published = parse(datestring)\n Item.objects.create(channel=channel_title, item_title=item_title,\n item_description=item_description, item_published=item_published,\n item_slug=item_slug)\n else:\n feed_channel_description = feed.feed.description\n feed_channel_image_url = feed.feed.image.href\n feed_channel_title_slug = slugify(feed.feed.title)\n Channel.objects.create(channel_title=feed_channel_title, channel_description=feed_channel_description,\n channel_image=feed_channel_image_url, channel_slug=feed_channel_title_slug)\n\n for item in feed.entries:\n item_title = item.title\n max_length = Item._meta.get_field('item_slug').max_length\n item_slug = slugify(item.title)[:max_length]\n item_description = item.description\n datestring = item.published\n item_published = parse(datestring)\n channel_title = Channel.objects.get(channel_title=feed_channel_title)\n Item.objects.create(channel=channel_title, item_title=item_title,\n item_description=item_description, item_published=item_published,\n item_slug=item_slug)\n\n super().save(*args, **kwargs)\n except:\n pass\n\n def __str__(self):\n return self.url\n\n\nimport threading\n\n\ndef getter():\n try:\n urls = FeedURL.objects.all()\n for rss in urls:\n url = requests.get(rss.url)\n feed = feedparser.parse(url.content)\n feed_channel_title = feed.feed.title\n channel_title = Channel.objects.get(channel_title=feed_channel_title)\n for item in feed.entries:\n item_title = item.title\n if Item.objects.filter(item_title=item_title).exists():\n pass\n else:\n max_length = Item._meta.get_field('item_slug').max_length\n item_slug = slugify(item.title)[:max_length]\n item_description = item.description\n datestring = item.published\n item_published = parse(datestring)\n Item.objects.create(channel=channel_title, item_title=item_title,\n item_description=item_description, item_published=item_published,\n item_slug=item_slug)\n except:\n pass\n threading.Timer((60 * 10), getter).start()\n\n # automatically get new episodes\n # getter()\n","sub_path":"feed/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"573703628","text":"#!/usr/bin/env python2\nfrom gimpfu import *\nimport os\nimport urllib2\nimport ssl\n\nlabel_colors = {\n 'Road': (0x40, 0x20, 0x20),\n 'Lanemarkings': (0xff, 0x00, 0x00),\n 'Undrivable': (0x80, 0x80, 0x60),\n 'Movable': (0x00, 0xff, 0x66),\n 'Mycar': (0xcc, 0x00, 0xff),\n}\n\n\ndef _find_mask_layer(image):\n mask_layer = None\n for layer in image.layers:\n if layer.name == 'mask':\n return layer\n\n\ndef _mask_file_name(image):\n fn = pdb.gimp_image_get_filename(image)\n return os.path.join(os.path.dirname(os.path.dirname(fn)), 'masks', os.path.basename(fn))\n\n\nrepo_url_base = 'https://github.com/commaai/comma10k/raw/master/masks/'\n\ndef _mask_file_url(image):\n fn = pdb.gimp_image_get_filename(image)\n return repo_url_base + os.path.basename(fn)\n\n\ndef _dowload_file(url, local_path, progress_text):\n pdb.gimp_progress_init(progress_text, None)\n try:\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n u = urllib2.urlopen(url, context=ctx)\n with open(local_path, 'wb') as f:\n meta = u.info()\n file_size = int(meta.getheaders(\"Content-Length\")[0])\n file_size_dl = 0\n block_sz = 4192\n while True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n file_size_dl += len(buffer)\n f.write(buffer)\n pdb.gimp_progress_update(file_size_dl * 100. / file_size)\n finally:\n pdb.gimp_progress_end()\n\n\t\ndef load_mask_file(image, drawable):\n mask_layer = _find_mask_layer(image)\n if mask_layer != None:\n gimp.message(\"Mask file already loaded\")\n return\n\n mask_layer = pdb.gimp_file_load_layer(image, _mask_file_name(image))\n mask_layer.opacity = 60.0\n mask_layer.name = 'mask'\n pdb.gimp_image_insert_layer(image, mask_layer, None, -1)\n\n\ndef save_mask_file(image, drawable):\n mask_layer = _find_mask_layer(image)\n if not mask_layer:\n gimp.message(\"Mask file not loaded yet\")\n return\n pdb.gimp_selection_none(image)\n mask_fn = _mask_file_name(image)\n pdb.file_png_save2(image, mask_layer, mask_fn, mask_fn, 0, 9, 0, 0, 0, 0, 0, 0, 0)\n pdb.gimp_image_remove_layer(mask_layer)\n load_mask_file(image, drawable)\n\n\ndef load_github_mask_file(image, drawable):\n layer_name = 'github mask'\n for layer in image.layers:\n if layer.name == layer_name:\n pdb.gimp_image_remove_layer(image, layer)\n break\n url = _mask_file_url(image)\n progress_text = 'Downloading mask for {}'.format(url.split('/')[-1])\n tmp_png_fn = pdb.gimp_temp_name('png')\n _dowload_file(url, tmp_png_fn, progress_text)\n if not os.path.exists(tmp_png_fn):\n pdb.gimp_message('Downloading from github failed.')\n return\n github_mask_layer = pdb.gimp_file_load_layer(image, tmp_png_fn)\n github_mask_layer.opacity = 90.0\n github_mask_layer.name = layer_name\n pdb.gimp_image_insert_layer(image, github_mask_layer, None, -1)\n github_mask_layer.visible = True\n mask_layer = _find_mask_layer(image)\n if mask_layer != None:\n mask_layer.opacity = 90.0\n return\n\n\ndef label_selected_pixels(image, drawable, category_name):\n mask_layer = _find_mask_layer(image)\n if not mask_layer:\n gimp.message(\"Mask file not loaded yet\")\n return\n if pdb.gimp_selection_is_empty(image):\n pdb.gimp_message(\"You must first select a region.\")\n return\n pdb.gimp_context_set_foreground(label_colors[category_name])\n pdb.gimp_edit_fill(mask_layer, 0)\n #pdb.gimp_selection_none(image)\n mask_layer.visible = True\n\n\nregister(\n \"comma10k_load_mask_file\",\n \"Load Mask File\",\n \"Load Mask File\",\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"<Image>/Comma10K/Load Mask File\",\n \"RGB*, GRAY*\",\n [],\n [],\n load_mask_file\n)\n\nregister(\n \"comma10k_save_mask_file\",\n \"Save Mask File\",\n \"Save Mask File\",\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"<Image>/Comma10K/Save Mask File\",\n \"RGB*, GRAY*\",\n [],\n [],\n save_mask_file\n)\n\nregister(\n \"comma10k_load_github_mask_file\",\n \"Load Github Mask File\",\n \"Load Github Mask File\",\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"<Image>/Comma10K/Load Old Mask from github\",\n \"RGB*, GRAY*\",\n [],\n [],\n load_github_mask_file\n)\n\n\nfor category_name in label_colors.keys():\n register(\n \"comma10k_set_foreground_color_%s\" % category_name,\n \"Set FColor to %s\" % category_name,\n \"Set FColor to %s\" % category_name,\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"<Image>/Comma10K/Set Foreground Color to/%s\" % category_name,\n \"RGB*, GRAY*\",\n [],\n [],\n lambda img, l, category_name=category_name: pdb.gimp_context_set_foreground(label_colors[category_name])\n )\n\n register(\n \"comma10k_label_selected_pixels_as_%s\" % category_name,\n \"Label selected pixels as %s\" % category_name,\n \"Label selected pixels as %s\" % category_name,\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"<Image>/Comma10K/Label Selected Pixels as/%s\" % category_name,\n \"RGB*, GRAY*\",\n [],\n [],\n lambda img, l, category_name=category_name: label_selected_pixels(img, l, category_name)\n )\n\nmain()\n","sub_path":"gimp_plugin/gimp_comma10k_helpers.py","file_name":"gimp_comma10k_helpers.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"520251358","text":"infile = open(\"fibo.hex\", \"r\")\noutfile = open(\"fibo\", \"w\")\n\nscale = 16 ## equals to hexadecimal\n\nnum_of_bits = 8\n\nfor line in infile:\n hex_string = line.strip()\n outfile.write(bin(int(hex_string, scale))[2:].zfill(num_of_bits))\n outfile.write(\"\\n\")\n\nprint(\"Worked\")\n\ninfile.close()\noutfile.close()\n","sub_path":"hextobin.py","file_name":"hextobin.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51110434","text":"#BOJ 2133 타일 채우기\n\nN = int(input())\n\ndpList = [0 for i in range(0,31)]\ndpList[0] = 1\ndpList[2] = 3\ndpList[4] = 11\n\nfor i in range(6, N+1,2):\n dpList[i] = dpList[i-2]*3\n for j in range(4, i+1, 2):\n dpList[i] += 2*dpList[i-j]\n\nif N % 2 == 1:\n print(0)\nelse:\n print(dpList[N])\n","sub_path":"Dynamic Programming/BOJ_2133_타일채우기.py","file_name":"BOJ_2133_타일채우기.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"597353863","text":"\ndef main():\n required = -1\n while required <= 0:\n required = int(input(\"Enter the number of items being shipped\"))\n itemCosts = [\"\"] * required\n totalCost = 0\n for i in range(0,required,1):\n print(\"Please enter cost of item:\", str(i+1))\n itemCosts[i] = int(input())\n totalCost += itemCosts[i]\n\n print(\"Number of items:\", required)\n for i in range(0,required,1):\n print(\"Price of item:\", itemCosts[i])\n\n if totalCost > 100:\n totalCost = totalCost * 0.9\n print(\"Total cost for shipping\", required, \"items is:\", totalCost)\n\nmain()\n\n\n\n\n\n","sub_path":"Prac_01/shippingCalculator.py","file_name":"shippingCalculator.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"362259065","text":"\"\"\"Local settings for use within Django app. Requires reload / rebuild to pick up for deploy.\"\"\"\nimport os\nfrom django.conf import settings\n\n# Default Settings Overrides\nSECRET_KEY = os.getenv('APP_SECRET_KEY', 'blergh')\nDEBUG = bool(os.getenv('APP_DEBUG_MODE', False))\nALLOWED_HOSTS = [\n 'localhost',\n '127.0.0.1',\n os.getenv('APP_HOST'),\n os.getenv('APP_FQDN')\n]\n\n# Deployment type\nCOMBINE_DEPLOYMENT = os.getenv('COMBINE_DEPLOYMENT', 'server')\n\n# Combine Install Location\nCOMBINE_INSTALL_PATH = os.getenv('COMBINE_INSTALL_PATH', '/opt/combine')\n\n# Combine Front-End\nAPP_HOST = os.getenv('APP_HOST', '127.0.0.1')\n\n# Spark Cluster Information\nSPARK_HOST = os.getenv('SPARK_HOST', '127.0.0.1')\nSPARK_PORT = int(os.getenv('SPARK_PORT', 8080))\n# if taken, will automatically increment +100 from here until open port is found\nSPARK_APPLICATION_ROOT_PORT = 4040\n\n# Spark tuning\nSPARK_MAX_WORKERS = int(os.getenv('SPARK_MAX_WORKERS', 1))\nJDBC_NUMPARTITIONS = int(os.getenv('JDBC_NUMPARTITIONS', 200))\nSPARK_REPARTITION = int(os.getenv('SPARK_REPARTITION', 200))\nTARGET_RECORDS_PER_PARTITION = int(os.getenv('TARGET_RECORDS_PER_PARTITION', 5000))\nMONGO_READ_PARTITION_SIZE_MB = int(os.getenv('MONGO_READ_PARTITION_SIZE_MB', 4))\n\n# Apache Livy settings\n'''\nCombine uses Livy to issue spark statements.\nLivy provides a stateless pattern for interacting with Spark, and by proxy, DPLA code.\n'''\nLIVY_HOST = os.getenv('LIVY_HOST', '127.0.0.1')\nLIVY_PORT = int(os.getenv('LIVY_PORT', 8998))\nLIVY_DEFAULT_SESSION_CONFIG = {\n 'kind':'pyspark',\n 'jars':[\n 'file:///combinelib/mysql.jar'\n ],\n 'files':[\n 'file://%s/core/spark/es.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/spark/jobs.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/spark/record_validation.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/spark/utils.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/spark/console.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/xml2kvp.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n ],\n\n # Spark conf overrides\n 'conf':{\n 'spark.ui.port': SPARK_APPLICATION_ROOT_PORT\n },\n}\n\n# Storage for avro files and other binary files\n'''\nMake sure to note file:// or hdfs:// prefix\n'''\nBINARY_STORAGE = os.getenv('BINARY_STORAGE', 'file:///home/combine/data/combine')\nWRITE_AVRO = bool(os.getenv('WRITE_AVRO', False))\n\n# ElasicSearch server\nES_HOST = os.getenv('ES_HOST', '127.0.0.1')\nINDEX_TO_ES = bool(os.getenv('INDEX_TO_ES', True))\n\n# ElasticSearch analysis\nCARDINALITY_PRECISION_THRESHOLD = int(os.getenv('CARDINALITY_PRECISION_THRESHOLD', 100))\nONE_PER_DOC_OFFSET = float(os.getenv('ONE_PER_DOC_OFFSET', 0.05))\n\n# Service Hub\nSERVICE_HUB_PREFIX = os.getenv('SERVICE_HUB_PREFIX', 'funcake--')\n\n# OAI Server\nOAI_RESPONSE_SIZE = int(os.getenv('OAI_RESPONSE_SIZE', 500))\nCOMBINE_OAI_IDENTIFIER = os.getenv('COMBINE_OAI_IDENTIFIER', 'oai:funnel_cake')\nMETADATA_PREFIXES = {\n 'mods':{\n 'schema':'http://www.loc.gov/standards/mods/v3/mods.xsd',\n 'namespace':'http://www.loc.gov/mods/v3'\n },\n 'oai_dc':{\n 'schema':'http://www.openarchives.org/OAI/2.0/oai_dc.xsd',\n 'namespace':'http://purl.org/dc/elements/1.1/'\n },\n 'dc':{\n 'schema':'http://www.openarchives.org/OAI/2.0/oai_dc.xsd',\n 'namespace':'http://purl.org/dc/elements/1.1/'\n },\n}\n\n# Database configurations for use in Spark context\nCOMBINE_DATABASE = {\n 'jdbc_url':os.getenv('MYSQL_JDBC', 'jdbc:mysql://%s:3306/combine' % settings.DATABASES['default']['HOST']),\n 'user':os.getenv('MYSQL_USER', settings.DATABASES['default']['USER']),\n 'password':os.getenv('MYSQL_PASSWORD', settings.DATABASES['default']['PASSWORD'])\n}\n\n# DPLA API\nDPLA_RECORD_MATCH_QUERY = bool(os.getenv('DPLA_RECORD_MATCH_QUERY', True))\nDPLA_API_KEY = os.getenv('DPLA_API_KEY', None)\n\n# AWS S3 Credentials\nAWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID', None)\nAWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY', None)\nDPLA_S3_BUCKET = os.getenv('DPLA_S3_BUCKET', 'dpla-provider-export')\n\n# Analysis Jobs Org and Record Group\n'''\nThis dictionary provides the name of the Organization and Record Group that\nAnalysis Jobs will be created under. Because Analysis jobs are extremely similar\nto other workflow jobs, but do not lend themselves towards the established\nOrganization --> Record Group --> Job hierarchy, this ensures they are treated\nsimilarily to other jobs, but skip the need for users to manually create these\nsomewhat unique Organization and Record Group.\n - it is recommended to make these names quite unique,\n to avoid clashing with user created Orgs and Record Groups\n - the Organization and Record Group names defined in ANALYSIS_JOBS_HIERARCHY\n will NOT show up in any Org or Record Group views or other workflows\n\t- it is quite normal, and perhaps encouraged, to leave these as the defaults\n'''\nANALYSIS_JOBS_HIERARCHY = {\n # suffix is md5 hash of 'AnalysisOrganization'\n 'organization':'AnalysisOrganizationf8ed4bfcefc4dbf87b588a5de9b7cc95',\n # suffix is md5 hash of 'AnalysisRecordGroup'\n 'record_group':'AnalysisRecordGroupf660bb4826bea8b63fd773d27d687cfd'\n}\n\n# Celery Configurations\nCELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL', 'redis://localhost:6379/0')\nCELERY_RESULT_BACKEND = os.getenv('CELERY_RESULT_BACKEND', 'redis://localhost:6379/0')\n\n# StateIO Configurations\n'''\nConfigurations used for exporting/importing \"states\" in Combine, including\nOrganizations, Record Groups, Jobs, Validation Scenarios, Transformation\nScenarios, etc. These can be large in size, and potentially helpful to\npreserve, so /tmp is not ideal here.\n'''\nSTATEIO_EXPORT_DIR = os.getenv('STATEIO_EXPORT_DIR', '/home/combine/data/combine/stateio/exports')\nSTATEIO_IMPORT_DIR = os.getenv('STATEIO_IMPORT_DIR', '/home/combine/data/combine/stateio/imports')\n\n# Mongo server\nMONGO_HOST = os.getenv('MONGO_HOST', '127.0.0.1')\n\n# overrides for DATABASE settings\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': os.getenv('MYSQL_NAME', 'combine'),\n 'USER': os.getenv('MYSQL_USER', 'combine'),\n 'PASSWORD': os.getenv('MYSQL_PASSWORD', 'combine'),\n 'HOST': os.getenv('MYSQL_HOST', '127.0.0.1'),\n 'PORT': int(os.getenv('MYSQL_PORT', 3306)),\n }\n}\n","sub_path":"combine/localsettings.py","file_name":"localsettings.py","file_ext":"py","file_size_in_byte":6360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643987027","text":"#!/usr/bin/python\n\nimport sqlite3\n\nimport sys\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python']\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python/lib/yaml/lib']\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python/lib/webob']\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python/lib/fancy_urllib']\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python/lib/django']\nsys.path += ['.']\n\nfrom google.appengine.datastore import entity_pb\nfrom google.appengine.api import datastore\n\nconn = sqlite3.connect('local_data/FacebookCachedObject.db', isolation_level=None)\ncursor = conn.cursor()\ncursor.execute('select id, value from result')\nfor entity_id, entity in cursor:\n entity_proto = entity_pb.EntityProto(contents=entity)\n e = datastore.Entity._FromPb(entity_proto)\n if str(entity_id).endswith('OBJ_EVENT'):\n real_id = str(entity_id).split(':')[-1]\n if 'json_data' in e:\n f = open('test_data/FacebookCachedObject/%s' % real_id, 'w')\n f.write(e['json_data'])\n f.close()\n","sub_path":"server/tools/dump_fbo_db.py","file_name":"dump_fbo_db.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464006214","text":"#! /usr/bin/ env python\n# -*- coding:utf-8 -*-\n\n\n\"\"\"\nipset 增删改\n\nmodify log:\n 2016-6-23:\n 1、新增ipv6的ipset\n\"\"\"\n\n\nimport os\nimport json\nfrom logging import getLogger\n\nfrom db.mysqlconnect import execute_sql\nfrom utils.mask_transition import exchange_mask\nfrom objectdefine.ip_range import get_ip\nfrom utils.logger_init import logger_init\n\n\nfrom IPy import IP\n\n\n\nLOGGER_PATH = '/usr/local/bluedon/log/ipset.log'\nLOGGER_NAME = 'IPSET'\n\nlogger_init(LOGGER_NAME, LOGGER_PATH, 'DEBUG')\n\n\ndef set_ipset(data, action='add', iptype='ipv4'):\n \"\"\" 设置ipset \"\"\"\n\n ipset_path = '/usr/local/sbin/ipset'\n cmd_ipset = {'delipset': '%s destroy %s',\n 'ipv4': '%s creat %s hash:net',\n 'ipv6': '%s creat %s hash:net family inet6',\n 'change_ipset': '%s %s %s %s'}\n\n # 创建ipset\n if action == 'del':\n ipset_cmd = cmd_ipset['delipset'] %(ipset_path, data['HideID'])\n elif action == 'add':\n ipset_cmd = cmd_ipset[iptype] %(ipset_path, data['HideID'])\n\n os.system(ipset_cmd)\n getLogger(LOGGER_NAME).debug(ipset_cmd)\n\n if action == 'del':\n return\n\n # 把ip添加到ipset中\n sip = str(data['sIP']).split(',')\n if len(sip) == 1:\n addr_sql = 'select * from m_tbaddress_list_scm where id=%s' %(sip[0])\n else:\n sip = tuple([int(item) for item in sip])\n addr_sql = 'select * from m_tbaddress_list_scm where id in %s' %(str(sip))\n results = execute_sql(addr_sql)\n for result in results:\n addr_list = ip_iprange(result)\n for addr in addr_list:\n cmd = cmd_ipset['change_ipset'] %(ipset_path, action,\n data['HideID'], addr)\n getLogger(LOGGER_NAME).debug(cmd)\n os.system(cmd)\n os.system(\"ipset save > /etc/ipset.conf\")\n #print data['HideID']\n\ndef ip_iprange(data):\n \"\"\"\n args:\n data: 记录集\n return:\n addr_list: ip列表\n \"\"\"\n\n addr_list = list()\n if data['sIPV'].lower() == 'ipv4':\n if str(data['sAddtype']).strip() == '1': # ip和掩码形式\n if data['sAddress'].endswith('.0'):\n if '.' not in data['sNetmask']:\n addr_list = ['%s/%s' %(data['sAddress'], data['sNetmask'])]\n else:\n addr_list = [IP('%s/%s' %(data['sAddress'], data['sNetmask']),\n make_net=True).strNormal(1)]\n else:\n addr_list = [data['sAddress']]\n elif str(data['sAddtype']).strip() == '2': # ip段\n iprange = '%s-%s' %(data['sAddress'], data['sNetmask'])\n addr_list = get_ip(iprange)\n else:\n addr_list = [data['sAddress']]\n return addr_list\n\ndef main(args):\n ipset_sql = 'select * from m_tbaddressgroup_scm'\n datas = execute_sql(ipset_sql)\n if not args in ['init', 'reboot']:\n return\n\n for data in datas:\n set_ipset(data, 'del', data['sGroupIPV'])\n\n if args == 'reboot':\n for data in datas:\n set_ipset(data, 'add', data['sGroupIPV'])\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) < 2:\n getLogger(LOGGER_NAME).debug('have more args! (eg: python -m objectdefine.set_ipgroup init/reboot)')\n else:\n main(sys.argv[1])\n","sub_path":"chuhuo_2.71/bluedon/scm/set_ipgroup.py","file_name":"set_ipgroup.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643897601","text":"from django import forms\nfrom messaging.models import Message\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field\nfrom crispy_forms.bootstrap import FormActions\n\nclass NewMessageForm(forms.ModelForm):\n helper = FormHelper()\n helper.form_tag = True\n helper.form_method = 'POST'\n helper.form_class = 'form-horizontal'\n helper.label_class = 'col-sm-4'\n helper.field_class = 'col-sm-8'\n helper.layout = Layout(\n Field('to_user',css_class='input-sm' ), \n Field('short_message',css_class='input-sm'),\n FormActions(Submit('Submit', 'Submit', css_class='btn-primary'))\n )\n class Meta:\n model = Message\n fields = ('short_message',\n 'to_user')","sub_path":"tinytotts/messaging/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286250117","text":"import inspect\nimport os\nimport re\nimport time\nfrom bs4 import BeautifulSoup as bs\nimport easygui\nimport pandas as pd\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\ndef get_chromedriver_path():\n # Get CWD and pass chromedriver to PATH env variable\n current_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))\n path_to_chromedriver = os.path.join(current_folder, 'chromedriver.exe')\n return path_to_chromedriver\n\n\nCHROME_PATH = get_chromedriver_path()\n\n\nclass FileLoader(object):\n\n def __init__(self, path):\n self.path = path\n self.output_dir = self.generate_output_dir()\n self.file = self.read_file()\n self.url_paths = self.parse_file()\n\n\n @property\n def url_search(self):\n return re.compile(r\"(http(s)?:\\/\\/.)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)\")\n\n def is_url(self, x):\n if not isinstance(x, str):\n return False\n if self.url_search.search(x):\n return True\n else:\n return False\n\n def generate_filepath(self, url):\n f = url.split(\"/\")[-1]\n f += \".html\"\n return os.path.join(self.output_dir, f)\n\n def read_file(self):\n file_ext = os.path.splitext(self.path)[1]\n if file_ext == '.csv':\n open_method = pd.read_csv\n elif file_ext == '.xls' or file_ext == '.xlsx':\n open_method = pd.read_excel\n else:\n open_method = None\n print(file_ext + \"Not supported\")\n return pd.DataFrame() # Returning an empty dataframe vs False required for truth value error from pandas\n df = open_method(self.path, header=None)\n df_ = df[[df.columns[0]]] # Drop all but first column\n del df\n col_name = df_.columns[0]\n df_.rename(columns={col_name: 'url'}, inplace=True)\n # Drop invalid URLs\n df_ = df_.loc[df_['url'].apply(lambda x: self.is_url(x))]\n df_['filepath'] = df_['url'].apply(lambda x: self.generate_filepath(x))\n return df_\n\n def parse_file(self):\n if self.file.empty:\n return []\n return dict(self.file[['url', 'filepath']].values.tolist())\n\n def generate_output_dir(self):\n cwd = os.getcwd()\n output_dir = os.path.join(cwd, 'pages_0')\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n return output_dir\n elif not os.listdir(output_dir):\n return output_dir\n else:\n counter = 1\n for i in range(1000):\n output_dir = os.path.join(cwd, 'pages_{}'.format(i))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n return output_dir\n elif not os.listdir(output_dir):\n return output_dir\n else:\n counter += 1\n\n\nclass page_status_complete(object):\n \"\"\"\n Expectation that document.readyState == 'complete'\n \"\"\"\n\n def __init__(self):\n pass\n\n def __call__(self, driver):\n page_status = driver.execute_script(\"return document.readyState\")\n if page_status == 'complete':\n return driver.page_source\n else:\n return False\n\n\nclass Nomad(object):\n\n def __init__(self, url_paths, driver_path, wait_time=30):\n self.url_paths = url_paths\n self.driver = webdriver.Chrome(executable_path=driver_path)\n self.wait_time = wait_time\n\n def add_message(self, message):\n\n \"\"\"\n Intended for displaying a message on the blank page on Chromedriver opens\n \"\"\"\n\n self.driver.execute_script(\"\"\"\n var header = document.createElement('h1'); \n var message = document.createTextNode('{}');\n header.appendChild(message);\n document.body.appendChild(header);\n \"\"\".format(message))\n\n def get_and_wait(self, url):\n self.driver.get(url)\n wait = WebDriverWait(self.driver, self.wait_time)\n page_ = wait.until(page_status_complete())\n return page_\n\n def save_page(self, soup_page, file_path):\n with open(file_path, \"wb+\") as html_file:\n html_file.write(soup_page.encode(\"utf-8\"))\n\n def fetch_pages(self):\n errors = []\n success_counter = 0\n for url, path in self.url_paths.items():\n page_ = self.get_and_wait(url)\n if not page_:\n errors.append(url)\n print(\"Error getting {}\".format(url))\n soup = bs(page_, 'html.parser')\n self.save_page(soup, path)\n print(\"Finished {}\".format(url))\n success_counter += 1\n self.driver.quit()\n return errors, success_counter\n\n\ndef intro_prompt():\n print(\"Welcome to Nomad!\")\n print(\"\")\n time.sleep(2)\n print(\"This program navigates your browser to a list of URLs.\")\n time.sleep(2)\n print(\"After visiting each page, the page is saved to your computer\")\n time.sleep(2)\n print(\"This allows for data extraction by yourself or a more knowledgeable user\")\n print(\"\")\n\n\ndef intro_file_prompt():\n print(\"==========================================================================================================\")\n print(\"\")\n print(\"Nomad expects a .csv, .xls or .xlsx file of URL's\")\n time.sleep(1)\n print(\"These must be in Column A of your spreadsheet\")\n time.sleep(1)\n print(\"There is no need to include a header\")\n\n\ndef intro_prompt_for_file():\n print(\"==========================================================================================================\")\n print(\"\")\n time.sleep(2)\n print(\"In a moment a File Open Dialog will be opened\")\n time.sleep(1)\n print(\"If it is not visible, please try minimizing other applications\")\n time.sleep(1)\n print(\"It is likely to be hidden under other open windows\")\n time.sleep(1)\n\n\ndef intro_():\n intro_prompt()\n intro_file_prompt()\n intro_prompt_for_file()\n\n\ndef intro_login():\n print(\"After Nomad opens a new Chrome browser, please visit your destination website\")\n time.sleep(1)\n print(\"You will need to login\")\n time.sleep(1)\n print(\"Nomad will wait until you are ready\")\n time.sleep(1)\n\n\ndef intro_selenium():\n has_login = input(\"Do your websites require a login? Enter (Y/N)\")\n if has_login.lower() == \"y\":\n has_login = True\n else:\n has_login = False\n if has_login:\n intro_login()\n\ndef prompt_begin():\n user_ready = input(\"Are you ready to begin? Enter (Y/N)\")\n if user_ready.lower() == \"y\":\n return True\n else:\n return False\n\n\ndef exit_nomad(message):\n print(\"============\")\n print(message)\n counter = 5\n for i in range(5):\n print(\"Nomad exiting in {}\".format(counter))\n time.sleep(1)\n counter -= 1\n quit()\n\n\ndef error_on_file():\n exit_nomad(\"Nomad was not able to open the file you selected and will now exit\")\n\n\ndef output_results(errors, success_counts):\n if len(errors) == 0:\n print(\"Great news! Nomad was able to get all {} of your URLs\".format(success_counts))\n time.sleep(5)\n exit_nomad(\"Goodbye!\")\n elif len(errors) > 0 and success_count > 0:\n print(\"The good news is that Nomad was able to get {} of your URLs\".format(success_counts))\n print(\"The bad news is that Nomad could not get {} of them\".format(len(errors)))\n print(\"They were : \")\n for e in errors:\n print(e)\n time.sleep(30)\n exit_nomad(\"Goodbye!\")\n else:\n print(\"Well that's embarrassing, Nomad was unable to get any of your URLs\")\n exit_nomad(\"Goodbye!\")\n\n\nif __name__ == '__main__':\n intro_()\n path_in = easygui.fileopenbox(msg=\"Select the Spreadsheet containing URLS\", title=\"Nomad\")\n fileloader = FileLoader(path_in)\n if fileloader.file.empty:\n error_on_file()\n quit()\n intro_selenium()\n # Create a Nomad object\n # Passing FileLoaders\n\n nomad = Nomad(fileloader.url_paths, CHROME_PATH)\n nomad.add_message(\"Please indicate via the console when you are ready to begin\")\n user_ready = prompt_begin()\n if not user_ready:\n nomad.driver.quit()\n exit_nomad(\"Please restart Nomad when you are ready\")\n errors, success_count = nomad.fetch_pages()\n output_results(errors, success_count)\n","sub_path":"Nomad/nomad.py","file_name":"nomad.py","file_ext":"py","file_size_in_byte":8463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"129602702","text":"\n\n#calss header\nclass _IDENTIFY():\n\tdef __init__(self,): \n\t\tself.name = \"IDENTIFY\"\n\t\tself.definitions = [u'to recognize someone or something and say or prove who or what that person or thing is: ', u'to recognize a problem, need, fact, etc. and to show that it exists: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_identify.py","file_name":"_identify.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"7292389","text":"import numpy\nimport os\n\nfrom __main__ import send_cmd_help\nfrom .utils import checks\nfrom .utils.chat_formatting import pagify\nfrom .utils.dataIO import dataIO\nfrom discord.ext import commands\n\n\nclass Lootbox:\n\n def __init__(self, bot):\n self.bot = bot\n self.db = dataIO.load_json(\"data/lootbox/servers.json\")\n\n @commands.group(pass_context=True)\n async def box(self, ctx):\n \"\"\"Box related commands\"\"\"\n if ctx.invoked_subcommand is None:\n await send_cmd_help(ctx)\n\n @box.command(pass_context=True)\n async def add(self, ctx, name: str, content: str, multi: int=None):\n \"\"\"Adds items to a box\n Usage:\n winter = box name\n [p]box add winter Key 20\n [p]box add winter \"Key, Unsealing Charm\" 20\"\"\"\n name = name.lower()\n server = ctx.message.server\n counter = 0\n neg = False\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please use [p]box create first\")\n return\n if \", \" in content:\n content = content.split(\", \")\n elif \",\" in content:\n content = content.split(\",\")\n if multi and type(content) is not list:\n if multi < 0:\n neg = True\n multi = abs(multi)\n content = [content.lower()] * multi\n else:\n if multi < 0:\n neg = True\n multi = abs(multi)\n content = content * multi\n print(content)\n for x in content:\n x = x.lower()\n if x in self.db[server.id][name][\"content\"]:\n if neg:\n self.db[server.id][name][\"content\"][x] -= 1\n else:\n self.db[server.id][name][\"content\"][x] += 1\n else:\n counter += 1\n continue\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"Items added to {} box: {}. Items failed to add: \"\n \"{}\".format(name, len(content)-counter, counter))\n\n @box.command(pass_context=True)\n async def create(self, ctx, name: str, output: int, *, content: str):\n \"\"\"Creates a box in the current server\n [p]box create winter 6 Key, Unsealing Charm, Black Padded Coat, Infernal Horn\"\"\"\n name = name.lower()\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n if name in self.db[server.id]:\n await self.bot.say(\"Box already exists, please use another name or use box edit to change the contents\")\n return\n if \", \" in content:\n content = content.split(\", \")\n elif \",\" in content:\n content = content.split(\",\")\n self.db[server.id][name] = {\"content\": {}, \"output\": output}\n for x in content:\n x = x.lower()\n self.db[server.id][name][\"content\"][x] = 0\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"{} box has been added, it has {} items and outputs {}\"\n \" items\".format(name, len(content), output))\n\n @checks.mod_or_permissions()\n @box.group(pass_context=True)\n async def edit(self, ctx):\n \"\"\"Allows editing of box names or output\"\"\"\n if ctx.invoked_subcommand is None:\n await send_cmd_help(ctx)\n\n @edit.command(pass_context=True)\n async def name(self, ctx, name: str, newname: str):\n \"\"\"Allows editing of the boxes' name\n winter = current name\n autumn = new name\n [p]box edit name winter autumn\"\"\"\n name = name.lower()\n newname = newname.lower()\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n if newname in self.db[server.id]:\n await self.bot.say(\"Box already exists, please use another name\")\n return\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please make sure the spelling is correct and\"\n \" that it's found in [p]box list\")\n return\n self.db[server.id][newname] = self.db[server.id].pop(name, None)\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"{} has been renamed to {}\".format(name, newname))\n\n @edit.command(pass_context=True)\n async def output(self, ctx, name: str, output: int):\n \"\"\"Allows adjusting how many items\n come out of the simulated lootbox\n [p]box edit output 20\"\"\"\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please make sure the spelling is correct and\"\n \" that it's found in [p]box list\")\n return\n self.db[server.id][name][\"output\"] = output\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"{} box's output has changed to {}\".format(name, output))\n\n @edit.command(pass_context=True)\n async def append(self, ctx, name: str, items: str):\n \"\"\"Allows adding new items to an already created lootbox\n [p]box edit append \"item_1 1, item_2 4, item_3 5\"\n Names are fixed when they are added.\"\"\"\n server = ctx.message.server\n items = items.split(\", \")\n itemis = dict()\n for item in items:\n item, value = item.split(\" \")\n item = item.replace(\"_\", \" \").lower()\n itemis[item] = value\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please make sure the spelling is correct and\"\n \" that it's found in [p]box list\")\n return\n items = list(itemis.keys())\n for item in items:\n value = itemis[item]\n if item in self.db[server.id][name][\"content\"]:\n items = [item for item in items if item not in self.db[server.id][name][\"content\"]]\n else:\n self.db[server.id][name][\"content\"][item] = value\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n if items:\n await self.bot.say(\"{} box has added the following items:\\n{}\".format(name, \"\\n\".join(items)))\n else:\n await self.bot.say(\"{} box hasn't added any new items\".format(name))\n\n @edit.command(pass_context=True)\n async def remove(self, ctx, name: str, items: str):\n \"\"\"Allows removing items to an already created lootbox\n [p]box edit remove \"item_1 1, item_2 4, item_3 5\"\n Names are fixed when they are added.\"\"\"\n server = ctx.message.server\n items = items.split(\", \")\n itemis = dict()\n for item in items:\n item, value = item.split(\" \")\n item = item.replace(\"_\", \" \").lower()\n itemis[item] = value\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please make sure the spelling is correct and\"\n \" that it's found in [p]box list\")\n return\n for item in itemis:\n value = itemis[item]\n print(item)\n if item in self.db[server.id][name][\"content\"]:\n del itemis[item]\n continue\n else:\n self.db[server.id][name][\"content\"][item] = value\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"{} box's has added the following items:\\n{}\".format(name, \"\\n\".join(list(itemis))))\n\n @box.command(pass_context=True)\n async def info(self, ctx, name: str):\n \"\"\"Shows info on the box, it's contents\n and the probability of getting an item\"\"\"\n name = name.lower()\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n if name not in self.db[server.id]:\n await self.bot.say(\"Please make sure that the name is spelled correctly and \"\n \"that you can find it in [p]box list\")\n return\n box = list(self.db[server.id][name][\"content\"].keys())\n values = list(self.db[server.id][name][\"content\"].values())\n value = sum(values)\n for x in range(len(values)):\n values[x] = values[x]/value\n box[x] = \" {:.2%} chance of getting \".format(values[x]) + box[x]\n msg = \"You can get the following items from the box:\\n\"\n msg += \"\\n\".join(box)\n for page in pagify(msg):\n await self.bot.say(page)\n\n @box.command(pass_context=True)\n async def list(self, ctx):\n \"\"\"Shows existing boxes in the current server\"\"\"\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n if len(self.db[server.id]) < 1:\n await self.bot.say(\"No boxes have been created for this server yet, please create some using [p]box create\"\n \" first, thanks\")\n return\n boxes = self.db[server.id].keys()\n await self.bot.say(\"Here are this server's boxes:\\n{}\".format(\"\\n\".join(boxes)))\n\n @checks.is_owner()\n @box.command(pass_context=True)\n async def remove(self, ctx, name: str):\n \"\"\"Deletes existing boxes\"\"\"\n name = name.lower()\n server = ctx.message.server\n if name not in self.db[server.id]:\n await self.bot.say(\"Please make sure that the name is spelled correctly and \"\n \"that you can find it in [p]box list\")\n return\n del self.db[server.id][name]\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"Box has been removed\")\n\n @box.command(pass_context=True)\n async def sim(self, ctx, name: str, item: str=None):\n \"\"\"Simulates the opening of a box (It won't be as accurate as an actual lootbox)\n If an item is always in a box, put the item name spelled correctly,\n with capitalization and all\n if you have Key in a box called winter do:\n [p]box sim winter Key\"\"\"\n name = name.lower()\n item = item.lower()\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Please make sure that the name is spelled correctly and \"\n \"that you can find it in [p]box list\")\n return\n box = list(self.db[server.id][name][\"content\"].keys())\n output = self.db[server.id][name][\"output\"]\n values = list(self.db[server.id][name][\"content\"].values())\n if item:\n try:\n y = box.index(item)\n del box[y]\n del values[y]\n output = output - 1\n except ValueError:\n item = None\n value = sum(values)\n for x in range(len(values)):\n values[x] = values[x]/value\n meow = numpy.random.choice(box, output, replace=False, p=values)\n if item:\n counter = numpy.random.randint(0, len(meow))\n meow = numpy.insert(meow, counter, item)\n msg = \"From {} box you got:\\n\".format(name)\n msg += \"\\n\".join(meow)\n for page in pagify(msg, delims=[\"\\n\"]):\n await self.bot.say(page)\n\n\ndef check_folders():\n # create data/lootbox if not there\n if not os.path.exists('data/lootbox'):\n print('Creating data/lootbox folder...')\n os.mkdir('data/lootbox')\n\n\ndef check_files():\n # create servers.json if not there\n # put in default values\n default = {}\n if not os.path.isfile('data/lootbox/servers.json'):\n print('Creating default lootbox servers.json...')\n dataIO.save_json('data/lootbox/servers.json', default)\n\n\ndef setup(bot):\n check_folders()\n check_files()\n n = Lootbox(bot)\n bot.add_cog(n)\n","sub_path":"lootbox/lootbox.py","file_name":"lootbox.py","file_ext":"py","file_size_in_byte":12523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"364122762","text":"# def ticket(price=5):\n# amount = int(input('Сколько вы хотите купить билетов? '))\n# return amount*price\n\n# print(ticket(int(input(\"Билеты\"))))\n\nimport random\nimport time\n\ndef display_intro():\n print('Ты - Шрек, спасающий Фиону.\\nСейчас ты находишься между 2 башнями.\\nВ одной башне тебя ждет Фиона.\\nА в другой - дракон, который за секунду тебя испепелит.')\n\ndef choose_tower():\n sick=int(input('Выбери башню '))\n while sick!=1 and sick!=2:\n sick=int(input('Выбери башню '))\n return sick\n\ndef check_tower(chosenTower):\n print('Вы приближаетесь к башне..')\n time.sleep(2)\n print('Она тёмная и жуткая..')\n time.sleep(2)\n print('Перед тобой резко открывается дверь и из нее на тебя пристально смотрит...')\n print('---------------------------------')\n time.sleep(2)\n jode = random.randint(1,2)\n if jode==chosenTower:\n print('Ты спас Фиону!')\n else:\n print('Тебя сжёг дракон :(')\n\nstart_game='yes'\nwhile start_game=='yes' or start_game=='y':\n display_intro()\n check_tower(choose_tower())\n start_game=input('Хочешь сыграть еще раз? ')\n\n","sub_path":"def.py","file_name":"def.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"358609747","text":"\"\"\"\ndf.py\n\"\"\"\nimport warnings\nimport copy\nimport numbers\nfrom ctypes import *\nfrom array import array\nimport numpy as np\nimport pandas as pd\nfrom collections import Iterable, OrderedDict\n\nfrom ..exrpc import rpclib\nfrom ..exrpc.server import FrovedisServer, set_association, \\\n check_association, do_if_active_association\nfrom ..matrix.dvector import FrovedisDvector\nfrom ..matrix.dvector import FrovedisIntDvector, FrovedisLongDvector\nfrom ..matrix.dvector import FrovedisULongDvector\nfrom ..matrix.dvector import FrovedisFloatDvector, FrovedisDoubleDvector\nfrom ..matrix.dvector import FrovedisStringDvector\nfrom ..matrix.dtype import DTYPE, TypeUtil, get_string_array_pointer\nfrom ..matrix.dense import FrovedisRowmajorMatrix\nfrom ..matrix.dense import FrovedisColmajorMatrix\nfrom ..matrix.crs import FrovedisCRSMatrix\nfrom ..mllib.model_util import ModelID\nfrom .info import df_to_sparse_info\nfrom .frovedisColumn import FrovedisColumn\nfrom .dfoperator import dfoperator\nfrom .dfutil import union_lists, infer_dtype, add_null_column_and_type_cast, \\\n infer_column_type_from_first_notna, get_string_typename, \\\n get_python_scalar_type, check_string_or_array_like, \\\n check_stat_error\nfrom ..utils import deprecated\nfrom pandas.core.common import SettingWithCopyWarning\n\ndef read_csv(filepath_or_buffer, sep=',', delimiter=None,\n header=\"infer\", names=None, index_col=None,\n usecols=None, squeeze=False, prefix=None,\n mangle_dupe_cols=True, dtype=None, na_values=None,\n verbose=False, comment=None, low_memory=True,\n rows_to_see=1024, separate_mb=1024):\n \"\"\"\n loads frovedis dataframe from csv file\n \"\"\"\n\n #TODO: support index_col parameter (currently gets ignored)\n if comment is not None:\n if isinstance(comment, str):\n if len(comment) != 1:\n raise ValueError(\"read_csv: comment should be either \" +\\\n \"a string of unit length or None!\")\n # TODO: remove the below error when \"comment\" support would be added in Frovedis\n raise ValueError(\"read_csv: Frovedis currently doesn't support parameter comment!\")\n else:\n comment=\"\"\n\n if delimiter is None:\n delimiter = sep\n\n if len(delimiter) != 1:\n raise ValueError(\"read_csv: Frovedis currently supports only single \"\n \"character delimiters!\")\n\n if not isinstance(verbose, bool):\n raise ValueError(\"read_csv: Frovedis doesn't support \"\n \"verbose={0}!\".format(verbose))\n\n if not isinstance(mangle_dupe_cols, bool):\n raise ValueError(\"read_csv: Frovedis doesn't support \"\n \"mangle_dupe_cols={0}!\".format(mangle_dupe_cols))\n if names:\n if len(np.unique(names)) != len(names):\n raise ValueError(\"read_csv: Duplicate names are not allowed.\")\n\n if na_values is None:\n na_values = ['null', 'NULL', 'nan', '-nan', 'NaN', '-NaN', 'NA', 'N/A', 'n/a']\n elif isinstance(na_values, dict):\n raise ValueError(\"read_csv: Frovedis currently doesn't support \"\\\n \"na_values as dictionary!\")\n else:\n na_values = check_string_or_array_like(na_values, 'read_csv')\n \n if header not in (\"infer\", 0, None):\n raise ValueError(\"read_csv: Frovedis doesn't support \"\n \"header={0}!\".format(header))\n\n import csv\n with open(filepath_or_buffer) as f:\n reader = csv.reader(f, delimiter=delimiter)\n row1 = next(reader)\n ncols = len(row1)\n\n if ncols == 0:\n raise ValueError(\"read_csv: Frovedis currently doesn't support \"\n \"blank line at beginning!\")\n\n if dtype and isinstance(dtype, dict):\n dtype = {key: np.dtype(value).name for (key,value) in dtype.items()}\n\n add_index = True\n if usecols is not None:\n if all(isinstance(e, int) for e in usecols):\n usecols = np.asarray(usecols, dtype=np.int32)\n if np.min(usecols) < 0 or np.max(usecols) >= ncols:\n raise ValueError(\"read_csv: usecols index is out-of-bound!\")\n else:\n raise ValueError(\"read_csv: currently Frovedis supports only ids \" +\\\n \"for usecols parameter!\")\n else:\n usecols = np.empty(0, dtype=np.int32)\n \n if names is None:\n if header is None:\n if prefix is None:\n names = [str(i) for i in range(0, ncols)]\n elif isinstance(prefix, str):\n names = [prefix + str(i) for i in range(0, ncols)]\n else:\n raise ValueError(\"read_csv: Frovedis doesn't support \"\n \"prefix={0}!\".format(prefix))\n else:\n names = [] #to be infered from 0th line in input csv file\n else:\n if len(usecols) > 0:\n if len(names) == ncols:\n pass\n elif len(names) == len(usecols):\n # if names is given, frovedis expects all column names to be\n # provided. thus populating dummy names for those columns\n # which are not in usecols\n tnames = [\"_c_\" + str(i) for i in range(0, ncols)]\n for i in range(len(usecols)):\n cid = usecols[i]\n tnames[cid] = names[i]\n names = tnames\n else:\n raise ValueError(\"read_csv: Passed header names mismatches usecols\")\n else:\n if len(names) == ncols - 1:\n names = [\"index\"] + names\n add_index = False\n elif len(names) > ncols:\n names = names[:ncols] # TODO: support pandas like NaN cols\n elif len(names) < ncols - 1:\n raise ValueError(\"read_csv: Frovedis currently doesn't support \"\n \"multi-level index loading!\")\n index_col_no = -1\n if index_col is None:\n pass\n elif isinstance(index_col, bool):\n if index_col:\n raise ValueError(\"read_csv: The value of index_col couldn't be 'True'\")\n else:\n # dont use 1st col as index\n if names[0] == \"index\":\n names = names[1:]\n add_index = True\n elif isinstance(index_col, int):\n if index_col < 0 or index_col > (ncols -1 ):\n raise ValueError(\"read_csv: The value for 'index_col' is invalid!\")\n index_col_no = index_col\n if names == []:\n add_index = False\n elif names[0] == \"index\":\n names = names[1:]\n add_index = False\n if len(names) == ncols - 1:\n names.insert(index_col, \"index\") \n #inserted in names, so this is parsed as well \n else:\n raise ValueError(\"read_csv: Frovedis currently supports only bool and int types for index_col !\")\n\n single_dtype = None\n types = []\n partial_type_info = False\n if dtype is None:\n dtype = {}\n types = []\n elif isinstance(dtype, dict):\n if not names:\n partial_type_info = True\n elif not set(names).issubset(set(dtype.keys())):\n partial_type_info = True\n else:\n types = [get_string_typename(dtype[e]) for e in names]\n else:\n # single_dtype\n single_dtype = np.dtype(dtype).name #raise exception if dtype not valid\n if names:\n n = len(names)\n else:\n n = ncols\n if single_dtype == 'bool':\n types = [] # let it be infered at server side\n else:\n types = [get_string_typename(single_dtype)] * n\n\n is_all_bools = single_dtype == 'bool'\n bool_cols = []\n if isinstance(dtype, dict):\n bool_cols = [k for k in dtype if dtype[k] == 'bool']\n\n name_arr = get_string_array_pointer(names)\n type_arr = get_string_array_pointer(types)\n bool_cols_arr = get_string_array_pointer(bool_cols)\n\n # for partial_type_info\n dtype_keys = []\n dtype_vals = []\n if partial_type_info:\n dtype_keys = list(dtype.keys())\n dtype_vals = [get_string_typename(e) for e in dtype.values()]\n dtype_keys_arr = get_string_array_pointer(dtype_keys)\n dtype_vals_arr = get_string_array_pointer(dtype_vals)\n\n na_sz = len(na_values)\n na_ptr = get_string_array_pointer(na_values)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.load_dataframe_from_csv(host, port, \n filepath_or_buffer.encode('ascii'),\n type_arr, name_arr,\n len(type_arr), len(name_arr),\n delimiter.encode('ascii'),\n na_ptr, na_sz,\n comment.encode(\"ascii\"),\n rows_to_see, separate_mb,\n partial_type_info,\n dtype_keys_arr, dtype_vals_arr,\n len(dtype_keys), low_memory, add_index,\n usecols, len(usecols),\n verbose, mangle_dupe_cols, index_col_no,\n bool_cols_arr, len(bool_cols_arr),\n is_all_bools)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n if is_all_bools:\n types = [DTYPE.BOOL] * len(types)\n elif len(bool_cols) > 0:\n for i in range(len(names)):\n if names[i] in bool_cols:\n types[i] = DTYPE.BOOL\n\n res = FrovedisDataframe().load_dummy(dummy_df[\"dfptr\"], \\\n names[1:], types[1:])\n #TODO: handle index/num_row setting inside load_dummy()\n res.index = FrovedisColumn(names[0], types[0]) #setting index\n res.num_row = dummy_df[\"nrow\"]\n return res\n\nclass DataFrame(object):\n \"\"\"\n DataFrame\n \"\"\"\n\n def __init__(self, df=None, is_series=False):\n \"\"\"\n __init__\n \"\"\"\n self.__fdata = None\n self.__cols = None\n self.__types = None\n self.index = None\n self.is_series = is_series\n if df is not None:\n self.load(df)\n\n def has_index(self):\n \"\"\"\n has_index\n \"\"\"\n return self.index is not None\n\n @set_association\n def load_dummy(self, fdata, cols, types):\n \"\"\"\n load_dummy\n \"\"\"\n self.__fdata = fdata\n self.__cols = cols\n self.__types = types\n for i in range(0, len(cols)):\n cname = cols[i]\n dt = types[i]\n self.__dict__[cname] = FrovedisColumn(cname, dt)\n return self\n\n def show(self):\n \"\"\"\n show\n \"\"\"\n '''\n if self.__fdata is not None:\n (host, port) = FrovedisServer.getServerInstance()\n rpclib.show_frovedis_dataframe(host, port, self.__fdata)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n print(\"\\n\")\n '''\n print(str(self))\n\n def release(self):\n \"\"\"\n to release dataframe pointer from server heap and\n resets after-fit populated attributes to None\n \"\"\"\n self.__release_server_heap()\n if self.__cols is not None:\n for cname in self.__cols:\n del self.__dict__[cname]\n self.__fdata = None\n self.__cols = None\n self.__types = None\n self.index = None\n self.is_series = None\n\n @do_if_active_association\n def __release_server_heap(self):\n \"\"\" releases the dataframe pointer from server heap \"\"\"\n (host, port) = FrovedisServer.getServerInstance()\n rpclib.release_frovedis_dataframe(host, port, self.__fdata)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n def __del__(self):\n \"\"\" destructs a python dataframe object \"\"\"\n self.release()\n\n def is_fitted(self):\n \"\"\" function to confirm if the dataframe is already constructed \"\"\"\n return self.__fdata is not None\n\n @check_association\n def __len__(self):\n \"\"\"\n to be invoked by len() method\n \"\"\"\n #TODO: set this parameter always\n if \"num_row\" not in self.__dict__:\n (host, port) = FrovedisServer.getServerInstance()\n self.num_row = rpclib.get_frovedis_dataframe_length(host, port, \\\n self.__fdata)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return int(self.num_row)\n\n @property\n def ndim(self):\n \"\"\"return dimension in input df\"\"\"\n return 1 if self.is_series else 2 \n\n @ndim.setter\n def ndim(self, val):\n \"\"\"ndim setter\"\"\"\n raise AttributeError(\\\n \"attribute 'ndim' of DataFrame object is not writable\")\n\n @property\n def count(self): # similar to spark dataframe \n \"\"\"return num_row in input df\"\"\"\n return len(self)\n\n @count.setter\n def count(self, val):\n \"\"\"count setter\"\"\"\n raise AttributeError(\\\n \"attribute 'count' of DataFrame object is not writable\")\n\n @property\n @check_association\n def dtypes(self):\n \"\"\"return data types of input df\"\"\"\n dt = {}\n for i in range(len(self.__cols)):\n if self.__types[i] == DTYPE.STRING:\n dt[self.__cols[i]] = \"object\"\n else:\n dt[self.__cols[i]] = \\\n TypeUtil.to_numpy_dtype(self.__types[i]).__name__\n return pd.Series(dt)\n\n @dtypes.setter\n def dtypes(self, val):\n \"\"\"dtypes setter\"\"\"\n raise AttributeError(\\\n \"attribute 'dtypes' of DataFrame object is not writable\")\n\n @property\n @check_association\n def shape(self):\n \"\"\"return shape of input df\"\"\"\n return (len(self), len(self.__cols))\n\n @shape.setter\n def shape(self, val):\n \"\"\"shape setter\"\"\"\n raise AttributeError(\\\n \"attribute 'shape' of DataFrame object is not writable\")\n\n @set_association\n def load(self, df):\n \"\"\"\n load\n \"\"\"\n if len(df) == 0:\n raise ValueError(\"Cannot load an empty pandas dataframe \" +\\\n \"(column types could not be deduced)\")\n if isinstance(df.index, pd.MultiIndex):\n raise ValueError(\"Cannot load a pandas dataframe \" +\\\n \"with multi level index\")\n\n self.release()\n self.num_row = len(df)\n cols = df.columns.tolist()\n self.__cols = cols\n indx_name = df.index.name if df.index.name is not None else \"index\"\n cols = [indx_name] + cols\n size = len(cols)\n types = [0] * size\n dvec = [None] * size\n\n for idx in range(0, size):\n cname = cols[idx]\n if idx == 0:\n val = df.index\n else:\n val = df[cname]\n vtype = val.dtype.name\n if vtype == 'object': # type-infering required to detect string\n vtype = infer_column_type_from_first_notna(df, val, idx == 0)\n #print(cname + \":\" + vtype)\n if vtype == 'int32' or vtype == 'int':\n dt = DTYPE.INT\n dvec[idx] = FrovedisIntDvector(val)\n elif vtype == 'int64' or vtype == 'long':\n dt = DTYPE.LONG\n dvec[idx] = FrovedisLongDvector(val)\n elif vtype == 'uint64':\n dt = DTYPE.ULONG\n dvec[idx] = FrovedisULongDvector(val)\n elif vtype == 'float32' or vtype == 'float':\n dt = DTYPE.FLOAT\n dvec[idx] = FrovedisFloatDvector(val)\n elif vtype == 'float64' or vtype == 'double':\n dt = DTYPE.DOUBLE\n dvec[idx] = FrovedisDoubleDvector(val)\n elif vtype == 'str' or vtype == 'str_':\n dt = DTYPE.STRING\n dvec[idx] = FrovedisStringDvector(val)\n elif vtype == 'bool' or vtype == 'bool_':\n dt = DTYPE.BOOL\n dvec[idx] = FrovedisIntDvector(np.asarray(val, dtype=np.int32))\n else:\n raise TypeError(\"Unsupported column type '%s' in creation of \"\\\n \"frovedis dataframe: \" % (vtype))\n types[idx] = dt\n if idx == 0:\n self.index = FrovedisColumn(cname, dt) \n else:\n self.__dict__[cname] = FrovedisColumn(cname, dt) #For query purpose\n\n col_names = get_string_array_pointer(cols)\n dvec_arr = np.asarray([dv.get() for dv in dvec], dtype=c_long)\n dptr = dvec_arr.ctypes.data_as(POINTER(c_long))\n type_arr = np.asarray(types, dtype=c_short)\n tptr = type_arr.ctypes.data_as(POINTER(c_short))\n self.__types = types[1:]\n\n (host, port) = FrovedisServer.getServerInstance()\n self.__fdata = rpclib.create_frovedis_dataframe(host, port, tptr,\n col_names, dptr, size)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n # dvectors in 'dptr' are already destructed during dataframe\n # construction. thus resetting the metadata to avoid double\n # free issue from server side during destructor calls of the \n # dvectors in 'dptr'\n for dv in dvec:\n dv.reset()\n\n def __getitem__(self, target):\n \"\"\"\n __getitem__\n \"\"\"\n if self.__fdata is not None:\n if isinstance(target, str):\n return self.select_frovedis_dataframe([target])\n elif isinstance(target, list):\n return self.select_frovedis_dataframe(target)\n elif isinstance(target, dfoperator):\n return self.filter_frovedis_dataframe(target)\n elif isinstance(target, slice):\n return self.__filter_slice_range(target)\n else:\n raise TypeError(\"Unsupported indexing input type!\")\n else:\n raise ValueError(\"Operation on invalid frovedis dataframe!\")\n\n @property\n @check_association\n def columns(self):\n \"\"\"returns column list\"\"\"\n return self.__cols\n\n @columns.setter\n @check_association\n def columns(self, newcols):\n \"\"\"renames columns\"\"\"\n if newcols is None or np.isscalar(newcols):\n raise TypeError(\"must be called with a collection of some \"\n \"kind, '%s' was passed\" % (newcols))\n if len(newcols) != len(self.__cols):\n raise ValueError(\"Length mismatch: Expected axis has %d elements\"\n \", new values have %d elements\" \\\n % (len(self.__cols), len(newcols)))\n self.rename(columns=dict(zip(self.__cols, newcols)), inplace=True)\n\n @check_association\n def filter_frovedis_dataframe(self, opt):\n \"\"\" \n filters rows on the basis of given 'opt' condition \n from the input dataframe \n \"\"\"\n ret = DataFrame(is_series=self.is_series)\n ret.index = self.index\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.filter_frovedis_dataframe(host, port, \\\n self.get(), opt.get())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, list(self.__cols), list(self.__types)) \n return ret \n\n @check_association\n def select_frovedis_dataframe(self, targets):\n \"\"\" selects given columns from the input dataframe \"\"\"\n targets = list(check_string_or_array_like(targets, \"select\"))\n is_ser = len(targets) == 1\n ret = DataFrame(is_series=is_ser)\n ret_types = self.__get_column_types(targets)\n ret_cols = list(targets) #targets is a list\n ret.num_row = len(self) \n ret.index = self.index\n\n if self.has_index():\n targets = [self.index.name] + targets\n\n sz = len(targets) \n ptr_arr = get_string_array_pointer(targets)\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.select_frovedis_dataframe(host, port, self.get(), \\\n ptr_arr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, ret_cols, ret_types)\n return ret \n\n @check_association\n def nsort(self, n, columns, keep='first', is_desc=False):\n \"\"\"\n returns top n sorted rows (in ascending or descending order)\n \"\"\"\n func = \"nlargest\" if is_desc else \"nsmallest\"\n if not isinstance(n, int):\n raise TypeError(\\\n func + \": expected a positive integer for 'n' parameter!\\n\")\n elif n < 0:\n raise ValueError(\\\n func + \": expected a positive integer for 'n' parameter!\\n\")\n\n if not isinstance(keep, str):\n raise TypeError(\\\n func + \": expected a string for 'keep' parameter!\\n\")\n elif keep != \"all\" and keep != \"first\" and keep != \"last\":\n raise ValueError(func + \": supported 'keep' values are 'first', \"\\\n \"'last' and 'all' only! receieved %s.\\n\" % (keep))\n\n sort_by = check_string_or_array_like(columns, func)\n for item in sort_by:\n # TODO: confirm possibility of including index column\n #if item not in self.columns and item != self.index.name:\n if item not in self.columns: \n raise ValueError(func + \": No column named: \" + str(item))\n\n sz = len(sort_by) \n ptr_arr = get_string_array_pointer(sort_by)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_ksort(host, port, self.get(),\n n, ptr_arr, sz, keep.encode('ascii'), \n is_desc)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret = DataFrame(is_series=self.is_series)\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return ret\n\n def nlargest(self, n, columns, keep='first'):\n \"\"\"\n returns top n sorted rows in descending order\n \"\"\"\n return self.nsort(n, columns, keep, is_desc=True)\n\n def nsmallest(self, n, columns, keep='first'):\n \"\"\"\n returns top n sorted rows in ascending order\n \"\"\"\n return self.nsort(n, columns, keep, is_desc=False)\n\n def sort_index(self, axis=0, ascending=True, inplace=False,\n kind='quicksort', na_position='last'):\n \"\"\"\n sort_index\n \"\"\"\n return self.sort_values(by=self.index.name, axis=axis, ascending=ascending, \n inplace=inplace, kind=kind, na_position=na_position)\n\n @check_association\n def sort_values(self, by, axis=0, ascending=True,\n inplace=False, kind='radixsort', na_position='last'):\n \"\"\"\n sort_values\n \"\"\"\n if na_position != \"last\":\n if na_position == \"first\":\n raise ValueError(\"Frovedis currently doesn't support \" \\\n \"na_position='first' !\")\n else:\n raise ValueError(\"invalid na_position: '{}' \".format(na_position))\n\n if axis not in (0, \"index\"):\n if axis in (1, \"columns\"):\n raise ValueError(\"Frovedis currently doesn't support sorting \" \\\n \"the axis = 1 !\")\n else:\n raise ValueError(\"No axis named {} for frovedis dataframe !\"\n .format(axis))\n\n if kind not in [\"radixsort\", \"stable\"]:\n warnings.warn(\"Frovedis currently supports radixsort (stable) \" \\\n \"internally, other 'kind' parameters will be ignored!\")\n\n if inplace:\n raise ValueError(\"Frovedis currently doesn't support inplace \" \\\n \"sorting of dataframes ! \")\n\n sort_by = check_string_or_array_like(by, \"sort\")\n for item in sort_by:\n if item not in self.columns and item != self.index.name:\n raise ValueError(\"sort: No column named: %s\" % str(item))\n\n sz = len(sort_by) \n sort_by_arr = get_string_array_pointer(sort_by)\n \n if type(ascending).__name__ == 'bool':\n orderlist = [ascending] * sz\n sort_order = np.asarray(orderlist, dtype=np.int32)\n elif type(ascending).__name__ == 'list':\n if len(ascending) != sz:\n raise ValueError(\"sort: Length of by and ascending parameters\"\n \" are not matching!\")\n sort_order = np.asarray(ascending, dtype=np.int32)\n else:\n dgt = str(ascending).isdigit()\n if dgt:\n orderlist = [bool(ascending)] * sz\n sort_order = np.asarray(orderlist, dtype=np.int32)\n else:\n raise TypeError(\"sort: Expected: digit|list; Received: \",\n type(ascending).__name__)\n\n ret = DataFrame(is_series=self.is_series)\n ret.index = self.index\n ret.num_row = len(self) \n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.sort_frovedis_dataframe(host, port, self.get(),\\\n sort_by_arr, sort_order, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, list(self.__cols), list(self.__types)) \n return ret \n\n def sort(self, columns=None, axis=0, ascending=True,\n inplace=False, kind='radixsort', na_position='last', **kwargs):\n \"\"\"\n sort_\n \"\"\"\n if not columns:\n raise ValueError(\"Column to be sorted cannot be None!\")\n return self.sort_values(by=columns, axis=axis,\n ascending=ascending,\n inplace=inplace, kind=kind,\n na_position=na_position)\n\n @check_association\n def groupby(self, by=None, axis=0, level=None,\n as_index=True, sort=True, group_keys=True, squeeze=False,\n observed=False, dropna=True):\n \"\"\"\n groupby\n \"\"\"\n from frovedis.dataframe import grouped_df\n if axis != 0:\n raise NotImplementedError(\\\n \"groupby: axis = '%d' is currently not supported!\" % (axis))\n\n if level is not None: \n raise NotImplementedError( \\\n \"groupby: level is currently not supported!\")\n\n g_by = check_string_or_array_like(by, \"groupby\")\n types = self.__get_column_types(g_by) \n if dropna:\n g_df = self.dropna(subset=g_by)\n else:\n g_df = self\n\n sz = len(g_by) \n ptr_arr = get_string_array_pointer(g_by)\n (host, port) = FrovedisServer.getServerInstance()\n fdata = rpclib.group_frovedis_dataframe(host, port, g_df.get(),\n ptr_arr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return grouped_df.FrovedisGroupedDataframe()\\\n .load_dummy(fdata, list(g_by), list(types), \\\n list(self.__cols), list(self.__types))\n def __merge_rename_helper(self, rename_dict):\n \"\"\"\n helper function for renaming columns/index for dataframe\n \"\"\"\n ret = self.rename(rename_dict)\n index_name = self.index.name\n\n if index_name is not None and index_name in rename_dict:\n ret = self.rename_index(rename_dict[index_name])\n\n return ret\n\n # method to evaluate join keys\n def __evaluate_join_condition(self, df_right, left_on, right_on):\n \"\"\"\n __evaluate_join_condition\n \"\"\"\n # assumes left_on, right_on as python list\n if len(left_on) != len(right_on):\n raise ValueError(\"Size of left_on and right_on is\" +\n \" not matched!\")\n #for renaming\n col_dict = {}\n for i in range(len(left_on)):\n if left_on[i] == right_on[i]:\n tmp = right_on[i] + \"_right\"\n col_dict[right_on[i]] = tmp\n right_on[i] = tmp\n df_right = df_right.__merge_rename_helper(col_dict)\n renamed_key = list(col_dict.values()) # [] if no renaming is performed\n\n # for dfopt combining\n sz = len(left_on)\n left_on_arr = get_string_array_pointer(left_on)\n right_on_arr = get_string_array_pointer(right_on)\n\n (host, port) = FrovedisServer.getServerInstance()\n dfopt_proxy = rpclib.get_multi_eq_dfopt(host, port, left_on_arr,\n right_on_arr, sz)\n dfopt = dfoperator(dfopt_proxy)\n return (df_right, dfopt, renamed_key, right_on)\n\n def __get_frovedis_how(self, how):\n pandas_to_frov_how = { \"left\": \"outer\",\n \"inner\": \"inner\" }\n if how not in pandas_to_frov_how:\n raise ValueError(\"Frovedis currently doesn't support how={0}!\".format(how))\n return pandas_to_frov_how[how]\n\n @check_association\n def merge(self, right, on=None, how='inner', left_on=None, right_on=None,\n left_index=False, right_index=False, sort=False,\n suffixes=('_x', '_y'), copy=True,\n indicator=False, join_type='bcast'):\n \"\"\"\n merge\n \"\"\"\n\n right = DataFrame.asDF(right)\n on_index = None\n\n if not isinstance(left_index, bool):\n raise ValueError(\n \"left_index parameter must be of type bool, not \", type(left_index)\n )\n if not isinstance(right_index, bool):\n raise ValueError(\n \"right_index parameter must be of type bool, not\", type(right_index)\n )\n\n if left_on and left_index:\n raise ValueError(\"Can only pass 'left_on' OR 'left_index'\" +\n \" not a combination of both!\")\n elif right_on and right_index:\n raise ValueError(\"Can only pass 'right_on' OR 'right_index'\" +\n \" not a combination of both!\")\n elif on and (left_index or right_index):\n raise ValueError(\"Can only pass 'on' OR 'left_index' and\" +\n \" 'right_index', not a combination of both!\")\n \n # table must have index, if merge-target is index\n if left_index and not self.has_index():\n raise ValueError(\"left table doesn't have index!\\n\")\n if right_index and not right.has_index():\n raise ValueError(\"right table doesn't have index!\\n\")\n\n # index rename for right, if same with left\n if self.has_index() and right.has_index():\n if self.index.name == right.index.name:\n right = right.rename_index(right.index.name + \"_right\")\n reset_index_name = False #rename not required, if both are same\n else:\n # if both table have different names for index,\n # then if merge takes place on both indices i.e., \n # (left_index=right_index=True), resultant table \n # would have generic name for index column\n reset_index_name = True\n\n if left_index and right_index:\n on_index = self.index\n if self.index.name == \"index\": \n #rename not required, if index-name is already generic\n reset_index_name = False \n elif left_index and not right_index:\n on_index = right.index\n reset_index_name = False\n elif right_index and not left_index:\n on_index = self.index\n reset_index_name = False\n\n if on: #if key name is same in both dataframes\n if(left_on) or (right_on):\n raise ValueError(\"Can only pass 'on' OR 'left_on' and\" +\n \" 'right_on', not a combination of both!\")\n left_on = right_on = on\n\n # no of nulls\n n_nulls = sum(x is None for x in (on, right_on, left_on))\n if n_nulls == 3:\n if self is right: \n # Early return: all columns are common => all comlumns are treated as keys\n # returning a copy of self\n ret = self.select_frovedis_dataframe(self.columns)\n ret.reset_index(drop=True, inplace=True)\n return ret\n\n if left_index and right_index:\n left_on, right_on = self.index.name, right.index.name\n elif left_index:\n raise ValueError(\"Must pass right_on or right_index=True\")\n elif right_index:\n raise ValueError(\"Must pass left_on or left_index=True\")\n else:\n common_cols = list(set(self.columns) & set(right.columns))\n if len(common_cols) == 0:\n raise ValueError(\"No common columns to perform merge on.\")\n left_on = right_on = common_cols\n elif left_on and right_index:\n right_on = right.index.name\n elif left_index and right_on:\n left_on = self.index.name\n\n if (left_on and not right_on) or (not left_on and right_on):\n raise ValueError(\"Both left_on and right_on need to be provided.\"+\n \" In case of common keys, use 'on' parameter!\")\n\n if not isinstance(left_on, (tuple, list)):\n left_keys = [left_on]\n else:\n left_keys = list(left_on)\n\n if not isinstance(right_on, (tuple, list)):\n right_keys = [right_on]\n else:\n right_keys = list(right_on)\n\n # right, right_keys may be modified if keys are same ( in __evaluate_join_condition())\n right, dfopt, renamed_keys, right_keys = \\\n self.__evaluate_join_condition(right, left_keys, right_keys)\n\n left_non_key_cols = set(self.__cols) - set(left_keys)\n right_non_key_cols = set(right.__cols) - set(right_keys)\n common_non_key_cols = left_non_key_cols & right_non_key_cols\n \n left_non_key_column_in_right_key = left_non_key_cols & set(right_keys)\n right_non_key_column_in_left_key = right_non_key_cols & set(left_keys)\n\n # if renaming required add suffixes\n df_left = self\n df_right = right\n if len(common_non_key_cols) > 0 \\\n or len(left_non_key_column_in_right_key) > 0 \\\n or len(right_non_key_column_in_left_key) > 0:\n renamed_left_cols = {}\n renamed_right_cols = {}\n lsuf, rsuf = suffixes\n if lsuf == '' and rsuf == '':\n raise ValueError(\"columns overlap but no suffix specified: %s \" \\\n % common_non_key_cols)\n for e in common_non_key_cols:\n renamed_left_cols[e] = e + str(lsuf)\n renamed_right_cols[e] = e + str(rsuf)\n\n for e in left_non_key_column_in_right_key:\n renamed_left_cols[e] = e + str(lsuf)\n\n for e in right_non_key_column_in_left_key:\n renamed_right_cols[e] = e + str(rsuf)\n\n if lsuf != '':\n df_left = self.__merge_rename_helper(renamed_left_cols)\n if rsuf != '':\n df_right = right.__merge_rename_helper(renamed_right_cols)\n\n ret = DataFrame()\n ret_cols = df_left.__cols + df_right.__cols\n ret_types = df_left.__types + df_right.__types\n frov_how = self.__get_frovedis_how(how)\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.merge_frovedis_dataframe(host, port, df_left.get(), \\\n df_right.get(), dfopt.get(), \\\n frov_how.encode('ascii'), \\\n join_type.encode('ascii'))\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, ret_cols, ret_types)\n \n targets = ret.columns\n if renamed_keys:\n for key in renamed_keys:\n if key in targets:\n targets.remove(key)\n\n if on_index:\n index_name = on_index.name\n ret.index = FrovedisColumn(index_name, dtype=on_index.dtype)\n ret = ret.select_frovedis_dataframe(targets)\n if index_name.endswith(\"_right\"):\n index_name = index_name[:-len(\"_right\")]\n ret.rename_index(index_name, inplace=True)\n elif reset_index_name:\n ret.rename_index(\"index\", inplace=True)\n else:\n ret = ret.select_frovedis_dataframe(targets)\n ret = ret.add_index(\"index\")\n\n return ret\n \n # exception at frovedis server: same key is not\n # currently supported by frovedis\n def join(self, right, on, how='inner',\n lsuffix='_left', rsuffix='_right', sort=False, join_type='bcast'):\n \"\"\"\n join\n \"\"\"\n suffix = []\n suffix.append(lsuffix)\n suffix.append(rsuffix)\n if not on:\n raise ValueError(\"Key to join can not be None!\")\n return self.merge(right, on=on, how=how, suffixes=suffix, sort=sort,\n join_type=join_type)\n\n @check_association\n def rename(self, columns, inplace=False):\n \"\"\" returns new dataframe with renamed columns \"\"\"\n if not columns:\n return self\n if not isinstance(columns, dict):\n raise TypeError(\"Expected: dictionary; Received: \",\n type(columns).__name__)\n\n names = list(columns.keys())\n new_names = list(columns.values())\n if inplace:\n ret = self\n else:\n ret = DataFrame(is_series=self.is_series)\n ret.index = self.index\n ret.num_row = len(self) \n ret_cols = list(self.__cols)\n ret_types = list(self.__types)\n\n t_names = []\n t_new_names = []\n for i in range(0, len(names)):\n item = names[i]\n new_item = new_names[i]\n if item in ret_cols: # otherwise skipped as in pandas rename()\n if inplace:\n del self.__dict__[item]\n idx = ret_cols.index(item)\n ret_cols[idx] = new_item\n t_names.append(item)\n t_new_names.append(new_item)\n \n sz = len(t_names)\n name_ptr = get_string_array_pointer(t_names)\n new_name_ptr = get_string_array_pointer(t_new_names)\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.rename_frovedis_dataframe(host, port, self.get(), \\\n name_ptr, new_name_ptr, \\\n sz, inplace)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, ret_cols, ret_types)\n return None if inplace else ret \n\n @check_association\n def rename_index(self, new_name, inplace=False): \n \"\"\" renames index field of self inplace \"\"\"\n if not self.has_index():\n raise ValueError(\"rename_index: no index field for renaming!\")\n if inplace:\n ret = self\n else:\n ret = DataFrame(is_series=self.is_series)\n ret.num_row = len(self) \n ret.index = FrovedisColumn(new_name, self.index.dtype)\n ret_cols = list(self.__cols)\n ret_types = list(self.__types)\n\n sz = 1\n name_ptr = get_string_array_pointer([self.index.name])\n new_name_ptr = get_string_array_pointer([new_name])\n\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.rename_frovedis_dataframe(host, port, \\\n self.get(), name_ptr, new_name_ptr, \\\n sz, inplace)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, ret_cols, ret_types)\n return None if inplace else ret \n\n def copy(self, deep=True):\n \"\"\"\n copy input dataframe to construct a new dataframe\n \"\"\"\n if not deep:\n raise NotImplementedError(\"copy: shallow-copy is not yet supported!\")\n if self.get() is None: # empty dataframe\n return DataFrame()\n else:\n return self[self.columns]\n\n def get(self):\n \"\"\"\n get proxy of dataframe at server side\n \"\"\"\n return self.__fdata\n\n @staticmethod\n def asDF(df):\n \"\"\"\n asDF\n \"\"\"\n if isinstance(df, DataFrame):\n return df\n elif isinstance(df, pd.DataFrame):\n return DataFrame(df)\n elif isinstance(df, pd.Series):\n return DataFrame(df=pd.DataFrame(df), is_series=True)\n else: \n raise TypeError(\"asDF: invalid dataframe type '%s' \"\n \"is provided!\" % (type(df).__name__))\n\n def __get_column_types(self, columns):\n \"\"\"\n __get_column_types\n \"\"\"\n columns = check_string_or_array_like(columns, \"__get_column_types\")\n sz = len(columns)\n types = [0]*sz\n for i in range(0, sz):\n item = columns[i]\n if item not in self.columns:\n raise ValueError(\"No column named: %s\" % str(item))\n else:\n types[i] = self.__dict__[item].dtype\n return types\n\n # returns python list of strings\n def __get_stat(self, name, columns, types=None):\n \"\"\"\n __get_stat\n \"\"\"\n if len(columns) == 0:\n return []\n if isinstance(types, list) and len(columns) != len(types):\n raise ValueError(\"Size of inputs doesn't match!\")\n if not isinstance(name, str):\n raise TypeError(\"Expected: string; Received: \", type(name).__name__)\n (host, port) = FrovedisServer.getServerInstance()\n sz = len(columns)\n cols_ptr = get_string_array_pointer(columns)\n\n if types:\n type_arr = np.asarray(types, dtype=c_short)\n tptr = type_arr.ctypes.data_as(POINTER(c_short))\n if name == 'min':\n if not types:\n raise ValueError(\"type of target columns is missing for\"\n \" min calculation\")\n ret = rpclib.get_min_frovedis_dataframe(host, port, self.get(),\n cols_ptr, tptr, sz)\n elif name == 'max':\n if not types:\n raise ValueError(\"type of target columns is missing for\"\n \" max calculation\")\n ret = rpclib.get_max_frovedis_dataframe(host, port, self.get(),\n cols_ptr, tptr, sz)\n elif name == 'sum':\n if not types:\n raise ValueError(\"type of target columns is missing for\"\n \" sum calculation\")\n ret = rpclib.get_sum_frovedis_dataframe(host, port, self.get(),\n cols_ptr, tptr, sz)\n elif name == 'std':\n ret = rpclib.get_std_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'sem':\n ret = rpclib.get_sem_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'avg' or name == 'mean':\n ret = rpclib.get_avg_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'count':\n ret = rpclib.get_cnt_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'var':\n ret = rpclib.get_var_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'median':\n ret = rpclib.get_median_frovedis_dataframe(host, port, self.get(),\n cols_ptr, tptr, sz)\n else:\n raise ValueError(\"Unknown statistics request is encountered!\")\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return ret\n\n def __get_stat_wrapper(self, func_name, columns):\n if self.__fdata is None:\n raise ValueError(\"Operation on invalid frovedis dataframe!\")\n columns = check_string_or_array_like(columns, func_name) \n\n if func_name == \"count\": # uses all columns\n types = self.__get_column_types(columns)\n return self.__get_stat('count', columns, types)\n else:\n numeric_cols, numeric_cols_types = \\\n self.__get_numeric_columns(cols=columns)\n ret = self.__get_stat(func_name, numeric_cols, numeric_cols_types)\n result_dict = dict(zip(numeric_cols, ret))\n return [result_dict.get(col, np.nan) for col in columns]\n\n def __get_numeric_columns(self, cols=None, include_bool=True):\n \"\"\"\n __get_numeric_columns\n \"\"\"\n if cols is not None:\n cols = check_string_or_array_like(cols, \"__get_numeric_columns\")\n types = self.__get_column_types(cols)\n else:\n cols = self.__cols\n types = self.__types\n\n if include_bool:\n non_numeric_types = [DTYPE.STRING]\n else:\n non_numeric_types = [DTYPE.STRING, DTYPE.BOOL]\n\n numeric_cols = []\n numeric_col_types = []\n for i in range(0, len(cols)):\n if types[i] not in non_numeric_types:\n numeric_cols.append(cols[i])\n numeric_col_types.append(types[i])\n return numeric_cols, numeric_col_types\n\n #TODO: support pandas-like input parameters and \n # improve result compatibility\n @check_association\n def describe(self):\n \"\"\"\n describe\n \"\"\"\n cols, types = self.__get_numeric_columns(include_bool=False)\n index = ['count', 'mean', 'median', 'var', 'std', 'sem', 'sum', 'min', 'max']\n return self.__agg_impl(cols, index)\n\n def __agg_impl(self, cols, index):\n \"\"\"\n agg impl\n \"\"\"\n func_ret = []\n for ind in index:\n func_ret.append(self.__get_stat_wrapper(ind, cols))\n ret = pd.DataFrame(func_ret, index=index, columns=cols)\n\n ncols = len(cols)\n types = self.__get_column_types(cols)\n has_max = 'max' in ret.index\n has_min = 'min' in ret.index\n # agg func list has std, avg/mean, then dtype = float64\n if (len(set(index).intersection(set(['mean', 'avg', 'std', \\\n 'var', 'median', 'sem']))) > 0):\n rtypes = [np.float64] * ncols\n else:\n rtypes = [np.int32 if x == DTYPE.BOOL \\\n else TypeUtil.to_numpy_dtype(x) for x in types]\n # here we are type-casting column one-by-one.\n # since some pandas version has issue in casting all\n # target columns with dictionary input for astype()\n # REF: https://github.com/pandas-dev/pandas/issues/21445\n warnings.simplefilter(action=\"ignore\", category=SettingWithCopyWarning)\n for i in range(0, ncols):\n ret[cols[i]] = ret[cols[i]].astype(rtypes[i])\n # special treatement for bool columns\n if types[i] == DTYPE.BOOL:\n if has_max:\n tmp = ret[cols[i]]['max']\n ret[cols[i]]['max'] = True if tmp == 1 else False\n if has_min:\n tmp = ret[cols[i]]['min']\n ret[cols[i]]['min'] = True if tmp == 1 else False\n warnings.simplefilter(action=\"default\", category=SettingWithCopyWarning)\n return ret \n\n @check_association\n def agg(self, func):\n if isinstance(func, str):\n return self.__agg_list([func]).transpose()[func]\n elif isinstance(func, list):\n return self.__agg_list(func)\n elif isinstance(func, dict):\n return self.__agg_dict(func)\n else:\n raise ValueError(\"Unsupported 'func' type : {0}\".format(type(func)))\n\n def __agg_list(self, func):\n return self.__agg_impl(cols=self.columns, index=func)\n\n def __agg_dict(self, func_dict):\n from itertools import chain \n func_dict = dict(func_dict)\n for col in func_dict:\n if isinstance(func_dict[col], str):\n func_dict[col] = [func_dict[col]]\n\n all_cols = list(func_dict.keys())\n all_funcs = list(set(chain.from_iterable(func_dict.values())))\n\n df_all_res = self.__agg_impl(cols=all_cols, index=all_funcs)\n data_dict = {col: {} for col in all_cols}\n\n for col in func_dict:\n for func in func_dict[col]:\n data_dict[col][func] = df_all_res[col][func]\n\n return pd.DataFrame(data_dict)\n\n @check_association\n def to_dict(self, orient=\"dict\", into=dict):\n \"\"\"\n returns dataframe columns as dictionary\n \"\"\"\n if orient not in [\"dict\", \"list\"]:\n raise ValueError(\"to_dict: supported only 'dict' and 'list' \" \\\n \"as for 'orient' parameter!\\n\")\n if into != dict:\n #if not isinstance(into, dict):\n raise ValueError(\\\n \"to_dict: supported only dictionary as per return type!\\n\")\n return self.__to_dict_impl(orient=orient, into=into)\n\n def __get_index_column(self):\n \"\"\" returns index column if present \"\"\"\n if not self.has_index():\n raise ValueError(\"input dataframe doesn't have index column!\\n\")\n\n (host, port) = FrovedisServer.getServerInstance()\n indx_dvec = rpclib.get_frovedis_col(host, port, self.get(),\n self.index.name.encode('ascii'),\n self.index.dtype)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return FrovedisDvector(indx_dvec).to_numpy_array()\n\n def __to_dict_impl(self, orient=\"dict\", into=dict, include_index=True):\n \"\"\"\n helper for to_dict\n \"\"\"\n\n out_data = OrderedDict()\n if orient == \"dict\": # presence of index is must \n if self.has_index():\n indx_arr = self.__get_index_column()\n else:\n indx_arr = np.arange(len(self), dtype=np.int64)\n elif orient == \"list\": \n if include_index and self.has_index(): # extract index, if presents\n out_data[self.index.name] = self.__get_index_column()\n \n else:\n raise ValueError(\"to_dict: supported 'orient' values are \" \\\n \"'dict' and 'list' only!\\n\")\n \n (host, port) = FrovedisServer.getServerInstance()\n for i in range(0, len(self.columns)):\n cc = self.__cols[i]\n tt = self.__types[i]\n dvec = rpclib.get_frovedis_col(host, port, self.get(),\n cc.encode('ascii'), tt)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n col_arr = FrovedisDvector(dvec).to_numpy_array()\n #TODO: fix NULL conversion in case of string-vector; \n #TODO: fix numeric to boolean conversion in case of boolean-vector\n if orient == \"dict\":\n out_data[cc] = dict(zip(indx_arr, col_arr)) # this is very slow...\n else: # list\n out_data[cc] = col_arr\n\n return out_data\n\n @check_association\n def to_pandas_dataframe(self):\n \"\"\"\n returns a pandas dataframe object from frovedis dataframe\n \"\"\"\n res = pd.DataFrame(self.__to_dict_impl(orient=\"list\", \\\n include_index=True))\n\n if self.has_index():\n res.set_index(self.index.name, inplace=True)\n if (self.index.dtype == DTYPE.BOOL):\n res.index = res.index.to_series().replace({0: False, 1: True})\n elif (self.index.dtype == DTYPE.STRING):\n res.index = res.index.to_series().replace({\"NULL\": np.nan})\n\n for col in self.columns:\n # BOOL treatment\n if (self.__dict__[col].dtype == DTYPE.BOOL):\n res[col].replace(to_replace={0: False, 1: True}, inplace=True)\n # NULL treatment for string columns\n elif (self.__dict__[col].dtype == DTYPE.STRING):\n res[col].replace(to_replace={\"NULL\": np.nan}, inplace=True)\n return res\n\n @deprecated(\"Use to_pandas_dataframe() instead!\\n\")\n def to_panda_dataframe(self):\n return self.to_pandas_dataframe()\n\n @check_association\n def to_numpy(self, dtype=None, copy=False, na_value=None):\n \"\"\"\n frovedis dataframe to numpy array conversion\n \"\"\"\n out_data = self.__to_dict_impl(orient=\"list\", include_index=False)\n return np.array(list(out_data.values()), dtype=dtype).T\n\n @property\n def values(self):\n \"\"\"\n frovedis dataframe to numpy array conversion\n \"\"\"\n return self.to_numpy()\n\n @values.setter\n def values(self, val):\n \"\"\"values setter\"\"\"\n raise AttributeError(\\\n \"attribute 'values' of DataFrame object is not writable\")\n\n @check_association\n def to_frovedis_rowmajor_matrix(self, t_cols, dtype=np.float32):\n \"\"\"\n to_frovedis_rowmajor_matrix\n \"\"\"\n for item in t_cols: # implicit checks for iterable on 't_cols'\n if item not in self.__cols:\n raise ValueError(\"No column named: %s\" % str(item))\n sz = len(t_cols)\n cols_ptr = get_string_array_pointer(t_cols)\n (host, port) = FrovedisServer.getServerInstance()\n if dtype == np.float32:\n dmat = rpclib.df_to_rowmajor(host, port, self.get(),\n cols_ptr, sz, DTYPE.FLOAT)\n elif dtype == np.float64:\n dmat = rpclib.df_to_rowmajor(host, port, self.get(),\n cols_ptr, sz, DTYPE.DOUBLE)\n else:\n raise TypeError(\"Supported types: float32/float64; Found: \" \\\n + dtype.__name__)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return FrovedisRowmajorMatrix(mat=dmat, dtype=dtype)\n\n @check_association\n def to_frovedis_colmajor_matrix(self, t_cols, dtype=np.float32):\n \"\"\"\n to_frovedis_colmajor_matrix\n \"\"\"\n for item in t_cols: # implicit checks for iterable on 't_cols'\n if item not in self.__cols:\n raise ValueError(\"No column named: %s\" % str(item))\n sz = len(t_cols)\n cols_ptr = get_string_array_pointer(t_cols)\n (host, port) = FrovedisServer.getServerInstance()\n if dtype == np.float32:\n dmat = rpclib.df_to_colmajor(host, port, self.get(),\n cols_ptr, sz, DTYPE.FLOAT)\n elif dtype == np.float64:\n dmat = rpclib.df_to_colmajor(host, port, self.get(),\n cols_ptr, sz, DTYPE.DOUBLE)\n else:\n raise TypeError(\"Supported types: float32/float64; Found: \" \\\n + dtype.__name__)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return FrovedisColmajorMatrix(mat=dmat, dtype=dtype)\n\n @check_association\n def to_frovedis_crs_matrix(self, t_cols, cat_cols,\n dtype=np.float32, #default type: float\n need_info=False):\n \"\"\"\n to_frovedis_crs_matrix\n \"\"\"\n for item in t_cols: # implicit checks for iterable on 't_cols'\n if item not in self.__cols:\n raise ValueError(\"No column named: %s\" % str(item))\n for item in cat_cols: # implicit checks for iterable on 'cat_cols'\n if item not in t_cols:\n raise ValueError(\"target column list doesn't contain\"\n \" categorical column: \", item)\n sz1 = len(t_cols)\n cols_ptr = get_string_array_pointer(t_cols)\n sz2 = len(cat_cols)\n cat_cols_ptr = get_string_array_pointer(cat_cols)\n # getting unique id for info to be registered at server side\n info_id = ModelID.get()\n (host, port) = FrovedisServer.getServerInstance()\n if dtype == np.float32:\n dmat = rpclib.df_to_crs(host, port, self.get(),\n cols_ptr, sz1,\n cat_cols_ptr, sz2,\n info_id, DTYPE.FLOAT)\n elif dtype == np.float64:\n dmat = rpclib.df_to_crs(host, port, self.get(),\n cols_ptr, sz1,\n cat_cols_ptr, sz2,\n info_id, DTYPE.DOUBLE)\n else:\n raise TypeError(\"Supported types: float32/float64; Found: \" \\\n + dtype.__name__)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n #default at server: size_t\n crs = FrovedisCRSMatrix(mat=dmat, dtype=dtype, itype=np.int64)\n info = df_to_sparse_info(info_id)\n\n if need_info:\n return crs, info\n else:\n info.release()\n return crs\n\n @check_association\n def to_frovedis_crs_matrix_using_info(self, info, dtype=np.float32):\n \"\"\"\n to_frovedis_crs_matrix_using_info\n \"\"\"\n if info.get() is None:\n raise ValueError(\"Operation on invalid frovedis dataframe\"\n \" conversion info!\")\n (host, port) = FrovedisServer.getServerInstance()\n if dtype == np.float32:\n dmat = rpclib.df_to_crs_using_info(host, port, self.get(),\n info.get(), DTYPE.FLOAT)\n elif dtype == np.float64:\n dmat = rpclib.df_to_crs_using_info(host, port, self.get(),\n info.get(), DTYPE.DOUBLE)\n else:\n raise TypeError(\"Supported types: float32/float64; Found: \" \\\n + dtype.__name__)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n #default at server: size_t\n return FrovedisCRSMatrix(mat=dmat, dtype=dtype, itype=np.int64)\n\n def filter(self, items=None, like=None, regex=None, axis=None):\n \"\"\"\n Subset the dataframe rows or columns according to the specified index labels.\n \"\"\"\n # no of keyword args\n nkw = sum(x is not None for x in (items, like, regex))\n # only 1 can be not-None\n if nkw > 1:\n raise TypeError(\n \"Keyword arguments `items`, `like`, or `regex` \"\n \"are mutually exclusive\"\n )\n\n if axis not in (None, 0, 1, 'columns', 'index'):\n raise ValueError(\"filter(): Unsupported axis '%s' is\"+\n \" provided!\" % str(axis))\n\n # default axis = 1 , i.e. column names\n if axis is None or axis == 'columns':\n axis = 1\n elif axis == 0 or axis == 'index':\n raise ValueError(\"filter() on 'index' axis is not supported for\"+\n \"frovedis DataFrame!\")\n\n if items is not None:\n targets = list(items)\n elif like is not None:\n def func(x):\n \"\"\" used for filtering \"\"\"\n return like in x\n targets = list(filter(func, self.__cols))\n elif regex is not None:\n import re\n pattern = re.compile(regex)\n def func(x):\n \"\"\" used for filtering \"\"\"\n return pattern.search(x) is not None\n targets = list(filter(func, self.__cols))\n else:\n raise TypeError(\"Must pass either `items`, `like`, or `regex`\")\n return self.select_frovedis_dataframe(targets)\n\n def apply(self, func, axis=0, raw=False, \\\n result_type=None, args=(), **kwds):\n return self.to_pandas_dataframe()\\\n .apply(func, axis, raw, result_type, args)\n\n @check_association\n def isna(self):\n ncol = len(self.__cols)\n cols_ptr = get_string_array_pointer(self.__cols)\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.isnull_frovedis_dataframe(host, port, self.get(), \\\n cols_ptr, ncol, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret = DataFrame()\n ret.num_row = len(self)\n ret.index = self.index\n ret_cols = list(self.__cols)\n ret_types = [DTYPE.BOOL]*len(self)\n ret.load_dummy(proxy, ret_cols, ret_types)\n if not self.has_index():\n ret.add_index(\"index\")\n return ret\n\n def isnull(self):\n return self.isna()\n\n @check_association\n def drop_duplicates(self, subset=None, keep='first', inplace=False, \\\n ignore_index=False):\n \"\"\" \n drops duplicate rows for specified columns (None: all columns).\n \"\"\"\n if subset is None:\n targets = self.columns # for all columns by default\n else: # must be an iterable\n targets = []\n for col in np.unique(subset): # handling duplicate columns\n if col in self.__cols:\n targets.append(col)\n else:\n raise KeyError(\"Index[\" + col + \"] is not found!\")\n\n if keep != 'first' and keep != 'last':\n raise ValueError(\"drop_duplicates: currently supports only \" \\\n \"'first' or 'last' as for 'keep' parameter!\")\n sz = len(targets)\n targets_ptr = get_string_array_pointer(targets)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.drop_frovedis_duplicate_rows(host, port, \\\n self.get(), targets_ptr, sz, \\\n keep.encode('ascii'))\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret = self if inplace else DataFrame()\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n if ignore_index:\n ret.reset_index(drop=True, inplace=True)\n return None if inplace else ret\n \n def drop(self, labels=None, axis=0, index=None, columns=None, \\\n level=None, inplace=False, errors='raise'):\n \"\"\" drops specified labels from rows or columns. \"\"\"\n if columns is not None:\n ret = self.drop_cols(targets=columns, inplace=inplace)\n elif index is not None:\n ret = self.drop_rows(targets=index, inplace=inplace)\n else:\n if labels is None:\n raise TypeError(\"drop() takes at least 2 arguments (1 given)\")\n if axis == 0:\n ret = self.drop_rows(targets=labels, inplace=inplace)\n elif axis == 1:\n ret = self.drop_cols(targets=labels, inplace=inplace)\n else:\n raise ValueError(\"drop(): No axis named %d for \" \\\n \"object type %s\" % (axis, self.__class__))\n return ret \n \n @check_association\n def drop_cols(self, targets, inplace=False):\n \"\"\" drops specified columns from input dataframe. \"\"\"\n targets = check_string_or_array_like(targets, \"drop\")\n\n if inplace:\n for item in targets:\n try:\n idx = self.__cols.index(item)\n self.__cols.pop(idx)\n self.__types.pop(idx)\n del self.__dict__[item]\n except ValueError as ve: #item might not be present in col-list\n raise ValueError(\"drop: No column named: %s\" % str(item))\n\n sz = len(targets)\n targets_ptr = get_string_array_pointer(targets)\n (host, port) = FrovedisServer.getServerInstance()\n rpclib.drop_frovedis_dataframe_columns(host, port, \\\n self.get(), targets_ptr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n else:\n cols = list(self.__cols)\n for item in targets:\n if item not in cols:\n raise ValueError(\"drop: No column named: %s\" % str(item))\n else:\n cols.remove(item)\n return self[cols] # just select the required columns\n\n @check_association\n def drop_rows(self, targets, inplace=False):\n \"\"\" drops specified columns from input dataframe. \"\"\"\n if not self.has_index():\n raise ValueError(\"drop(): input dataframe doesn't \" \\\n \"have any index column!\")\n\n if isinstance(targets, str):\n targets = [targets]\n if isinstance(targets, numbers.Number):\n targets = [targets]\n elif isinstance(targets, Iterable):\n targets = np.unique(targets)\n else:\n raise ValueError(\"drop: given indices must be an iterable!\")\n\n sz = len(targets)\n dtype = self.index.dtype\n index_col = self.index.name.encode('ascii')\n (host, port) = FrovedisServer.getServerInstance()\n\n if dtype == DTYPE.INT:\n targets = np.asarray(targets, dtype=np.int32)\n targets_ptr = targets.ctypes.data_as(POINTER(c_int))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_int(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.LONG:\n targets = np.asarray(targets, dtype=np.int64)\n targets_ptr = targets.ctypes.data_as(POINTER(c_long))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_long(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.ULONG:\n targets = np.asarray(targets, dtype=np.uint)\n targets_ptr = targets.ctypes.data_as(POINTER(c_ulong))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_ulong(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.FLOAT:\n targets = np.asarray(targets, dtype=np.float32)\n targets_ptr = targets.ctypes.data_as(POINTER(c_float))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_float(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.DOUBLE:\n targets = np.asarray(targets, dtype=np.float64)\n targets_ptr = targets.ctypes.data_as(POINTER(c_double))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_double(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.STRING:\n targets_ptr = get_string_array_pointer(targets)\n dummy_df = rpclib.drop_frovedis_dataframe_rows_str(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n else:\n raise TypeError(\\\n \"drop(): Unsupported index column dtype is detected!\")\n\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret = self if inplace else DataFrame()\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return None if inplace else ret\n\n def __get_dvec(self, dtype, val):\n \"\"\"\n get dvector from numpy array\n \"\"\"\n dvec_constructor_map = { DTYPE.INT: FrovedisIntDvector,\n DTYPE.LONG: FrovedisLongDvector,\n DTYPE.ULONG: FrovedisULongDvector,\n DTYPE.FLOAT: FrovedisFloatDvector,\n DTYPE.DOUBLE: FrovedisDoubleDvector,\n DTYPE.STRING: FrovedisStringDvector,\n DTYPE.BOOL: FrovedisIntDvector\n }\n if dtype not in dvec_constructor_map:\n raise ValueError(\"Unsupported dtype for creating dvector: {0}!\\n\"\n .format(dtype))\n if dtype == DTYPE.BOOL:\n val = np.array(val).astype(np.int32)\n res = dvec_constructor_map[dtype](val)\n return res\n\n def __append_column(self, col_name, data_type, data, position=None,\n drop_old=False):\n if col_name is None:\n raise ValueError(\"cannot label index with a null key\")\n elif not isinstance(col_name, str):\n raise TypeError(\"expected a string parameter for 'col_name'! \"\n \"received: '%s'\" % (type(col_name).__name__))\n\n if position is None:\n pos = -1\n elif isinstance(position, int):\n if position < 0 or position > (len(self.columns)):\n raise ValueError(\"Invalid position for appending column : {} !\"\n .format(position))\n if self.has_index():\n pos = position + 1 # 0 is reserved for index column\n else:\n pos = position\n else:\n raise TypeError(\"Invalid type for position, for appending \"\n \"column: {} !\".format(position))\n\n data_type = TypeUtil.to_id_dtype(data_type)\n is_bool = (data_type == DTYPE.BOOL)\n dvec = self.__get_dvec(data_type, data)\n (host, port) = FrovedisServer.getServerInstance()\n df_proxy = -1\n if self.__fdata:\n df_proxy = self.get()\n dummy_df = rpclib.df_append_column(host, port, df_proxy,\n col_name.encode(\"ascii\"),\n data_type, dvec.get(),\n pos, drop_old)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n # dvector 'dvec' is already destructed during append column.\n # thus resetting the metadata to avoid double free issue from\n # server side during destructor call of the dvector 'dvec'\n dvec.reset()\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n if is_bool:\n ind = names.index(col_name)\n types[ind] = DTYPE.BOOL\n\n bool_cols = set([self.__cols[i] for i in range(len(self.__types)) \\\n if self.__types[i] == DTYPE.BOOL])\n if len(bool_cols) > 0:\n for i in range(len(names)):\n if names[i] in bool_cols:\n types[i] = DTYPE.BOOL\n\n self.num_row = dummy_df[\"nrow\"]\n if self.has_index() or \\\n df_proxy == -1: # empty dataframe case: new index column is added\n self.index = FrovedisColumn(names[0], types[0]) #setting index\n self.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n self.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n return self\n\n def __get_dtype_name(self, arr): #TODO: improve\n if arr.dtype.name != 'object':\n if arr.dtype.char in (\"U\", \"S\"):\n return \"str\"\n else:\n return arr.dtype.name\n\n # if dtype is object\n arr_without_nan = np.array(list(filter(lambda x: x == x, arr)))\n if arr_without_nan.dtype.name != 'object':\n if arr_without_nan.dtype.char in (\"U\", \"S\"):\n return \"str\"\n else:\n return arr_without_nan.dtype.name\n elif all(isinstance(e, str) for e in arr_without_nan):\n return \"str\"\n else:\n # mixed dtypes\n raise ValueError(\"Cannot convert the values for the given data! \",\n arr)\n\n return res\n\n def __setitem__(self, key, value):\n \"\"\"\n Interface for appending column into DataFrame\n \"\"\"\n if key is None:\n raise ValueError(\"cannot label index with a null key\")\n elif isinstance(key, str):\n key = [key]\n elif not isinstance(key, list):\n raise TypeError(\"__setitem__: supported types for 'key' parameter \"\n \"are either string or list! received: '%s'\"\n % (type(key).__name__))\n\n if isinstance(value, (DataFrame, pd.DataFrame)):\n self.copy_column(value, names_as=key, inplace=True) \n else:\n if np.isscalar(value):\n if self.__fdata is None:\n raise ValueError(\"__setitem__: Frovedis currently doesn't \"\n \"support adding column with scalar \"\n \"values on empty dataframe!\")\n is_imax = (value == np.iinfo(np.int32).max)\n value = [value] * len(self)\n if is_imax: # check to avoid long array construction by default\n value = np.asarray(value, dtype=np.int32)\n else:\n value = np.asarray(value) # deduce type\n elif isinstance(value, (list, pd.Series, np.ndarray)):\n value = np.asarray(value)\n value = np.array(list(map(lambda x: np.nan if x is None else x, value)))\n if value.ndim != 1:\n raise ValueError(\\\n \"array is not broadcastable to correct shape\")\n if self.__fdata is not None and len(value) != len(self):\n raise ValueError(\"Length of values (%d) does not match \" \\\n \"with length of index (%d)\" % (len(value), len(self)))\n else:\n raise ValueError(\"__setitem__: Given column data type '{}' \"\n \"is not supported!\".format(type(value)))\n\n col_dtype = np.dtype(self.__get_dtype_name(value))\n for k in key:\n drop_old = False\n if self.__fdata and k in self.columns:\n drop_old = True\n self = self.__append_column(k, col_dtype, value, None, drop_old)\n return self\n\n def insert(self, loc, column, value, allow_duplicates=False):\n \"\"\"\n Insert column into DataFrame at specified location.\n \"\"\"\n if allow_duplicates == True: #TODO: allow it\n raise ValueError(\"insert: Frovedis does not support duplicate \"\n \"column names !\")\n\n if np.isscalar(value):\n if self.__fdata is None:\n raise ValueError(\"insert: Frovedis currently doesn't \"\n \"support adding column with scalar values \"\n \"on empty dataframe!\")\n is_imax = (value == np.iinfo(np.int32).max)\n value = [value] * len(self)\n if is_imax: # check to avoid long array construction by default\n value = np.asarray(value, dtype=np.int32)\n else:\n value = np.asarray(value) # deduce type\n elif isinstance(value, (list, pd.Series, np.ndarray)):\n value = np.asarray(value)\n value = np.array(list(map(lambda x: np.nan if x is None else x, value)))\n if value.ndim != 1:\n raise ValueError(\"array is not broadcastable to correct shape\")\n if self.__fdata is not None and len(value) != len(self):\n raise ValueError(\\\n \"Length of values does not match length of index\")\n else:\n raise ValueError(\"insert: Given column data type '{}' is \"\n \"not supported!\".format(type(value)))\n\n col_dtype = np.dtype(self.__get_dtype_name(value))\n if self.__fdata is None:\n if loc != 0: #insert in empty df, allowed loc = 0 only\n raise IndexError(\"insert: index '{}' is out of bounds for the \"\n \"given dataframe!\".format(loc))\n self = self.__append_column(column, col_dtype, value)\n else:\n if column in self.columns:\n raise ValueError(\"insert: The given column '{}' already exists !\"\n .format(column))\n self = self.__append_column(column, col_dtype, value, loc)\n return self\n\n @check_association\n def update_index(self, value, key=None, \\\n verify_integrity=False, inplace=False):\n \"\"\"\n updates/sets index values: pandas-like df.index = [...]\n \"\"\"\n if inplace: # copy may still take place, if self needs materialize \n ret = self\n else:\n ret = self.copy()\n \n if not isinstance(value, Iterable):\n raise TypeError(\"given index value must be an iterable!\")\n if verify_integrity:\n if len(np.unique(value)) != len(value):\n raise ValueError(\"given index values are not unique!\")\n\n col_data = np.asarray(value)\n col_dtype = self.__get_dtype_name(col_data)\n\n if ret.has_index():\n if key is not None: #rename required\n if ret.index.name != key: \n ret.rename_index(key, inplace=True) \n drop_old = True # existing index column will be dropped\n position = None # adds given column in same position (as in existing index)\n else:\n if key is None:\n key = \"index\" # default name to index-column\n drop_old = False # no index column to drop\n position = 0 # adds given column as index in 0th position\n ret = ret.__append_column(key, np.dtype(col_dtype), col_data, \\\n position, drop_old)\n return None if inplace else ret\n\n #TODO: support drop=False, multi-level index\n @check_association\n def set_index(self, keys, drop=True, append=False,\n inplace=False, verify_integrity=False): \n \"\"\" sets the index column of self \"\"\"\n if not drop:\n raise NotImplementedError(\"set_index: currently frovedis \" \\\n \"doesn't support drop=False!\")\n\n if not isinstance(keys, list):\n keys = [keys]\n \n # multi-level index case\n if append or len(keys) > 1:\n raise NotImplementedError(\"set_index: currently frovedis \" \\\n \"doesn't support multi-level index!\")\n\n if inplace: # copy may still take place, if self needs materialize\n ret = self\n else:\n ret = self.copy()\n\n if isinstance(keys[0], str): # keys = [\"colname\"]\n new_index_name = keys[0] \n cur_index_name = self.index.name if self.has_index() else \"\"\n if not new_index_name in ret.__cols:\n raise KeyError(\"set_index: '%s' key does not found in \" \\\n \"existing columns!\" % (new_index_name))\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_set_index(host, port, ret.get(), \\\n cur_index_name.encode(\"ascii\"), \\\n new_index_name.encode(\"ascii\"), \\\n verify_integrity)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.index = FrovedisColumn(names[0], types[0]) # with new index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n elif isinstance(keys[0], Iterable): # keys = [[1,2,3,4]]\n k = np.asarray(keys[0])\n if k.ndim != 1:\n raise ValueError(\"set_index: expected a one-dimensional key!\")\n ret.update_index(k, key=\"index\", \\\n verify_integrity=verify_integrity, inplace=True)\n else:\n raise TypeError(\"set_index: unknown type of 'keys' found!\")\n return None if inplace else ret \n\n @check_association\n def reset_index(self, drop=False, inplace=False): #TODO: support other params\n \"\"\" resets the index column of self \"\"\"\n if inplace: # copy may still take place, if self needs materialize\n ret = self\n else:\n ret = self.copy()\n\n if ret.has_index():\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_reset_index(host, port, ret.get(), \\\n drop)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n bool_cols = set([self.__cols[i] for i in range(len(self.__types)) \\\n if self.__types[i] == DTYPE.BOOL])\n if len(bool_cols) > 0:\n for i in range(len(names)):\n if names[i] in bool_cols:\n types[i] = DTYPE.BOOL\n\n ret.index = FrovedisColumn(names[0], types[0]) # with new index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret = ret.add_index(\"index\")\n return None if inplace else ret\n\n @check_association\n def copy_index(self, from_df, inplace=False, overwrite=True): \n \"\"\" copies index column from 'from_df' to self \"\"\"\n from_df = DataFrame.asDF(from_df)\n if not from_df.has_index():\n raise ValueError(\"from_df doesn't have any index column!\")\n\n if self.has_index():\n if not overwrite and from_df.index.name == self.index.name:\n raise ValueError(\"input dataframe already has an index \"\\\n \"column with same name!\")\n\n if inplace: # copy may still take place, if self needs materialize\n ret = self\n else:\n ret = self.copy()\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_copy_index(host, port, ret.get(), from_df.get(), \\\n from_df.index.name.encode(\"ascii\"), \\\n from_df.index.dtype)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return None if inplace else ret\n\n def copy_column(self, from_df, names_as=None, inplace=False): \n \"\"\" \n copies all columns from 'from_df' to self. if 'names_as' is given, \n copied columns would be renamed based on 'names_as'\n \"\"\"\n names = list(from_df.columns)\n if names_as is None:\n names_as = names\n elif isinstance(names_as, str):\n names_as = [names_as]\n elif not isinstance(names_as, list):\n raise TypeError(\"copy: supported types for 'names_as' parameter \"\n \"is either string or list! Received '%s' \"\n % (type(names_as).__name__))\n\n if len(names) != len(names_as):\n raise ValueError(\"Columns must be same length as key\")\n \n from_df = DataFrame.asDF(from_df)\n types = np.asarray(from_df.get_types(), dtype=c_short)\n sz = len(types)\n names_arr = get_string_array_pointer(names)\n names_as_arr = get_string_array_pointer(names_as)\n types_arr = types.ctypes.data_as(POINTER(c_short))\n\n if inplace: # copy may still take place, if self needs materialize\n ret = self\n else:\n ret = self.copy()\n\n if ret.__fdata is None: # self is empty DataFrame\n ret.__fdata = -1\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_copy_column(host, port, ret.get(), \\\n from_df.get(), names_arr, \\\n names_as_arr, types_arr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return None if inplace else ret\n\n @check_association\n def add_index(self, name): # behavior: inplace=True\n \"\"\" adds index column to self \"\"\"\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_add_index(host, port, self.get(),\n name.encode(\"ascii\"))\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n bool_cols = set([self.__cols[i] for i in range(len(self.__types)) \\\n if self.__types[i] == DTYPE.BOOL])\n if len(bool_cols) > 0:\n for i in range(len(names)):\n if names[i] in bool_cols:\n types[i] = DTYPE.BOOL\n\n self.index = FrovedisColumn(names[0], types[0]) #setting index\n self.num_row = dummy_df[\"nrow\"]\n self.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return self\n\n @check_association\n def astype(self, dtype, copy=True, errors='raise', \n check_bool_like_string=False):\n \"\"\" \n Casts a frovedis DataFrame object to a specified dtype \n\n check_bool_like_string: added parameter; if True, can cast string column\n having bool like case-insensitive strings (True, False, yes, No, \n On, Off, Y, N, T, F) to boolean columns\n \"\"\"\n t_cols = []\n t_dtypes = []\n if isinstance (dtype, (str, type)):\n numpy_dtype = np.dtype(dtype)\n t_cols = list(self.columns)\n t_dtypes = [TypeUtil.to_id_dtype(numpy_dtype)] * len(t_cols)\n elif isinstance (dtype, dict): # might include index as well\n for k, v in dtype.items():\n if k in self.columns or \\\n (self.has_index() and k == self.index.name):\n t_cols.append(k)\n t_dtypes.append(TypeUtil.to_id_dtype(np.dtype(v)))\n else:\n raise TypeError(\"astype: supports only string, numpy.dtype \" \\\n \"or dict object as for 'dtype' parameter!\")\n\n ret = self.copy() # always returns a new dataframe (after casting)\n (host, port) = FrovedisServer.getServerInstance()\n t_cols_ptr = get_string_array_pointer(t_cols)\n type_arr = np.asarray(t_dtypes, dtype=c_short)\n t_dtypes_ptr = type_arr.ctypes.data_as(POINTER(c_short))\n dummy_df = rpclib.df_astype(host, port, ret.get(), t_cols_ptr, \\\n t_dtypes_ptr, len(t_cols), \\\n check_bool_like_string)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n \n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n for i in range(0, len(t_dtypes)):\n if t_dtypes[i] == DTYPE.BOOL:\n col = t_cols[i]\n ind = names.index(col) \n types[ind] = DTYPE.BOOL\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n return ret\n\n @check_association\n def append(self, other, ignore_index=False, verify_integrity=False,\n sort=False):\n if isinstance(other, DataFrame):\n other = [other]\n is_frov_df = [True]\n elif isinstance(other, pd.DataFrame):\n other = [DataFrame.asDF(other)]\n is_frov_df = [False]\n elif isinstance(other, list):\n is_frov_df = [isinstance(e, DataFrame) for e in other]\n other = [DataFrame.asDF(e) for e in other]\n else:\n raise ValueError(\"append: unsupported type '%s' for \"\n \"'other'!\" % (type(other).__name__))\n \n dfs = [self] + other\n is_frov_df = [True] + is_frov_df # prepending [True]; self is DataFrame\n res_names = [self.columns] \n for e in other:\n res_names.append(e.columns)\n res_names = union_lists(res_names)\n res_dtypes = [infer_dtype(dfs, col) for col in res_names]\n astype_input = dict(zip(res_names, res_dtypes))\n #print(astype_input)\n dfs = add_null_column_and_type_cast(dfs, is_frov_df, astype_input)\n\n # preserving column order as in self, if not to be sorted\n res_names = sorted(dfs[0].columns) if sort else dfs[0].columns\n all_cols = [dfs[0].index.name] + res_names # adding index\n proxies = np.asarray([e.get() for e in dfs[1:]]) # default dtype=long\n proxies_ptr = proxies.ctypes.data_as(POINTER(c_long))\n verify_integrity = False if ignore_index else verify_integrity\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_union(host, port, dfs[0].get(), \\\n proxies_ptr, len(proxies), \\\n get_string_array_pointer(all_cols), \\\n len(all_cols), verify_integrity)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n for c, t in astype_input.items():\n if t == np.bool:\n # searching index, since dictionary items might not be ordered\n ind = names.index(c) \n types[ind] = DTYPE.BOOL\n res = DataFrame().load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n res.index = FrovedisColumn(names[0], types[0]) #setting index\n res.num_row = dummy_df[\"nrow\"]\n if ignore_index:\n res.reset_index(inplace=True, drop=True)\n return res\n\n @check_association\n def __set_col_order(self, new_cols):\n if not isinstance(new_cols, list):\n raise ValueError(\"__set_col_order: The new column order to be set\"\n \" must be provided as list of strings!\")\n else:\n check = all([ isinstance(e, str) for e in new_cols ] )\n if not check:\n raise ValueError(\"__set_col_order: The new column order to be set\"\n \" must be provided as list of strings!\")\n current_col_order = self.columns\n if self.has_index():\n current_col_order = [self.index.name] + current_col_order\n\n if len(current_col_order) != len(new_cols):\n raise ValueError(\"__set_col_order: The new column order to be set\"\n \" must have same number of columns as the dataframe!\")\n\n if set(current_col_order) != set(new_cols):\n raise ValueError(\"__set_col_order: The new column order to be set\"\n \" must have same column names as the dataframe!\")\n\n sz = len(new_cols)\n new_cols_ptr = get_string_array_pointer(new_cols)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_set_col_order(host, port, self.get(),\n new_cols_ptr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n self.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n self.index = FrovedisColumn(names[0], types[0]) #setting index\n self.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n self.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n return self\n\n def get_types(self):\n return self.__types\n\n def get_dtype(self, colname):\n \"\"\"\n returns numpy_dtype of given column, \n in case presents in (self.index.name or self.columns).\n otherwise, raises ValueError\n \"\"\"\n if self.has_index() and colname == self.index.name:\n ret = TypeUtil.to_numpy_dtype(self.index.dtype)\n elif colname in self.columns:\n ret = TypeUtil.to_numpy_dtype(self.__dict__[colname].dtype)\n else:\n raise ValueError(\"column not found: '%s'\" % (colname))\n return ret\n\n @check_association\n def fillna(self, value=None, method=None, axis=None, \n inplace=False, limit=None, downcast=None):\n \"\"\" \n replaces nulls in each column with given value\n \"\"\"\n if method is not None:\n raise NotImplementedError(\"fillna: currently doesn't support \"\n \"method: '%s'\" % method)\n\n if limit is not None:\n raise NotImplementedError(\"fillna: currently doesn't support \"\n \"limit: '%d'\" % limit)\n\n if downcast is not None:\n raise NotImplementedError(\"fillna: currently doesn't support \"\n \"downcasting!\")\n\n if axis is None:\n axis = 1 # columns\n elif axis not in (1, 'columns'):\n raise NotImplementedError(\"fillna: can only be performed \"\\\n \"on axis=1 (columns)\")\n\n if value is None: \n raise ValueError(\"fillna: must specify a value\")\n elif value is np.nan:\n return None if inplace else self.copy() # no need for any replacement\n elif not np.isscalar(value):\n raise NotImplementedError(\"fillna: curreently supports only \"\\\n \"scalar values for 'value' parameter, \"\\\n \"received: '%s'\" % type(value).__name__)\n value = str(value)\n if inplace:\n ret = self\n else:\n ret = DataFrame(is_series=self.is_series)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_fillna(host, port, \\\n self.get(), value.encode('ascii'), \\\n self.has_index())\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return None if inplace else ret\n\n # optimized implementation for query like \"self.isna().sum(axis=0)\"\n @check_association\n def countna(self, axis=0):\n \"\"\" counts number of missing values in the given axis \"\"\"\n if axis not in [0, 1, \"index\", \"columns\"]:\n raise ValueError(\"No axis named '%s' for DataFrame object\" % str(axis))\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_countna(host, port, self.get(), \\\n axis, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def dropna(self, axis=0, how='any', thresh=None, subset=None, inplace=False):\n \"\"\" drops rows/columns having null values\"\"\"\n if inplace:\n ret = self\n else:\n ret = DataFrame(is_series=self.is_series)\n\n if thresh is None:\n thresh = np.iinfo(np.uint).max\n elif not isinstance(thresh, int):\n raise ValueError(\\\n \"dropna: expected an integer value for 'thresh' parameter!\\n\")\n\n (host, port) = FrovedisServer.getServerInstance()\n if axis == 0: # dropna by rows (extraction subset: column names)\n if subset is None: \n subset = self.columns\n sz = len(subset)\n targets_ptr = get_string_array_pointer(subset)\n dummy_df = rpclib.df_dropna_by_rows(host, port, \\\n self.get(), targets_ptr, sz, \\\n how.encode('ascii'), thresh)\n elif axis == 1: # dropna by cols (extraction subset: index values)\n if not self.has_index():\n raise ValueError(\n \"dropna: input dataframe doesn't have an index column!\")\n index_nm = self.index.name.encode('ascii')\n if subset is None:\n subset = np.asarray([], dtype=np.int32) # int32: dummy type\n sz = len(subset)\n targets_ptr = subset.__array_interface__['data'][0]\n dummy_df = rpclib.df_dropna_by_cols_with_numeric_icol( \\\n host, port, \\\n self.get(), index_nm, targets_ptr, sz, \\\n how.encode('ascii'), thresh, DTYPE.INT)\n else:\n tt = self.index.dtype\n subset = np.asarray(subset, dtype=TypeUtil.to_numpy_dtype(tt))\n sz = len(subset)\n if tt != DTYPE.STRING:\n targets_ptr = subset.__array_interface__['data'][0]\n dummy_df = rpclib.df_dropna_by_cols_with_numeric_icol( \\\n host, port, \\\n self.get(), index_nm, targets_ptr, sz, \\\n how.encode('ascii'), thresh, tt)\n else:\n targets_ptr = get_string_array_pointer(subset)\n dummy_df = rpclib.df_dropna_by_cols_with_string_icol( \\\n host, port, \\\n self.get(), index_nm, targets_ptr, sz, \\\n how.encode('ascii'), thresh)\n else:\n raise ValueError(\\\n \"dropna: Unsupported axis parameter: '%d'\" % (axis))\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n ret.num_row = dummy_df[\"nrow\"]\n return None if inplace else ret\n\n @check_association\n def __binary_operator_impl(self, other, op_type, \\\n axis='columns', level=None, \n fill_value=None, is_rev=False):\n \"\"\" \n implements binary opeartions (+, -, *, /, //, %) of \n two dataframes invoking server side operations \n \"\"\"\n if not self.has_index():\n raise TypeError(op_type + \\\n \": input dataframe must have index column!\")\n\n if self.get() is None:\n raise ValueError(op_type + \": invoked on empty dataframe!\")\n\n if DTYPE.STRING in self.get_types(): \n raise NotImplementedError(op_type + \\\n \": table contains string column. Arithmetic operations \"\\\n \"on string column is not supported currently!\")\n \n if axis not in (1, 'columns'):\n raise NotImplementedError(op_type + \\\n \": can only be performed on axis=1 (columns)\")\n\n if fill_value is None or fill_value is np.nan:\n fillv = \"NULL\"\n fillv_dt = \"none\"\n elif np.isscalar(fill_value):\n fillv = str(fill_value)\n fillv_dt = get_python_scalar_type(fill_value)\n else:\n raise NotImplementedError(op_type + \\\n \": supports either None or scalar as for 'fill_value', \"\\\n \"received: %s\" % (fill_value))\n\n if np.isscalar(other):\n if not isinstance(other, (numbers.Number, np.integer, \\\n np.float32, np.float64)): \n raise TypeError(op_type + \\\n \": supported type of 'other' parameter is either DataFrame \"\\\n \"or numbers. Received: '%s'\" % type(other).__name__)\n immed = True\n immed_val = str(other)\n immed_dt = get_python_scalar_type(other)\n is_series = self.is_series\n elif isinstance(other, (list, np.ndarray)):\n other = np.asarray(other)\n is_numeric = all([isinstance(e, numbers.Number) for e in other])\n if not is_numeric:\n raise NotImplementedError(op_type + \\\n \": array-like other contains non-numeric values!\")\n if other.ndim != 1:\n raise ValueError(op_type + \\\n \": multi-dimensional array-like 'other' is not supported!\")\n # below implementation is according to axis = 1\n nrow = len(self)\n ncol = len(self.columns)\n if ncol == 1:\n if len(other) != nrow:\n raise ValueError(op_type + \": Unable to coerce to Series,\" \\\n \" length must be %d: given %d\"\n % (nrow, len(other)))\n other = DataFrame(pd.DataFrame(other, columns=self.columns))\n else:\n if len(other) != ncol:\n raise ValueError(op_type + \": Wrong number of items \" \\\n \"passed %d, placement implies %d\" \\\n % (len(other), ncol))\n tmp_df = pd.DataFrame()\n for i in range(0, ncol):\n tmp_df[self.columns[i]] = [other[i]] * nrow\n other = DataFrame(tmp_df)\n immed = False\n is_series = False\n other.copy_index(self, inplace=True, overwrite=True)\n else:\n other = DataFrame.asDF(other)\n if other.get() is None:\n raise ValueError(op_type + \": right table is empty!\")\n if DTYPE.STRING in other.get_types(): \n raise NotImplementedError(op_type + \\\n \": right table contains string column. Arithmetic operations \"\\\n \"on string column is not supported currently!\")\n immed = False\n is_series = self.is_series and other.is_series\n \n (host, port) = FrovedisServer.getServerInstance()\n # nan values can be generated during pow, div, mod operations\n # and pandas treats nan values as null\n if op_type in (\"pow\", \"fdiv\", \"idiv\", \"mod\"):\n nan_is_null = True\n else:\n nan_is_null = False \n \n if immed:\n # any operation with immediate value as nan would produce nan\n if other is np.nan:\n nan_is_null = True\n dummy_df = rpclib.df_immed_binary_operation(host, port, \\\n self.get(), immed_val.encode('ascii'), \\\n immed_dt.encode('ascii'), \\\n op_type.encode('ascii'), is_rev, nan_is_null)\n else:\n if is_rev:\n left, right = other, self\n else:\n left, right = self, other\n dummy_df = rpclib.df_binary_operation(host, port, left.get(), \\\n right.get(), is_series, fillv.encode('ascii'), \\\n fillv_dt.encode('ascii'), \\\n op_type.encode('ascii'), nan_is_null)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret = DataFrame(is_series=is_series)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n #sorting columns as per pandas result\n ret.__set_col_order([names[0]] + sorted(names[1:]))\n return ret\n\n @check_association\n def abs(self):\n \"\"\" \n returns resultant dataframe after performing \n absolute value of each column\n \"\"\"\n if not self.has_index():\n raise TypeError(\"abs: input dataframe must have index column!\")\n\n if DTYPE.STRING in self.get_types(): \n raise TypeError(\"bad operand type for abs(): 'str'\")\n \n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_abs(host, port, self.get())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret = DataFrame(is_series=self.is_series)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n # treatment of bool columns\n for i in range(0, len(names)):\n if self.__dict__[names[i]].dtype == DTYPE.BOOL:\n types[i] = DTYPE.BOOL\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n\n def add(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self + other \"\"\"\n return self.__binary_operator_impl(other, \"add\", axis, level, \\\n fill_value, is_rev=False)\n\n def radd(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other + self\"\"\"\n return self.__binary_operator_impl(other, \"add\", axis, level, \\\n fill_value, is_rev=True)\n\n def __add__(self, other):\n \"\"\" \n overloaded binary operator+ (wrapper of self.add())\n returns resultant dataframe after adding self + other \n \"\"\"\n return self.add(other)\n\n def __IADD__(self, other):\n \"\"\" \n overloaded binary operator+= to perform self += other \n \"\"\"\n self = self.add(other)\n\n def sub(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self - other \"\"\"\n return self.__binary_operator_impl(other, \"sub\", axis, level, \\\n fill_value, is_rev=False)\n\n def rsub(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other - self\"\"\"\n return self.__binary_operator_impl(other, \"sub\", axis, level, \\\n fill_value, is_rev=True)\n\n def __sub__(self, other):\n \"\"\" \n overloaded binary operator- (wrapper of self.sub())\n returns resultant dataframe after adding self - other \n \"\"\"\n return self.sub(other)\n\n def __ISUB__(self, other):\n \"\"\" \n overloaded binary operator-= to perform self -= other \n \"\"\"\n self = self.sub(other)\n\n def mul(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self * other \"\"\"\n return self.__binary_operator_impl(other, \"mul\", axis, level, \\\n fill_value, is_rev=False)\n\n def rmul(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other * self\"\"\"\n return self.__binary_operator_impl(other, \"mul\", axis, level, \\\n fill_value, is_rev=True)\n\n def __mul__(self, other):\n \"\"\" \n overloaded binary operator* (wrapper of self.mul())\n returns resultant dataframe after adding self * other \n \"\"\"\n return self.mul(other)\n\n def __IMUL__(self, other):\n \"\"\" \n overloaded binary operator*= to perform self *= other \n \"\"\"\n self = self.mul(other)\n\n def truediv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self / other \"\"\"\n return self.__binary_operator_impl(other, \"fdiv\", axis, level, \\\n fill_value, is_rev=False)\n\n def rtruediv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other / self\"\"\"\n return self.__binary_operator_impl(other, \"fdiv\", axis, level, \\\n fill_value, is_rev=True)\n\n def div(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self / other \"\"\"\n return self.truediv(other, axis, level, fill_value)\n\n def rdiv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self / other \"\"\"\n return self.rtruediv(other, axis, level, fill_value)\n\n def __div__(self, other):\n \"\"\" \n overloaded binary operator/ for python 2.x (wrapper of self.truediv())\n returns resultant dataframe after adding self / other \n \"\"\"\n return self.truediv(other)\n\n def __truediv__(self, other):\n \"\"\" \n overloaded binary operator/ (wrapper of self.truediv())\n returns resultant dataframe after adding self / other \n \"\"\"\n return self.truediv(other)\n\n def __IDIV__(self, other):\n \"\"\" \n overloaded binary operator/= to perform self /= other \n \"\"\"\n self = self.truediv(other)\n\n def floordiv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self // other \"\"\"\n return self.__binary_operator_impl(other, \"idiv\", axis, level, \\\n fill_value, is_rev=False)\n\n def rfloordiv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other // self\"\"\"\n return self.__binary_operator_impl(other, \"idiv\", axis, level, \\\n fill_value, is_rev=True)\n\n def __floordiv__(self, other):\n \"\"\" \n overloaded binary operator// (wrapper of self.floordiv())\n returns resultant dataframe after adding self // other \n \"\"\"\n return self.floordiv(other)\n\n def __IFLOORDIV__(self, other):\n \"\"\" \n overloaded binary operator//= to perform self //= other \n \"\"\"\n self = self.floordiv(other)\n\n def mod(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self % other \"\"\"\n return self.__binary_operator_impl(other, \"mod\", axis, level, \\\n fill_value, is_rev=False)\n\n def rmod(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other % self\"\"\"\n return self.__binary_operator_impl(other, \"mod\", axis, level, \\\n fill_value, is_rev=True)\n\n def __mod__(self, other):\n \"\"\" \n overloaded binary operator% (wrapper of self.mod())\n returns resultant dataframe after adding self % other \n \"\"\"\n return self.mod(other)\n\n def __IMOD__(self, other):\n \"\"\" \n overloaded binary operator%= to perform self %= other \n \"\"\"\n self = self.mod(other)\n\n def pow(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self ** other \"\"\"\n return self.__binary_operator_impl(other, \"pow\", axis, level, \\\n fill_value, is_rev=False)\n\n def rpow(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other ** self\"\"\"\n return self.__binary_operator_impl(other, \"pow\", axis, level, \\\n fill_value, is_rev=True)\n\n def __pow__(self, other):\n \"\"\" \n overloaded binary operator** (wrapper of self.pow())\n returns resultant dataframe after adding self ** other \n \"\"\"\n return self.pow(other)\n\n def __IPOW__(self, other):\n \"\"\" \n overloaded binary operator**= to perform self **= other \n \"\"\"\n self = self.pow(other)\n\n @check_association\n def head(self, n=5):\n \"\"\"\n return first n rows of the dataframe\n \"\"\"\n if not isinstance(n, int):\n raise TypeError(\"head: Invalid type '%s' for n\"\n \"is provided!\" % (type(n).__name__))\n if n < 0:\n nrows = len(self)\n n = max(0, nrows + n)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_head(host, port, self.get(), n)\n\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n ret = DataFrame()\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return ret\n\n @check_association\n def tail(self, n=5):\n \"\"\"\n return last n rows of the dataframe\n \"\"\"\n if not isinstance(n, int):\n raise TypeError(\"tail: Invalid type '%s' for n\"\n \"is provided!\" % (type(n).__name__))\n if n < 0:\n nrows = len(self)\n n = max(0, nrows + n)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_tail(host, port, self.get(), n)\n\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n ret = DataFrame()\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return ret\n\n @check_association\n def __filter_slice_range(self, target):\n \"\"\"\n return filtered dataframe in given slice range\n \"\"\"\n a, b, c = target.start, target.stop, target.step\n\n if c is None:\n c = 1\n elif not isinstance(c, int):\n raise TypeError(\"filter_slice_range: slice step must be integer or None!\")\n\n if c == 0:\n raise ValueError(\"filter_slice_range: slice step cannot be zero!\")\n elif c < 0:\n raise ValueError(\"filter_slice_range: slice step cannot be negative!\")\n\n nrows = len(self)\n a_int = -1\n b_int = -1\n\n ## check for bool moved to first\n ## since isinstance(True, int) also returns True\n\n if isinstance(a, bool) or isinstance(b, bool) \\\n or not (isinstance(a, int) or a is None) \\\n or not (isinstance(b, int) or b is None):\n # non - integer slice\n if a is None:\n a_int = 0\n else:\n aloc = self.__get_index_loc_impl(a)\n if len(aloc) != 1:\n raise ValueError(\"Cannot get slice bound for \" \\\n \"non-unique label '%s'\" % (a))\n a_int = int(aloc[0])\n\n if b is None:\n b_int = nrows\n else:\n bloc = self.__get_index_loc_impl(b)\n if len(bloc) != 1:\n raise ValueError(\"Cannot get slice bound for \" \\\n \"non-unique label '%s'\" % (b))\n b_int = int(bloc[0])\n b_int += 1\n else:\n # integer slice\n a_int = int(a) if a is not None else 0\n b_int = int(b) if b is not None else nrows\n\n if a_int < 0:\n a_int = max(0, nrows + a_int)\n if b_int < 0:\n b_int = max(0, nrows + b_int)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_slice_range(host, port, self.get(), a_int, b_int, c)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret = DataFrame()\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return ret\n\n @check_association\n def __get_index_loc_impl(self, value):\n \"\"\"\n helper for get_index_loc\n \"\"\"\n if not self.has_index():\n raise ValueError(\"get_index_loc: no index column in input df!\")\n\n index_name = self.index.name\n dtype = self.index.dtype\n\n (host, port) = FrovedisServer.getServerInstance()\n ret = rpclib.df_get_index_loc(host, port, self.get(), \\\n index_name.encode('ascii'), \\\n str(value).encode('ascii'), \\\n dtype)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return ret\n\n # similar to pandas pd.Index.get_loc(value)\n def get_index_loc(self, value):\n \"\"\"\n returns row-ids (int, slice or maask) for given value in index column\n \"\"\"\n idx = self.__get_index_loc_impl(value)\n sz = len(idx)\n if sz == 1: # int\n ret = int(idx[0])\n else:\n is_monotonic = np.all(np.diff(idx) == 1)\n if is_monotonic: # slice\n ret = slice(idx[0], idx[sz - 1] + 1, None)\n else: # masked-array\n mask = np.asarray([False] * len(self))\n mask[idx] = True\n ret = mask \n return ret\n\n @check_association\n def mean(self, axis=None, skipna=None, level=None, \n numeric_only=None, **kwargs):\n \"\"\"\n returns the mean of the values over the requested axis.\n \"\"\"\n axis_, skipna_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level)\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_mean(host, port, self.get(), \\\n cols_arr, ncol, \\\n axis_, skipna_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def var(self, axis=None, skipna=None, level=None, ddof=1,\n numeric_only=None, **kwargs):\n \"\"\"\n returns the variance of the values over the requested axis.\n \"\"\"\n axis_, skipna_, ddof_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level, ddof_=ddof)\n\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_var(host, port, self.get(), \\\n cols_arr, ncol, \\\n axis_, skipna_, ddof_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def std(self, axis=None, skipna=None, level=None, ddof=1,\n numeric_only=None, **kwargs):\n \"\"\"\n returns the standard deviatioon of the values over the requested axis.\n \"\"\"\n axis_, skipna_, ddof_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level, ddof_=ddof)\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_std(host, port, self.get(), \\\n cols_arr, ncol, \\\n axis_, skipna_, ddof_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def sem(self, axis=None, skipna=None, level=None, ddof=1,\n numeric_only=None, **kwargs):\n \"\"\"\n returns the standard error of mean of the values over the requested axis.\n \"\"\"\n axis_, skipna_, ddof_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level, ddof_=ddof)\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_sem(host, port, self.get(), \\\n cols_arr, ncol, \\\n axis_, skipna_, ddof_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def median(self, axis=None, skipna=None, level=None,\n numeric_only=None, **kwargs):\n \"\"\"\n returns the median of the values over the requested axis.\n \"\"\"\n axis_, skipna_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level)\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n type_arr = np.asarray(types, dtype=c_short)\n tptr = type_arr.ctypes.data_as(POINTER(c_short))\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_median(host, port, self.get(), \\\n cols_arr, tptr, ncol, \\\n axis_, skipna_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n\n def __setattr__(self, key, value):\n \"\"\" sets the specified attribute \"\"\"\n if key in self.__dict__: # instance attribute\n if self.__cols and key in self.__cols:\n self[key] = value\n else:\n self.__dict__[key] = value\n else:\n attr = getattr(self.__class__, key, None)\n if isinstance(attr, property):\n if attr.fset is None:\n raise AttributeError(\"%s: can't set attribute\" % (key))\n attr.fset(self, value) # calling setter of property\n else:\n self.__dict__[key] = value\n\n @check_association\n def __str__(self):\n \"\"\"\n returns string representation of the dataframe \n \"\"\"\n (host, port) = FrovedisServer.getServerInstance()\n df_str = rpclib.df_to_string(host, port, self.__fdata, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return df_str\n\n def __repr__(self):\n \"\"\"\n returns string representation of the dataframe \n \"\"\"\n return self.__str__()\n\nFrovedisDataframe = DataFrame\n","sub_path":"src/foreign_if/python/main/python/frovedis/dataframe/df.py","file_name":"df.py","file_ext":"py","file_size_in_byte":130151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618279786","text":"import torch\nfrom torch.utils.data import DataLoader\nimport argparse\n\ndef main(args):\n\n # cuda\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n # Datasets & Dataloader\n train_set = torch.utils.data.Dataset()\n train_loader = DataLoader(dataset=train_set, shuffle=True, batch_size=args.batch_size)\n\n valid_set = torch.utils.data.Dataset()\n valid_loader = DataLoader(dataset=valid_set, batch_size=args.batch_size)\n\n # Models\n model = torch.nn.Module()\n model.to(device)\n\n # Optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)\n\n # Training\n best_valid_loss = 1e99\n for epoch in range(1, args.epochs+1):\n \n train_loss = evaluate_epoch(model=model, data_loader=train_loader, optimizer=optimizer)\n valid_loss = evaluate_epoch(model=model, data_loader=valid_loader)\n\n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n best_epoch = epoch\n model.save()\n \n print(\"Epoch %02d/%02d Train Loss %5.3f Valid Loss %5.3f\"\n %(epoch, args.epochs, train_loss, valid_loss))\n\n raise NotImplementedError()\n\ndef evaluate_epoch(model, data_loader, optimizer=None):\n \n epoch_loss = 0\n\n if optimizer is not None:\n torch.enable_grad()\n model.train()\n else:\n torch.no_grad()\n model.eval()\n \n for batch in data_loader:\n\n loss = model(batch)\n\n if optimizer is not None:\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n epoch_loss += loss.item()\n\n return epoch_loss/len(data_loader)\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-ep', '--epochs', type=int)\n parser.add_argument('-bs', '--batch_size', type=int)\n parser.add_argument('-lr', '--learning_rate', type=float)\n\n # parser.add_argument('-bool', '--boolean', action=store_true)\n\n args = parser.parse_args()\n \n main(args)","sub_path":"base/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"511452080","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 5 13:27:15 2021\r\n\r\n@author: Hitesh\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nfrom db_conn import hana_conn\r\n#from datetime import date\r\n\r\n# st_date = date.today()\r\n# ed_date = date.today()\r\n \r\nclass operations:\r\n \r\n def __init__(self, CUST_ID, FIRST_NAME, LAST_NAME, REGION, ID_PROOF_TYPE, START_DATE, END_DATE, STATUS):\r\n self.CUST_ID = CUST_ID\r\n self.FIRST_NAME = FIRST_NAME\r\n self.LAST_NAME = LAST_NAME\r\n self.REGION = REGION\r\n self.ID_PROOF_TYPE = ID_PROOF_TYPE\r\n self.START_DATE = 'current_date'\r\n self.END_DATE = 'current_date'\r\n self.STATUS = STATUS\r\n self.conn=hana_conn() \r\n \r\n \r\n def read(self):\r\n cursor = self.conn.cursor() \r\n #cursor.execute(\"SELECT TOP 10 \"CUST_ID\",\"FIRST_NAME\",\"LAST_NAME\",\"REGION\",\"ID_PROOF_TYPE\",\"START_DATE\",\"END_DATE\",\"STATUS\" FROM CUSTOMER_DATA;\", {}) \r\n cursor.execute(\"SELECT TOP 10 * FROM CUSTOMER;\", {}) \r\n data = cursor.fetchall()\r\n print(\"Connection to SAP HANA Service successful.\")\r\n \r\n df = pd.DataFrame(data, columns=['CUST_ID','FIRST_NAME','LAST_NAME','REGION','ID_PROOF_TYPE','START_DATE','END_DATE','STATUS'])\r\n print(df)\r\n return df\r\n\t\r\n \r\n def create(self):\r\n #if variable=='Read'\r\n \r\n #cursor = self.conn.cursor() \r\n # val = (self.CUST_ID,self.FIRST_NAME,self.LAST_NAME,self.REGION,self.ID_PROOF_TYPE,self.START_DATE,self.END_DATE,self.STATUS)\r\n # sql=\"INSERT INTO CUSTOMER (CUST_ID,FIRST_NAME,LAST_NAME,REGION,ID_PROOF_TYPE,START_DATE,END_DATE,STATUS) VALUES\"\r\n # final_sql= (sql, val) \r\n # print(final_sql)\r\n # cursor.execute(final_sql, {})\r\n cursor = self.conn.cursor() \r\n cursor.execute(\"INSERT INTO CUSTOMER (CUST_ID,FIRST_NAME,LAST_NAME,REGION,ID_PROOF_TYPE,START_DATE,END_DATE,STATUS) VALUES('12345', 'Sidney', 'Hauke', 'New Jersey', 'Driving License', 'current_date', 'current_date', 'Active')\", {}) \r\n print(\"Customer got created\" )\r\n \r\n return \"Customer created\"\r\n \r\n def delete(self): \r\n cursor = self.conn.cursor() \r\n cursor.execute(\"DELETE FROM CUSTOMER WHERE CUST_ID =\"+str(self.CUST_ID), {})\r\n # res=cursor.fetchall() \r\n # print(res)\r\n print(\"Customer got removed\" )\r\n #return res\r\n return \"Customer got removed\" \r\n \r\n cursor.close()\r\n hana_conn.close() \r\n\r\n\r\n#unit testing \r\n# test = operations('12345','Sidney','Hauke','New Jersey','Driving License','s','e','Active')\r\n# test.delete()\r\n","sub_path":"customerapp.py","file_name":"customerapp.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"271255006","text":"import endpoints\nfrom protorpc import messages\nfrom protorpc import message_types\nfrom protorpc import remote\n\n#import datetime\nfrom google.appengine.ext import ndb\n\n\nclass GardenData(ndb.Model):\n date = ndb.DateTimeProperty(auto_now_add=True)\n soil_temp = ndb.FloatProperty()\n soil_moist = ndb.IntegerProperty()\n room_temp = ndb.IntegerProperty()\n room_moist = ndb.IntegerProperty()\n \n @classmethod\n def query_data(cls):\n qry = cls.query().order(-cls.date)\n return qry.fetch(1000)\n \n \npackage = 'gardendatapackage'\n\n@endpoints.api(name='gardendata', version='v1')\nclass GardenDataApi(remote.Service):\n \"\"\"Garden Data API v1.\"\"\"\n \n CONTAINER = endpoints.ResourceContainer(\n soil_temp = messages.FloatField(1, variant=messages.Variant.FLOAT, \n required=True),\n soil_moist = messages.IntegerField(2, variant=messages.Variant.UINT32,\n required=True),\n room_temp = messages.IntegerField(3, variant=messages.Variant.INT32,\n required=True),\n room_moist = messages.IntegerField(4, variant=messages.Variant.UINT32,\n required=True) \n )\n \n @endpoints.method(CONTAINER,\n path='api', http_method='POST',\n name='data.post')\n def save_data(self, request):\n gd = GardenData(soil_temp = request.soil_temp, \n soil_moist = request.soil_moist,\n room_temp = request.room_temp,\n room_moist = request.room_moist)\n \n gd.put()\n \n return message_types.VoidMessage() \n \n\nAPPLICATION = endpoints.api_server([GardenDataApi])","sub_path":"Google App Engine/garden_data_api.py","file_name":"garden_data_api.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"196337068","text":"import time,os,operator\n\ndef string_amend(str):\n strAmend = str.replace('\"', '')\n strAmend2 = strAmend.replace(',','')\n strAmend3 = strAmend2.replace(' ','')\n strAmend4 = strAmend3.replace('\\n','')\n return strAmend4\n\ndef bucketRtrv(c):\n new = c.split('\"bucket\":') #splits string on bucket: so that data before bucket name is moved to [0] and bucket name is moved to [1]\n del(new[0]) #deletes data before the actual bucket name that is stored in [0]\n str1 = ''.join(new) #turns the list into string for increased manipulation\n str2 = str1.split('\"pool\":') #splits the new string after the bucket name, on pool:, so that bucket name is now held in [0] and unneeded data in [1]\n if (len(str2)<2): #however, if the list is shorter than 2 elements, then there is no bucket name. Output bucket name as 'none'\n final = (\"None\")\n return final\n else:\n del(str2[1]) #If there is a bucket name, it is stored in [0], so [1] is deleted\n str3 = ''.join(str2) #Turn the bucket name back into string for manipulation\n return (string_amend(str3))\ndef idRtrv(c):\n new = c.split('\"id\":')\n del(new[0])\n str1 = ''.join(new)\n str2 = str1.split('\"marker\":')\n if (len(str2)<2):\n final = (\"None\")\n return final\n else:\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\ndef ownerRtrv(c):\n new = c.split('\"owner\":')\n del(new[0])\n str1 = ''.join(new)\n str2 = str1.split('\"ver\":')\n if (len(str2)<2):\n final = (\"None\")\n return final\n else:\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\ndef size_kbRtrv(c):\n new = c.split('\"size_kb\":')\n del(new[0])\n str1 = ''.join(new)\n str2 = str1.split('\"size_kb_actual\":')\n if (len(str2)<2):\n final=\"0\"\n return final \n else:\n if (len(str2)>4):\n del(str2[4])\n del(str2[3])\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3)) \n elif (len(str2)>3):\n del(str2[3])\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\n elif (len(str2)>2):\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return(string_amend(str3))\n else:\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\ndef size_kb_actualRtrv(c):\n new = c.split('\"size_kb_actual\":')\n del(new[0])\n str1 = ''.join(new)\n str2 = str1.split('\"num_objects\":')\n if (len(str2)<2):\n final=\"0\"\n return final \n else:\n if (len(str2)>4):\n del(str2[4])\n del(str2[3])\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3)) \n elif (len(str2)>3):\n del(str2[3])\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3)) \n elif (len(str2)>2):\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\n else:\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\ndef num_objectsRtrv(c):\n new = c.split('\"num_objects\":')\n if (len(new)>4):\n del(new[4])\n del(new[3])\n del(new[2])\n del(new[0])\n str1 = ''.join(new)\n return (string_amend(str1))\n elif (len(new)>3):\n del(new[3])\n del(new[2])\n del(new[0])\n str1 = ''.join(new)\n return(string_amend(str1))\n elif (len(new)>2):\n del(new[2])\n del(new[0])\n str1 = ''.join(new)\n return (string_amend(str1))\n del(new[0])\n str1 = ''.join(new)\n str1Amend = str1.replace('}', '')\n str1Amend2 = str1Amend.replace(',','')\n str1Amend3 = str1Amend2.replace(' ','')\n str1Amend4 = str1Amend3.replace('\\n','')\n if (str1Amend4==\"\"):\n final=\"0\"\n #print(final) use for fault checking\n return final\n else:\n str1Amend3 =str1Amend2.replace(']','')\n str1Amend4 = str1Amend3.replace(' ','')\n str1Amend5 = str1Amend4.replace('\\n','')\n return str1Amend5\n\nf=open('serverOutput.txt','r+') ##f=open('/usr/bin/radosgw-admin bucket stats','r+') Execute straight from this directory\nx=f.read()\ny=x.split('},'or']')\nz=[]\n \nfor c in y:\n n=bucketRtrv(c),idRtrv(c),ownerRtrv(c),size_kbRtrv(c),size_kb_actualRtrv(c),num_objectsRtrv(c)\n z.append(n)\n\n\n\nrotated = zip(*z[::1])\nrotated3 = rotated[2]\nrotated.remove(rotated3)\nrotated.insert(0,rotated3)\n\n\n\nfor i,c in enumerate(rotated):\n new=[]\n for x in c:\n new.append(x)\n rotated[i] = new\n\nfor i,c in enumerate(rotated[0]):\n if c=='None':\n rotated[0][i] = rotated[0][i-1]\n\nspaceUsed_kb= {}\nspaceUsed_kb_actual = {}\nfor i,c in enumerate(rotated[0]):\n if c not in spaceUsed_kb:\n spaceUsed_kb[c] = int(rotated[3][i])\n if c in spaceUsed_kb:\n spaceUsed_kb[c] = int(spaceUsed_kb[c])+int(rotated[3][i])\nfor i,c in enumerate(rotated[0]):\n if c not in spaceUsed_kb_actual:\n spaceUsed_kb_actual[c] = int(rotated[4][i])\n if c in spaceUsed_kb_actual:\n spaceUsed_kb_actual[c] = int(spaceUsed_kb_actual[c])+int(rotated[4][i])\n\n\n##function for sorting lists##\ndef sort_inner(inner):\n return inner[0]\n\nz = zip(*rotated[::1])\nz.sort(key=sort_inner)\n\ntemp =[]\ndictlist =[]\nfor key, value in spaceUsed_kb.iteritems():\n value=float(value)\n value = \"%.3f\" % float(value/(1048576))\n value = str(value)+'gb'\n temp = key,value\n dictlist.append(temp)\n\n\n\nlistOfTemps = []\nfor c in dictlist[::1]:\n dictlist.remove(c)\n temp2 = str(c).replace(\"'\",'').replace(',',' has used').replace('(','').replace(')','')\n listOfTemps.append(temp2)\ndictlist = dictlist + listOfTemps\n\n##Transferring dictionary into list which is stored in dictlist2##\ndictlist2 =[]\nfor key, value in spaceUsed_kb_actual.iteritems():\n value=float(value)\n value = \"%.3f\" % float(value/(1048576))\n value = str(value)+'gb'\n temp2 = key,value\n dictlist2.append(temp2)\n\n\ntemp3 =[]\nlistOfTemps2=[]\nfor c in dictlist2[::1]:\n dictlist2.remove(c)\n temp3 = str(c).replace(\"'\",'').replace(',',' has used').replace('(','').replace(')','')\n listOfTemps2.append(temp3)\ndictlist2 = dictlist2 + listOfTemps2\n\n##sort the totals in alphabetical order of owner##\ndictlist.sort(key=sort_inner)\ndictlist2.sort(key=sort_inner)\n\n\n##convert both lists to strings for writing to file##\ndictlistStr=str(dictlist)\ndictlist2Str=str(dictlist2)\n\n\n\n##Concatenates headings in 'startZ' with data in 'z'##\n\n\nfileOutput = 'Server Outputs'+'/'+(\"diskSpace\" + (time.strftime(\"%d.%m.%Y\") +\".csv\")) #creates dir called Server Outputs and file called diskSpace(date)\n\ndir = os.path.dirname(fileOutput)\n\nif not os.path.exists(dir):\n os.makedirs(dir)\n\n\ndictlist = tuple(dictlist)\ndictlist = [dictlist]\n#print(dictlist[0][1])\n#print(z[1])\nzNew=[]\nfor c in z: #Added column which shows data used by each person, however, it duplicates info\n for d in dictlist[0]:\n if d.find(c[0])!=-1:\n d=(d,)\n print(d)\n c=c+d\n print(c)\n zNew.append(c)\n\n\nf2=open(fileOutput, 'w+')\nf2.write(\"\\n\".join(map(lambda x: str(x).replace('(','').replace(')','').replace(\"'\",''), zNew)))\nf2.write('\\n\\n')\n#f2.write('\\n'+'size_kb, '+(dictlistStr.replace('[','').replace(']','').replace(\"'\",'')))\n#f2.write('\\n'+'size_kb_actual, '+(dictlist2Str.replace('[','').replace(']','').replace(\"'\",'')))\nf2.close()\nf.close()\n","sub_path":"src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":7876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"388372830","text":"\"\"\"\nThis code has been taken from\nhttps://blog.hypertrack.io/2016/10/08/dealing-with-database-transactions-in-django-celery/\n\nUsage:\n from pretix.base.services.async import TransactionAwareTask\n @task(base=TransactionAwareTask)\n def task_…():\n\"\"\"\nimport cProfile\nimport os\nimport random\nimport time\n\nfrom django.conf import settings\nfrom django.db import transaction\n\nfrom pretix.celery_app import app\n\n\nclass ProfiledTask(app.Task):\n\n def __call__(self, *args, **kwargs):\n\n if settings.PROFILING_RATE > 0 and random.random() < settings.PROFILING_RATE / 100:\n profiler = cProfile.Profile()\n profiler.enable()\n starttime = time.time()\n ret = super().__call__(*args, **kwargs)\n profiler.disable()\n tottime = time.time() - starttime\n profiler.dump_stats(os.path.join(settings.PROFILE_DIR, '{time:.0f}_{tottime:.3f}_celery_{t}.pstat'.format(\n t=self.name, tottime=tottime, time=time.time()\n )))\n return ret\n else:\n return super().__call__(*args, **kwargs)\n\n\nclass TransactionAwareTask(ProfiledTask):\n \"\"\"\n Task class which is aware of django db transactions and only executes tasks\n after transaction has been committed\n \"\"\"\n\n def apply_async(self, *args, **kwargs):\n \"\"\"\n Unlike the default task in celery, this task does not return an async\n result\n \"\"\"\n transaction.on_commit(\n lambda: super(TransactionAwareTask, self).apply_async(*args, **kwargs)\n )\n","sub_path":"src/pretix/base/services/async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"221783484","text":"import sys\n\nsys.path.insert(0, \"./yolov5\")\n\nfrom yolov5.utils.datasets import LoadImages, LoadStreams\nfrom yolov5.utils.general import check_img_size, non_max_suppression, scale_coords\nfrom yolov5.utils.torch_utils import select_device, time_synchronized\nfrom helpers.parser import get_config\nfrom deep_sort_pytorch.deep_sort import DeepSort\nfrom iou.iou_tracker import IOUTracker\n# from iou_kf.iou_kf_tracker import IOUKFTracker\nfrom sort.sort import Sort\nimport argparse\nimport os\nimport platform\nimport shutil\nimport time\nfrom pathlib import Path\nimport cv2\nimport torch\nimport torch.backends.cudnn as cudnn\nimport constants\nimport csv\nimport numpy as np\n\n\npalette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1)\n\n\ndef xyxy_to_tlwh(bbox_xyxy):\n tlwh_bboxs = []\n for box in bbox_xyxy:\n x1, y1, x2, y2 = [int(i) for i in box]\n top = y1\n left = x1\n w = int(x2 - x1)\n h = int(y2 - y1)\n tlwh_obj = [left, top, w, h]\n tlwh_bboxs.append(tlwh_obj)\n return tlwh_bboxs\n\n\ndef bbox_rel(*tlwh):\n \"\"\" Calculates the relative bounding box from absolute pixel values.\"\"\"\n bbox_left, bbox_top, bbox_w, bbox_h = tlwh\n x_c = bbox_left + bbox_w / 2\n y_c = bbox_top + bbox_h / 2\n w = bbox_w\n h = bbox_h\n return x_c, y_c, w, h\n\n\ndef compute_color_for_labels(label):\n \"\"\"\n Simple function that adds fixed color depending on the class\n \"\"\"\n color = [int((p * (label ** 2 - label + 1)) % 255) for p in palette]\n return tuple(color)\n\n\ndef draw_boxes(img, bbox, identities=None, offset=(0, 0)):\n for i, box in enumerate(bbox):\n x1, y1, x2, y2 = [int(i) for i in box]\n x1 += offset[0]\n x2 += offset[0]\n y1 += offset[1]\n y2 += offset[1]\n # box text and bar\n id = int(identities[i]) if identities is not None else 0\n color = compute_color_for_labels(id)\n label = \"{}{:d}\".format(\"\", id)\n t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]\n cv2.rectangle(img, (x1, y1), (x2, y2), color, 3)\n cv2.rectangle(\n img, (x1, y1), (x1 + t_size[0] + 3, y1 + t_size[1] + 4), color, -1\n )\n cv2.putText(\n img,\n label,\n (x1, y1 + t_size[1] + 4),\n cv2.FONT_HERSHEY_PLAIN,\n 2,\n [255, 255, 255],\n 2,\n )\n return img\n\n\ndef detect(cfg, save_img=False):\n out, source, view_img, save_txt, imgsz, gt_file = (\n cfg.OUTPUT,\n cfg.SOURCE,\n cfg.VIEW_IMG,\n cfg.SAVE_TXT,\n cfg.IMAGE_SIZE,\n cfg.GT_FILE\n )\n\n # Initialize\n device = select_device(cfg.DEVICE)\n\n # Create output folder\n exp_name = \"exp_\" + cfg.EXP_ID\n out = os.path.join(out, exp_name)\n if os.path.exists(out):\n shutil.rmtree(out) # delete output folder\n os.makedirs(out) # make new output folder\n\n half = device.type != \"cpu\" # half precision only supported on CUDA\n\n # Read groundtruth\n gt = np.genfromtxt(gt_file, delimiter=',')\n\n # Set Dataloader\n vid_path, vid_writer = None, None\n view_img = True\n save_img = True\n dataset = LoadImages(source, img_size=imgsz)\n\n t0 = time.time()\n\n save_path = str(Path(out))\n txt_path = str(Path(out)) + \"/results.txt\"\n\n seen_vid_paths = {}\n\n for frame_idx, (path, img, im0s, vid_cap) in enumerate(dataset):\n if path not in seen_vid_paths:\n seen_vid_paths[path] = True\n if cfg.TRACKER == constants.DEEP_SORT:\n # initialize deepsort\n tracker = DeepSort(\n cfg.DEEP_SORT.REID_CKPT,\n max_dist=cfg.DEEP_SORT.MAX_DIST,\n min_confidence=cfg.DEEP_SORT.MIN_CONFIDENCE,\n nms_max_overlap=cfg.DEEP_SORT.NMS_MAX_OVERLAP,\n max_iou_distance=cfg.DEEP_SORT.MAX_IOU_DISTANCE,\n max_age=cfg.DEEP_SORT.MAX_AGE,\n n_init=cfg.DEEP_SORT.N_INIT,\n nn_budget=cfg.DEEP_SORT.NN_BUDGET,\n use_cuda=True,\n )\n elif cfg.TRACKER == constants.IOU:\n sigma_iou = 1 - cfg.IOU.MAX_IOU_DISTANCE\n # initialize iou\n tracker = IOUTracker(\n sigma_l=cfg.IOU.MIN_CONFIDENCE,\n sigma_iou=sigma_iou,\n )\n elif cfg.TRACKER == constants.SORT:\n # initialize sort\n tracker = Sort(\n min_confidence=cfg.SORT.MIN_CONFIDENCE,\n max_iou_distance=cfg.SORT.MAX_IOU_DISTANCE,\n max_age=cfg.SORT.MAX_AGE,\n n_init=cfg.SORT.N_INIT,\n )\n\n frame_col_idx = 0\n frame_n = frame_idx + 1\n pred = gt[gt[:, frame_col_idx] == frame_n] \n\n bbox_xywh = []\n confs = []\n\n p, s, im0 = path, \"\", im0s\n s += \"%gx%g \" % img.shape[1:] # print string\n save_path = str(Path(out) / Path(p).name)\n\n # Process detections\n if pred is not None and len(pred):\n for frame, id, *tlwh, conf, cls, visibility in pred:\n if int(cls) == 1:\n x_c, y_c, bbox_w, bbox_h = bbox_rel(*tlwh)\n obj = [x_c, y_c, bbox_w, bbox_h]\n bbox_xywh.append(obj)\n confs.append(conf)\n\n xywhs = torch.Tensor(bbox_xywh)\n confss = torch.Tensor(confs)\n\n # Pass detections to iou/sort/deepsort tracker\n outputs = tracker.update(xywhs, confss, im0)\n\n # draw boxes for visualization\n if len(outputs) > 0:\n bbox_xyxy = outputs[:, :4]\n identities = outputs[:, -1]\n draw_boxes(im0, bbox_xyxy, identities)\n # to MOT format\n tlwh_bboxs = xyxy_to_tlwh(bbox_xyxy)\n\n # Write MOT compliant results to file\n if save_txt:\n fieldnames = [\n \"frame\",\n \"id\",\n \"bb_left\",\n \"bb_top\",\n \"bb_width\",\n \"bb_height\",\n \"conf\",\n \"x\",\n \"y\",\n \"z\",\n ]\n\n for j, (tlwh_bbox, output) in enumerate(zip(tlwh_bboxs, outputs)):\n bbox_left = tlwh_bbox[0]\n bbox_top = tlwh_bbox[1]\n bbox_w = tlwh_bbox[2]\n bbox_h = tlwh_bbox[3]\n identity = output[-1]\n with open(txt_path, 'a') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writerow({\n \"frame\": frame_n,\n \"id\": identity,\n \"bb_left\": float(bbox_left),\n \"bb_top\": float(bbox_top),\n \"bb_width\": float(bbox_w),\n \"bb_height\": float(bbox_h),\n \"conf\": -1,\n \"x\": -1,\n \"y\": -1,\n \"z\": -1,\n })\n else:\n tracker.increment_ages()\n\n # Print time (inference + NMS)\n # print(\"%sDone. (%.3fs)\" % (s, t2 - t1))\n\n # Stream results\n view_img = cfg.VIEW_IMG\n if view_img:\n cv2.imshow(p, im0)\n if cv2.waitKey(1) == ord(\"q\"): # q to quit\n raise StopIteration\n\n # Save results (image with detections)\n if save_img:\n print(\"saving img!\")\n if dataset.mode == \"images\":\n cv2.imwrite(save_path, im0)\n else:\n print(\"saving video!\")\n if vid_path != save_path: # new video\n vid_path = save_path\n if isinstance(vid_writer, cv2.VideoWriter):\n vid_writer.release() # release previous video writer\n\n # fps = vid_cap.get(cv2.CAP_PROP_FPS)\n fps = cfg.FPS\n w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n vid_writer = cv2.VideoWriter(\n save_path,\n cv2.VideoWriter_fourcc(*cfg.FOURCC),\n fps,\n (w, h),\n )\n vid_writer.write(im0)\n\n if save_txt or save_img:\n print(\"Results saved to %s\" % os.getcwd() + os.sep + out)\n if platform == \"darwin\": # MacOS\n os.system(\"open \" + save_path)\n\n print(\"Done. (%.3fs)\" % (time.time() - t0))\n\n\ndef main(config):\n cfg = get_config(config)\n cfg.IMAGE_SIZE = check_img_size(cfg.IMAGE_SIZE)\n print(cfg)\n\n with torch.no_grad():\n detect(cfg)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config\", type=Path, required=True)\n args = parser.parse_args()\n main(args.config)\n","sub_path":"track_by_gt_bbox.py","file_name":"track_by_gt_bbox.py","file_ext":"py","file_size_in_byte":9295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"207244791","text":"class Solution:\n def reverseWords(self, s):\n if s == '':\n return s\n ls = s.split()\n if ls == []:\n return ''\n\n res = ''\n for i in range(len(ls) - 1):\n res += ls[len(ls) - 1 - i] + ' '\n res += ls[0]\n return res\n","sub_path":"151_ReverseWordsInAString.py","file_name":"151_ReverseWordsInAString.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"352162141","text":"from fiasko_bro import validators\nfrom fiasko_bro.code_validator import CodeValidator\n\n\ndef test_has_no_directories_from_blacklist(test_repo):\n expected_output = 'data_in_repo', '.vscode'\n blacklists = CodeValidator.blacklists\n output = validators.has_no_directories_from_blacklist(\n solution_repo=test_repo,\n blacklists=blacklists,\n )\n assert output == expected_output\n\n\ndef test_no_star_imports_ok(origin_repo):\n blacklists = CodeValidator.blacklists\n output = validators.has_no_directories_from_blacklist(\n solution_repo=origin_repo,\n blacklists=blacklists,\n )\n assert output is None\n","sub_path":"tests/test_general_validators/test_has_no_directories_from_blacklist.py","file_name":"test_has_no_directories_from_blacklist.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"608855921","text":"# 대부분의 코드는 https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/15_Style_Transfer.ipynb 에서 가져옴 \n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport PIL.Image\n\n\"\"\"이미지 조작을 위한 헬퍼 함수\"\"\"\n# 이 함수는 이미지를 로드하고 부동소수점 형식의 NumPy 배열을 반환한다.\n# 이미지는 크기가 자동으로 조정되며 높이 또는 너비 중 가장 큰 것이 max_size와 같아진다\n# 또는 지정한 크기로 조정될 수 있다.\ndef load_image(filename, shape=None, max_size=None):\n image = PIL.Image.open(filename)\n\n if max_size is not None:\n # 최대 높이와 너비를 유지하면서 적절한 비율로 조정하기 위해 적절하게 계산해야한다\n factor = float(max_size) / np.max(image.size)\n\n # 이미지의 높이와 너비 조정\n size = np.array(image.size) * factor\n\n # 크기가 조정되어서 사이즈가 부동 소수점 형식을 따르지만 PIL은 정수 입력을 요구한다.\n size = size.astype(int)\n\n # 이미지를 재조정한다\n image = image.resize(size, PIL.Image.LANCZOS) # PIL.Image.LANCZOS 는 리샘플링 필터중 하나이다.\n\n if shape is not None:\n image = image.resize(shape, PIL.Image.LANCZOS) # PIL.Image.LANCZOS 는 리샘플링 필터중 하나이다.\n\n # 부동소수점 형식의 Numpy 배열로 변환한다.\n return np.float32(image)\n\n# JPEG 형태로 이미지를 저장한다\n# 이미지는 0~255 사이로 픽셀 값이 정해진 NumPy 배열로 주어진다.\ndef save_image(image, filename):\n # 픽셀 값이 0에서 255 사이인지 확인\n image = np.clip(image, 0.0, 255.0)\n\n # bytes로 변환\n image = image.astype(np.uint8)\n\n # JPEG로 이미지 저장\n with open(filename, 'wb') as file:\n PIL.Image.fromarray(image).save(file, 'jpeg')\n\n# 콘텐츠 이미지, 혼합된 이미지 및 스타일 이미지를 그립니다.\ndef plot_images(content_image, style_image, mixed_image):\n # 서브플롯으로 이미지 생성\n fig, axes = plt.subplots(1, 3, figsize=(10, 10))\n\n # 수직 간격 조절\n fig.subplots_adjust(hspace=0.1, wspace=0.1)\n\n # 콘텐츠 이미지를 그린다\n # 픽셀 값은 값을 255로 나눔으로써 0~1 사이 영역으로 정규화 된다\n ax = axes.flat[0]\n ax.imshow(content_image / 255.0, interpolation='sinc')\n ax.set_xlabel(\"Content\")\n\n # 혼합된 이미지를 그린다.\n ax = axes.flat[1]\n ax.imshow(mixed_image / 255.0, interpolation='sinc')\n ax.set_xlabel(\"Output\")\n\n # 스타일 이미지를 그린다\n ax = axes.flat[2]\n ax.imshow(style_image / 255.0, interpolation='sinc')\n ax.set_xlabel(\"Style\")\n\n # 모든 그림에서 틱 제거\n for ax in axes.flat:\n ax.set_xticks([])\n ax.set_yticks([])\n\n # 싱글 노트북 셀에서 이미지가 여러개로 잘 표시되는지 확인하자.\n plt.show()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"394036550","text":"from django.urls import path\n\nimport apps.comments.views as comments\n\nfrom .apps import CommentsConfig\n\napp_name = CommentsConfig.name\n\nurlpatterns = [\n path(\"create/<int:pk>\", comments.comment_create, name=\"comment_create\"),\n path(\"create-child/<int:pk>/<int:id_parent_comment>\",\n comments.child_comment_create, name=\"comment_child_create\"),\n path(\"ajax/like\", comments.like_dislike_ajax, name=\"ajax_comment\"),\n]\n","sub_path":"apps/comments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"607256812","text":"#1.要想读取csv文件,首先要导入csv代码库\n#这个csv也不用下载,是python内置的代码库\n#如果要读取excel需要下载相应的代码库:xlrd\n#怎么下载:1.通过命令下载:在dos窗口中输入pip install -U xlrd\n#之前老师发了一个selenium的离线包,也可以通过命令行在线安装\n## 在dos窗口中输入pip install -U selenium或者pip3 install selenium\n#-U是升级到新版的意思 pip是python语言最常用的项目管理工具,和jav中的maven类似\n#如果又安装python2.同时安装python3,那么可能需要把pip改成pip3\n#2.点击file-点击settings-project下面的inter preter-点击+号-搜索需要的代码库,并可直接安装\nimport csv\n#指定要读取的文件的路径\npath='C:/Users/51Testing/PycharmProjects/selenium1th/data/test_data.csv'\n#因为字符串中包含转义字符\\t等,怎么做?\n#方法1:每个反斜线前面加一个反斜线\n#方法2:把每个反斜线都改成正斜线\n#相比第二种方法更好,因为java、python语言都是跨平台的,在字符串中,两个反斜线会自动根据转义字符的规则转成一个反斜线,在windows操作系统中,用反斜线表示目录结构,但是在linux操作系统中,只有正斜线/才能表示目录。如果用双反斜线,代码就失去了跨平台的能力,因为linux用不了反斜线。如果用正斜线,代码可以同时在linux和windows中执行\n#方法3.在字符串外面加上一个字母r,会认为中间的所有的代码都不存在转义\nprint(path)\n#3.打开路径所对应的文件\nfile=open(path,'r')\n#4.读取文件的内容,通过什么来读取?我们导入了csv代码库,还一直没用\n#reader()方法是专门用来读取文件的\ndata_table=csv.reader(file)\n#5.打印data_table中的每一行数据,怎么办?写一个for-each循环\n#for是循环的关键字,item代表每一行,每循环一次,item就代表最新的一行数据。data_table表示整个文件中的所有数据\nfor item in data_table:\n print(item)\n#很多的测试用例可能都需要从excel中读取数据,所以我们应该对这些代码做一个简单的封装,建一个文件叫csvFileManager2,把以上代码封装到一个方法中,并且再建一个文件来读取封装好的方法\n","sub_path":"day4/csvFileManager.py","file_name":"csvFileManager.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468146599","text":"from PIL import Image, ImageDraw, ImageFont\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport cv2\n\n\n\ndef elastic_distortion(image, alpha, sigma, random_state=None): #Create an elastic distortion of the image to account for camera iregularities\n if random_state is None:\n random_state = np.random.RandomState(None)\n\n shape = image.shape\n dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=\"constant\", cval=0) * alpha\n dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=\"constant\", cval=0) * alpha\n dz = np.zeros_like(dx)\n\n x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]))\n indices = np.reshape(y+dy, (-1, 1)), np.reshape(x+dx, (-1, 1))\n distored_image = map_coordinates(image, indices, order=1, mode='reflect')\n return distored_image.reshape(image.shape)\n\n \ndef add_noise(img): #Add noise to the image\n row, col=np.shape(img)\n mean = 0\n var = 2\n sigma = var**0.3\n gauss = np.array((row, col))\n gauss = np.random.normal(mean,sigma,(row,col))\n gauss = gauss.reshape(row,col)\n noisy = img + gauss\n return noisy.astype('uint8')\n\ndef add_side_bars(img):\n \n for i in range(0, 4): #sides bars 4 pixel wide\n img[i, :]=np.random.randint(0, 255)\n img[-i, :]=np.random.randint(0, 255)\n img[:, i]=np.random.randint(0, 255)\n img[:, -i]=np.random.randint(0, 255)\n return img\n\ndef get_image_part(img, cell_size):\n x=np.random.randint(19, 40)\n y=np.random.randint(19, 40)\n img=img[x:x+cell_size, y:y+cell_size]\n return img\n\n\ndef create_data(length, list_of_font, threshold=True, consider_empty=True):\n cell_size=45\n y_label=np.zeros(length, dtype=int)\n \n x_img=np.zeros((length, cell_size, cell_size), dtype=float)\n for i in range(0, length):\n \n if consider_empty:\n y=np.random.randint(0, 9+1)\n \n else:\n y=np.random.randint(1, 9+1)\n \n y_label[i]=y\n \n strip_width, strip_height = 100, 100\n\n background =Image.new('RGB', (strip_width, strip_height), color = (np.random.randint(80, 255), np.random.randint(80, 255), np.random.randint(80, 255)))\n font1=list_of_font[np.random.randint(0, len(list_of_font))]\n font = ImageFont.truetype(font1, 40)\n draw = ImageDraw.Draw(background)\n text_width, text_height = draw.textsize(text, font)\n position = ((strip_width-text_width)/2,(strip_height-text_height)/2)\n color=(np.random.randint(0, 10), np.random.randint(0, 10), np.random.randint(0, 10))\n \n if y>0: #If label is greater than 0, draw number\n draw.text(position, str(y), color, font=font)\n #add bars of differents width around the cell:\n img=np.array(background)\n img=0.2989*img[:, :, 0]+0.5870*img[:, :, 1]+0.1140*img[:, :, 2]\n bar_w=np.random.randint(1, 4)\n img[:, 28:28+bar_w]=1\n bar_w=np.random.randint(1, 4)\n img[:, 74:74+bar_w]=1\n bar_w=np.random.randint(1, 4)\n img[28:28+bar_w, :]=1\n bar_w=np.random.randint(1, 4)\n img[74:74+bar_w, :]=1\n \n #Get images of different centers around the original cells center\n img=get_image_part(img, cell_size)\n \n img=add_noise(img)\n img = cv2.GaussianBlur(img, (3,3), 0)\n img=elastic_distortion(img, np.random.randint(0, 100), np.random.randint(5, 10), random_state=None)\n x_img[i, :, :]=img\n \n return x_img, y_label\n \n\ndef create_image_data(length):\n\n list_of_font=['/Library/Fonts/Arial.ttf', '/Library/Fonts/Courier New.ttf', '/Library/Fonts/Times New Roman.ttf']\n #ll=80000\n xx, yy=generate_digit_img(length, list_of_font)\n return xx, yy\n\n","sub_path":"train_digit_model/generate_digits.py","file_name":"generate_digits.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"417730442","text":"import numpy as np\r\nimport random as rnd\r\nimport operations\r\n\r\n\r\n# fe = open('fkeasypart4.lower','r')\r\n# fd = open('fkdifficpart4.lower','r')\r\n# fouts2t=open('fksrc2trg.lower','w')\r\n# foutt2s=open('fktrg2src.lower','w')\r\n# rnd.seed(7)\r\n\r\n\r\ndef repeatnoise(fe):\r\n fouts2t = []\r\n for e in fe:\r\n # create fksrc2trg\r\n easy = e.strip().split()\r\n winsize = 1 if rnd.randint(0, 1) == 0 else 2\r\n ndups = len(easy) // 8 if winsize == 1 else len(easy) // 11\r\n if ndups != 0 and len(easy) != 0:\r\n idces = set(np.random.choice(len(easy), size=(ndups,), replace=False))\r\n outsent = []\r\n for idx, word in enumerate(easy):\r\n wrd = ' '.join(easy[idx:idx + winsize])\r\n reword = wrd + ' ' + wrd.split()[0] if idx in idces else word\r\n outsent.append(reword)\r\n fouts2t.append(' '.join(outsent))\r\n elif ndups == 0:\r\n fouts2t.append(e.strip())\r\n\r\n return fouts2t\r\n\r\n\r\ndef dropnoise(fd):\r\n foutt2s = []\r\n for d in fd:\r\n # create fktrg2src\r\n diffi = d.strip().split()\r\n winsize = 1\r\n ndups = len(diffi) // 8 if winsize == 1 else len(diffi) // 11\r\n if ndups != 0 and len(diffi) != 0:\r\n idces = set(np.random.choice(len(diffi), size=(ndups,), replace=False))\r\n outsent = []\r\n for idx, word in enumerate(diffi):\r\n wrd = ' '.join(diffi[idx:idx + winsize])\r\n if idx not in idces:\r\n outsent.append(wrd)\r\n foutt2s.append(' '.join(outsent))\r\n elif ndups == 0:\r\n foutt2s.append(d.strip())\r\n return foutt2s\r\n\r\n\r\ndef hasNumbers(inputString):\r\n return any(char.isdigit() for char in inputString)\r\n\r\n\r\ndef wordordernoise(sents, noiseratio):\r\n sents = [sent.strip().split() for sent in sents]\r\n lengths = [len(sent) for sent in sents]\r\n for idx, length in enumerate(lengths):\r\n if length > 5:\r\n for it in range(int(noiseratio * length)):\r\n j = rnd.randint(0, length - 2)\r\n sents[idx][j], sents[idx][j + 1] = sents[idx][j + 1], sents[idx][j]\r\n return [' '.join(sent) for sent in sents]\r\n\r\n\r\ndef additive_noise(sent_batch,\r\n lengths,\r\n corpus,\r\n ae_add_noise_perc_per_sent_low,\r\n ae_add_noise_perc_per_sent_high,\r\n ae_add_noise_num_sent,\r\n ae_add_noise_2_grams):\r\n assert ae_add_noise_perc_per_sent_low <= ae_add_noise_perc_per_sent_high\r\n batch_size = len(lengths)\r\n if ae_add_noise_2_grams:\r\n shuffler_func = operations.shuffle_2_grams\r\n else:\r\n shuffler_func = operations.shuffle\r\n split_sent_batch = [\r\n sent.split()\r\n for sent in sent_batch\r\n ]\r\n length_arr = np.array(lengths)\r\n min_add_lengths = np.floor(length_arr * ae_add_noise_perc_per_sent_low)\r\n max_add_lengths = np.ceil(length_arr * ae_add_noise_perc_per_sent_high)\r\n for s_i in range(ae_add_noise_num_sent):\r\n add_lengths = np.round(\r\n np.random.uniform(min_add_lengths, max_add_lengths)\r\n ).astype(int)\r\n next_batch = operations.shuffle(corpus.next_batch(batch_size))\r\n for r_i, new_sent in enumerate(next_batch):\r\n addition = shuffler_func(new_sent.split())[:add_lengths[r_i]]\r\n split_sent_batch[r_i] += addition\r\n noised_sent_batch = [\r\n \" \".join(shuffler_func(sent))\r\n for sent in split_sent_batch\r\n ]\r\n return noised_sent_batch\r\n\r\n\r\ndef numberfiltering(sents):\r\n # replace any word with numbers in it as <OOV>\r\n sents = [sent.strip().split() for sent in sents]\r\n for idx in range(len(sents)):\r\n for pos in range(len(sents[idx])):\r\n if hasNumbers(sents[idx][pos]):\r\n sents[idx][pos] = 'BlahBlah'\r\n # print(sents)\r\n return [' '.join(sent) for sent in sents]\r\n\r\n\r\n","sub_path":"noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83688575","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('fileindex', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Photo',\n fields=[\n ('indexedfile_ptr', models.OneToOneField(to='fileindex.IndexedFile', auto_created=True, primary_key=True, serialize=False, parent_link=True, on_delete=models.CASCADE)),\n ],\n bases=('fileindex.indexedfile',),\n ),\n ]\n","sub_path":"photoindex/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"337748668","text":"#!/usr/bin/python\n# coding: utf8\nprint(__doc__)\nfrom numpy import *\n\n# 加载数据集\ndef loadDataSet():\n return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]\n\n# 创建集合 C1。即对 dataSet 进行去重,排序,放入 list 中,然后转换所有的元素为 frozenset\ndef createC1(dataSet):\n \"\"\"createC1(创建集合 C1)\n\n Args:\n dataSet 原始数据集\n Returns:\n frozenset 返回一个 frozenset 格式的 list\n \"\"\"\n\n C1 = []\n for transaction in dataSet:\n for item in transaction:\n if not [item] in C1:\n # 遍历所有的元素,如果不在 C1 出现过,那么就 append\n C1.append([item])\n # 对数组进行 `从小到大` 的排序\n # print 'sort 前=', C1\n C1.sort()\n # frozenset 表示冻结的 set 集合,元素无改变;可以把它当字典的 key 来使用\n # print 'sort 后=', C1\n # print 'frozenset=', map(frozenset, C1)\n return list(map(frozenset, C1))\n\n# 计算候选数据集 CK 在数据集 D 中的支持度,并返回支持度大于最小支持度(minSupport)的数据\ndef scanD(D, Ck, minSupport):\n \"\"\"scanD(计算候选数据集 CK 在数据集 D 中的支持度,并返回支持度大于最小支持度 minSupport 的数据)\n\n Args:\n D 数据集\n Ck 候选项集列表\n minSupport 最小支持度\n Returns:\n retList 支持度大于 minSupport 的集合\n supportData 候选项集支持度数据\n \"\"\"\n\n # ssCnt 临时存放选数据集 Ck 的频率. 例如: a->10, b->5, c->8 \n ssCnt = {}\n for tid in D:\n for can in Ck:\n # s.issubset(t) 测试是否 s 中的每一个元素都在 t 中\n if can.issubset(tid):\n # if not ssCnt.has_key(can):\n if can not in ssCnt.keys():\n ssCnt[can] = 1\n else:\n ssCnt[can] += 1\n numItems = float(len(D)) # 数据集 D 的数量\n retList = []\n supportData = {}\n for key in ssCnt:\n # 支持度 = 候选项(key)出现的次数 / 所有数据集的数量\n support = ssCnt[key]/numItems\n if support >= minSupport:\n # 在 retList 的首位插入元素,只存储支持度满足频繁项集的值\n retList.insert(0, key)\n # 存储所有的候选项(key)和对应的支持度(support)\n supportData[key] = support\n return retList, supportData\n\n# 输入频繁项集列表 Lk 与返回的元素个数 k,然后输出所有可能的候选项集 Ck\ndef aprioriGen(Lk, k):\n \"\"\"aprioriGen(输入频繁项集列表 Lk 与返回的元素个数 k,然后输出候选项集 Ck。\n 例如: 以 {0},{1},{2} 为输入且 k = 2 则输出 {0,1}, {0,2}, {1,2}. 以 {0,1},{0,2},{1,2} 为输入且 k = 3 则输出 {0,1,2}\n 仅需要计算一次,不需要将所有的结果计算出来,然后进行去重操作\n 这是一个更高效的算法)\n\n Args:\n Lk 频繁项集列表\n k 返回的项集元素个数(若元素的前 k-2 相同,就进行合并)\n Returns:\n retList 元素两两合并的数据集\n \"\"\"\n \n retList = []\n lenLk = len(Lk)\n for i in range(lenLk):\n for j in range(i+1, lenLk):\n L1 = list(Lk[i])[: k-2]\n L2 = list(Lk[j])[: k-2]\n # print '-----i=', i, k-2, Lk, Lk[i], list(Lk[i])[: k-2]\n # print '-----j=', j, k-2, Lk, Lk[j], list(Lk[j])[: k-2]\n L1.sort()\n L2.sort()\n # 第一次 L1,L2 为空,元素直接进行合并,返回元素两两合并的数据集\n # if first k-2 elements are equal\n if L1 == L2:\n # set union\n # print 'union=', Lk[i] | Lk[j], Lk[i], Lk[j]\n retList.append(Lk[i] | Lk[j])\n return retList\n\n# 找出数据集 dataSet 中支持度 >= 最小支持度的候选项集以及它们的支持度。即我们的频繁项集。\ndef apriori(dataSet, minSupport=0.5):\n \"\"\"apriori(首先构建集合 C1,然后扫描数据集来判断这些只有一个元素的项集是否满足最小支持度的要求。那么满足最小支持度要求的项集构成集合 L1。然后 L1 中的元素相互组合成 C2,C2 再进一步过滤变成 L2,然后以此类推,知道 CN 的长度为 0 时结束,即可找出所有频繁项集的支持度。)\n\n Args:\n dataSet 原始数据集\n minSupport 支持度的阈值\n Returns:\n L 频繁项集的全集\n supportData 所有元素和支持度的全集\n \"\"\"\n # C1 即对 dataSet 进行去重,排序,放入 list 中,然后转换所有的元素为 frozenset\n C1 = createC1(dataSet)\n # print 'C1: ', C1\n # 对每一行进行 set 转换,然后存放到集合中\n D = dataSet\n # print 'D=', D\n # 计算候选数据集 C1 在数据集 D 中的支持度,并返回支持度大于 minSupport 的数据\n L1, supportData = scanD(D, C1, minSupport)\n # print \"L1=\", L1, \"\\n\", \"outcome: \", supportData\n\n # L 加了一层 list, L 一共 2 层 list\n L = [L1]\n k = 2\n # 判断 L 的第 k-2 项的数据长度是否 > 0。第一次执行时 L 为 [[frozenset([1]), frozenset([3]), frozenset([2]), frozenset([5])]]。L[k-2]=L[0]=[frozenset([1]), frozenset([3]), frozenset([2]), frozenset([5])],最后面 k += 1\n while (len(L[k-2]) > 0):\n # print 'k=', k, L, L[k-2]\n Ck = aprioriGen(L[k-2], k) # 例如: 以 {0},{1},{2} 为输入且 k = 2 则输出 {0,1}, {0,2}, {1,2}. 以 {0,1},{0,2},{1,2} 为输入且 k = 3 则输出 {0,1,2}\n # print 'Ck', Ck\n\n Lk, supK = scanD(D, Ck, minSupport) # 计算候选数据集 CK 在数据集 D 中的支持度,并返回支持度大于 minSupport 的数据\n # 保存所有候选项集的支持度,如果字典没有,就追加元素,如果有,就更新元素\n supportData.update(supK)\n if len(Lk) == 0:\n break\n # Lk 表示满足频繁子项的集合,L 元素在增加,例如: \n # l=[[set(1), set(2), set(3)]]\n # l=[[set(1), set(2), set(3)], [set(1, 2), set(2, 3)]]\n L.append(Lk)\n k += 1\n # print 'k=', k, len(L[k-2])\n return L, supportData\n\n# 计算可信度(confidence)\ndef calcConf(freqSet, H, supportData, brl, minConf=0.7):\n \"\"\"calcConf(对两个元素的频繁项,计算可信度,例如: {1,2}/{1} 或者 {1,2}/{2} 看是否满足条件)\n\n Args:\n freqSet 频繁项集中的元素,例如: frozenset([1, 3]) \n H 频繁项集中的元素的集合,例如: [frozenset([1]), frozenset([3])]\n supportData 所有元素的支持度的字典\n brl 关联规则列表的空数组\n minConf 最小可信度\n Returns:\n prunedH 记录 可信度大于阈值的集合\n \"\"\"\n # 记录可信度大于最小可信度(minConf)的集合\n prunedH = []\n for conseq in H: # 假设 freqSet = frozenset([1, 3]), H = [frozenset([1]), frozenset([3])],那么现在需要求出 frozenset([1]) -> frozenset([3]) 的可信度和 frozenset([3]) -> frozenset([1]) 的可信度\n\n # print 'confData=', freqSet, H, conseq, freqSet-conseq\n conf = supportData[freqSet]/supportData[freqSet-conseq] # 支持度定义: a -> b = support(a | b) / support(a). 假设 freqSet = frozenset([1, 3]), conseq = [frozenset([1])],那么 frozenset([1]) 至 frozenset([3]) 的可信度为 = support(a | b) / support(a) = supportData[freqSet]/supportData[freqSet-conseq] = supportData[frozenset([1, 3])] / supportData[frozenset([1])]\n if conf >= minConf:\n # 只要买了 freqSet-conseq 集合,一定会买 conseq 集合(freqSet-conseq 集合和 conseq集合 是全集)\n print (freqSet-conseq, '-->', conseq, 'conf:', conf)\n brl.append((freqSet-conseq, conseq, conf))\n prunedH.append(conseq)\n return prunedH\n\n# 递归计算频繁项集的规则\ndef rulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):\n \"\"\"rulesFromConseq\n\n Args:\n freqSet 频繁项集中的元素,例如: frozenset([2, 3, 5]) \n H 频繁项集中的元素的集合,例如: [frozenset([2]), frozenset([3]), frozenset([5])]\n supportData 所有元素的支持度的字典\n brl 关联规则列表的数组\n minConf 最小可信度\n \"\"\"\n # H[0] 是 freqSet 的元素组合的第一个元素,并且 H 中所有元素的长度都一样,长度由 aprioriGen(H, m+1) 这里的 m + 1 来控制\n # 该函数递归时,H[0] 的长度从 1 开始增长 1 2 3 ...\n # 假设 freqSet = frozenset([2, 3, 5]), H = [frozenset([2]), frozenset([3]), frozenset([5])]\n # 那么 m = len(H[0]) 的递归的值依次为 1 2\n # 在 m = 2 时, 跳出该递归。假设再递归一次,那么 H[0] = frozenset([2, 3, 5]),freqSet = frozenset([2, 3, 5]) ,没必要再计算 freqSet 与 H[0] 的关联规则了。\n m = len(H[0])\n if (len(freqSet) > (m + 1)):\n # print 'freqSet******************', len(freqSet), m + 1, freqSet, H, H[0]\n # 生成 m+1 个长度的所有可能的 H 中的组合,假设 H = [frozenset([2]), frozenset([3]), frozenset([5])]\n # 第一次递归调用时生成 [frozenset([2, 3]), frozenset([2, 5]), frozenset([3, 5])]\n # 第二次 。。。没有第二次,递归条件判断时已经退出了\n Hmp1 = aprioriGen(H, m+1)\n # 返回可信度大于最小可信度的集合\n Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)\n print ('Hmp1=', Hmp1)\n print ('len(Hmp1)=', len(Hmp1), 'len(freqSet)=', len(freqSet))\n # 计算可信度后,还有数据大于最小可信度的话,那么继续递归调用,否则跳出递归\n if (len(Hmp1) > 1):\n # print '----------------------', Hmp1\n # print len(freqSet), len(Hmp1[0]) + 1\n rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)\n\n# 生成关联规则\ndef generateRules(L, supportData, minConf=0.7):\n \"\"\"generateRules\n\n Args:\n L 频繁项集列表\n supportData 频繁项集支持度的字典\n minConf 最小置信度\n Returns:\n bigRuleList 可信度规则列表(关于 (A->B+置信度) 3个字段的组合)\n \"\"\"\n bigRuleList = []\n # 假设 L = [[frozenset([1]), frozenset([3]), frozenset([2]), frozenset([5])], [frozenset([1, 3]), frozenset([2, 5]), frozenset([2, 3]), frozenset([3, 5])], [frozenset([2, 3, 5])]]\n for i in range(1, len(L)):\n # 获取频繁项集中每个组合的所有元素\n for freqSet in L[i]:\n # 假设:freqSet= frozenset([1, 3]), H1=[frozenset([1]), frozenset([3])]\n # 组合总的元素并遍历子元素,并转化为 frozenset 集合,再存放到 list 列表中\n H1 = [frozenset([item]) for item in freqSet]\n # 2 个的组合,走 else, 2 个以上的组合,走 if\n if (i > 1):\n rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)\n else:\n calcConf(freqSet, H1, supportData, bigRuleList, minConf)\n return bigRuleList\n\n\ndef getActionIds():\n from time import sleep\n from votesmart import votesmart\n # votesmart.apikey = 'get your api key first'\n votesmart.apikey = 'a7fa40adec6f4a77178799fae4441030'\n actionIdList = []\n billTitleList = []\n fr = open('../db/11.Apriori/recent20bills.txt')\n for line in fr.readlines():\n billNum = int(line.split('\\t')[0])\n try:\n billDetail = votesmart.votes.getBill(billNum) # api call\n for action in billDetail.actions:\n if action.level == 'House' and (action.stage == 'Passage' or action.stage == 'Amendment Vote'):\n actionId = int(action.actionId)\n print ('bill: %d has actionId: %d' % (billNum, actionId))\n actionIdList.append(actionId)\n billTitleList.append(line.strip().split('\\t')[1])\n except:\n print (\"problem getting bill %d\" % billNum)\n sleep(1) # delay to be polite\n return actionIdList, billTitleList\n\n\ndef getTransList(actionIdList, billTitleList): #this will return a list of lists containing ints\n itemMeaning = ['Republican', 'Democratic']#list of what each item stands for\n for billTitle in billTitleList:#fill up itemMeaning list\n itemMeaning.append('%s -- Nay' % billTitle)\n itemMeaning.append('%s -- Yea' % billTitle)\n transDict = {}#list of items in each transaction (politician)\n voteCount = 2\n for actionId in actionIdList:\n sleep(3)\n print ('getting votes for actionId: %d' % actionId)\n try:\n voteList = votesmart.votes.getBillActionVotes(actionId)\n for vote in voteList:\n if not transDict.has_key(vote.candidateName):\n transDict[vote.candidateName] = []\n if vote.officeParties == 'Democratic':\n transDict[vote.candidateName].append(1)\n elif vote.officeParties == 'Republican':\n transDict[vote.candidateName].append(0)\n if vote.action == 'Nay':\n transDict[vote.candidateName].append(voteCount)\n elif vote.action == 'Yea':\n transDict[vote.candidateName].append(voteCount + 1)\n except:\n print (\"problem getting actionId: %d\" % actionId)\n voteCount += 2\n return transDict, itemMeaning\n\n\n# 暂时没用上\n# def pntRules(ruleList, itemMeaning):\n# for ruleTup in ruleList:\n# for item in ruleTup[0]:\n# print itemMeaning[item]\n# print \" -------->\"\n# for item in ruleTup[1]:\n# print itemMeaning[item]\n# print \"confidence: %f\" % ruleTup[2]\n# print #print a blank line\n\ndef testApriori():\n # 加载测试数据集\n dataSet = loadDataSet()\n print ('dataSet: ', dataSet)\n\n # Apriori 算法生成频繁项集以及它们的支持度\n L1, supportData1 = apriori(dataSet, minSupport=0.7)\n print ('L(0.7): ', L1)\n print ('supportData(0.7): ', supportData1)\n\n print ('->->->->->->->->->->->->->->->->->->->->->->->->->->->->')\n\n # Apriori 算法生成频繁项集以及它们的支持度\n L2, supportData2 = apriori(dataSet, minSupport=0.5)\n print ('L(0.5): ', L2)\n print ('supportData(0.5): ', supportData2)\n\ndef testGenerateRules():\n # 加载测试数据集\n dataSet = loadDataSet()\n print ('dataSet: ', dataSet)\n\n # Apriori 算法生成频繁项集以及它们的支持度\n L1, supportData1 = apriori(dataSet, minSupport=0.5)\n print ('L(0.7): \\n', L1)\n print ('supportData(0.7):\\n ', supportData1)\n\n # 生成关联规则\n rules = generateRules(L1, supportData1, minConf=0.5)\n print ('rules:\\n ', rules)\n\ndef main():\n # 测试 Apriori 算法\n # testApriori()\n\n # 生成关联规则\n # testGenerateRules()\n\n ##项目案例\n # # 构建美国国会投票记录的事务数据集\n # actionIdList, billTitleList = getActionIds()\n # # 测试前2个\n # transDict, itemMeaning = getTransList(actionIdList[: 2], billTitleList[: 2])\n #transDict 表示 action_id的集合,transDict[key]这个就是action_id对应的选项,例如 [1, 2, 3]\n # transDict, itemMeaning = getTransList(actionIdList, billTitleList)\n # # 得到全集的数据\n # dataSet = [transDict[key] for key in transDict.keys()]\n # L, supportData = apriori(dataSet, minSupport=0.3)\n # rules = generateRules(L, supportData, minConf=0.95)\n # print (rules)\n\n # # 项目案例\n # # 发现毒蘑菇的相似特性\n # # 得到全集的数据\n dataSet = [line.split() for line in open(\"../db/11.Apriori/mushroom.dat\").readlines()]\n L, supportData = apriori(dataSet, minSupport=0.3)\n # # 2表示毒蘑菇,1表示可食用的蘑菇\n # # 找出关于2的频繁子项出来,就知道如果是毒蘑菇,那么出现频繁的也可能是毒蘑菇\n for item in L[1]:\n if item.intersection('2'):\n print (item)\n \n for item in L[2]:\n if item.intersection('2'):\n print (item)\n\nif __name__ == \"__main__\":\n # main()\n # testApriori()\n testGenerateRules()\n","sub_path":"13关联分析/apriori_ys.py","file_name":"apriori_ys.py","file_ext":"py","file_size_in_byte":16406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"439084553","text":"from gettvshow import gettvshow\nfrom channeladdr import channeladdr,tags\nfrom my_time import timelength_\nfrom channelname import name_normalize\ndef gettags(start,end,channel,number):#给用户的每个收视时段所观看的电视节目所进行的标签\n channel = name_normalize(channel)\n start = str(start)\n end = str(end)\n if channel in channeladdr:\n try:\n showlist = gettvshow(start,end,channel)#Excel附件原始形式的参数\n except:\n print(start,end,channel)\n pass#利用豆瓣对所看节目进行标签,并对标签进行时长累加,返回([标签,时长])\n return 0\n elif channel in tags:\n lbas = []#label and scores\n for tag in tags[channel]:\n lbas.append([tag,timelength_(start,end)])\n return lbas\n else:\n print('无与'+channel+'相关的数据!')\n return 0\ndef givetags(dic,account,tags):#给每个用户贴上标签\n if not account in dic:\n dic[account] = {}\n for tag in tags:\n if tag[0] in dic[account]:\n dic[account][tag[0]] = dic[account][tag[0]] + tag[1]\n else:\n dic[account][tag[0]] = tag[1]\n return dic\n","sub_path":"雷打不动的论文和附件/提交的附件/别点/千万别点/附件/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"515433745","text":"# global imports\nfrom Tkinter import *\nimport ttk\nimport os\n\n# own imports\nimport Plugins\n\n# create master and main widget\nmaster = Tk()\nprogram_name = \"La Paella\"\nmaster.wm_title(program_name)\nmaster.overrideredirect(1)\n\n# frame_time, used to control timers by doing frame_time % <timer> == 0\n# can also be used to know the ammount of frames the program has played\nframe_time = 0\nsmooth_value = 0\nglobal_timer = 0\nupdated = False\nnew_created = True\nlast_geometry = Plugins.ProgramGetSize(master)\nnew_geometry = last_geometry\nglobal_username = \"__USERNAME__\"\n\n#colors\nprogram_bg = \"#2980b9\"\nprogram_border = \"#1c567d\"\nprogram_border_dark = \"#123a54\"\n\n#widgets\nprogram_bg_clear_fg = \"#2e90d1\"\nprogram_bg_dark_fg = \"#52a7e0\"\n\nprogram_fg_clear_bg = \"#2c3e50\"\nprogram_fg_dark_bg = \"#34495e\"\n\nprogram_clear = \"#ffffff\"\n\n#set program window background color\nmaster[\"bg\"]=program_bg\nmain_border=Frame(master, bg=program_border)\ntop_bar = Frame(main_border, bg=program_border)\ntop_bar_name = Label(top_bar, text=program_name, bg=program_border, fg=program_clear)\ntop_bar_icon_image = PhotoImage(file=\"data/icon/icon_16x16.gif\")\nprogram_icon_image = PhotoImage(file=\"data/icon/icon_196x196.gif\")\ntop_bar_icon = Label(top_bar, text=\"\", image=top_bar_icon_image, bg=program_border)\ntop_bar_icon.pack(side=LEFT)\n#move window with top_bar if clicked\ntop_bar.bind(\"<Button-1>\", lambda x: Plugins.ProgramDragWithMouse(master, x))\ntop_bar_name.bind(\"<Button-1>\", lambda x: Plugins.ProgramDragWithMouse(master, x))\ntop_bar_name.pack(side=LEFT, fill=X, expand=YES)\n#functions\ndef ProgramEnd(frame = None):\n os._exit(1)\n \ndef ReloadIndexesInListbox(new_value, target_list):\n pass\n\nclose_button = Button(top_bar, text=\"x\", command=lambda: ProgramEnd(),\n bg=program_border_dark, fg=\"white\", bd=0,\n highlightthickness=0)\n\ndef main(status = \"Login\"):\n global last_geometry, new_geometry, updated, new_created\n \n main_frame = Frame(main_border, bg=program_bg)\n program_status = status\n #Misc Functions\n def UnbindWheel(widget):\n widget.bind(\"<MouseWheel>\", DoNothing) # windows and mac\n widget.bind(\"<Button-4>\", DoNothing) # linux specific\n widget.bind(\"<Button-5>\", DoNothing) # linux specific\n \n def DoNothing(event):\n return \"break\"\n\n #constants and program-based value\n user_list = {\n 0: \"Juan Perez\",\n 1: \"Lucas Rojas\",\n 2: \"Rodrigo Mesa\",\n 3: \"Pedro Palma\",\n 4: \"Amarando Cortez\",\n 5: \"Javier Astorga\",\n 6: \"Ignacio Rivero\",\n 7: \"Carlos Gomez\",\n 8: \"Federico Santamaria\",\n 9: \"Antonio Rios\",\n 10: \"Cesar Bustamante\",\n 11: \"Esteban Soto\",\n 12: \"Marisol Tapia\",\n }\n for i in range(1000):\n user_list[i+12] = \"User\"+str(i)\n \n user_list_length = len(user_list.keys())\n\n # no matter the program_status, there is a menu, if a program_status \n # needs tohide it, there is a config for it\n menu0 = Menu(main_frame)\n #master.config(menu=menu0)\n\n def hello(): pass\n\n filemenu = Menu(menu0, tearoff=0)\n filemenu.add_command(label=\"Open\", command=hello)\n filemenu.add_command(label=\"Save\", command=hello)\n filemenu.add_separator()\n filemenu.add_command(label=\"Exit\", command=lambda: ProgramEnd(main_frame))\n menu0.add_cascade(label=\"File\", menu=filemenu)\n\n # setup widgets based on program_status\n if program_status == \"Login\":\n label0 = Label(main_frame, text=\"Bienvenido a\", font=(\"Mono\", 16),\n bg=program_bg)\n label1 = Label(main_frame, text=program_name, font=(\"Mono\", 24),\n bg=program_bg)\n label2 = Label(main_frame, text=\"Elija su usuario de la lista:\",\n font=(\"Sans\", 12), bg=program_bg)\n \n label3 = Label(main_frame, text=\"Elija fuente de\",\n font=(\"Sans\", 12), bg=program_bg)\n label4 = Label(main_frame, text=\"usuarios y peliculas:\",\n font=(\"Sans\", 12), bg=program_bg)\n \n program_icon = Label(main_frame, text=\"\", image=program_icon_image,\n bg=program_bg, borderwidth=0)\n \n option_val = StringVar()\n option_list = [\"MovieLens 10M Dataset\", \"Small Dataset\"]\n option = OptionMenu(main_frame, option_val, *option_list,\n command=None)\n option[\"menu\"].config(bg=program_bg, fg=program_clear,\n activebackground=program_bg)\n option.config(bg=program_bg, fg=program_clear, relief=FLAT,\n highlightthickness=0, ) \n \n option_val.set(option_list[0])\n \n listbox0 = Listbox(main_frame, relief=FLAT, selectmode=SINGLE, bd=0,\n highlightthickness=0)\n \n scale0 = Scale(main_frame, from_=0, to_=100, orient=\"vertical\",\n showvalue=0, borderwidth=0, sliderrelief=FLAT,\n highlightcolor=program_bg, highlightthickness=0)\n \n bf = Frame(main_frame, bg=program_bg)\n bf_left = Frame(bf, bg=program_bg)\n bf_right = Frame(bf, bg=program_bg)\n \n button0 = Button(bf_left, text=\"Login\", relief=FLAT,\n command=lambda: ProgramSwitchMode(\"Loading\"),\n bg=program_bg, highlightthickness=0)\n button1 = Button(bf_right, text=\"Exit\", relief=FLAT,\n command=lambda: ProgramEnd(main_frame),\n bg=program_bg, highlightthickness=0)\n \n button2_value = option_list[0]\n button2 = Button(main_frame, text=\"Aplicar cambios...\", relief=FLAT,\n command=lambda: ReloadIndexesInListbox(button2_value, listbox0), \n bg=program_bg, highlightthickness=0)\n \n label0.grid(row=0, padx=8)\n label1.grid(row=1, padx=8, pady=(0, 8))\n label2.grid(row=5, padx=8, sticky=W)\n \n program_icon.grid(row=2)\n \n label3.grid(row=3, padx=8, sticky=W)\n option.grid(row=5, sticky=W+E, padx=8)\n label4.grid(row=4, padx=8, sticky=W)\n button2.grid(row=6, padx=8, sticky=W+E)\n \n listbox0.grid(row=7, padx=(8,26), pady=(12,4), sticky=W+E)\n scale0.grid(row=7, padx=(0, 8), pady=(12, 4), sticky=E+N+S)\n \n bf.grid(row=8, sticky=W+E)\n bf_left.pack(fill=BOTH, expand=YES, side=LEFT, padx=(8, 0), pady=4)\n bf_right.pack(fill=BOTH, expand=YES, side=RIGHT, padx=(0, 8), pady=4)\n\n button0.pack(fill=BOTH)\n button1.pack(fill=BOTH)\n \n UnbindWheel(listbox0)\n for user_id, user in user_list.items():\n listbox0.insert(END, str(user))\n for i in range(len(user_list)):\n #colour items based on modulo\n try:\n if i%2==0:\n color = program_bg_clear_fg\n color2 = program_fg_dark_bg\n else:\n color = program_bg_dark_fg\n color2 = program_fg_clear_bg\n listbox0.itemconfig(i, {'bg':color, \"fg\":color2})\n except:\n break\n \n elif program_status == \"Loading\":\n #design Loading screen\n label0 = Label(main_frame, text=\"Loading content...\",\n font=(\"Monospaced\", 24), bg=program_bg)\n (animation0, \n animation0_list, \n animation0_len) = Plugins.GetAnimationFromGif(main_frame, \"data/running.gif\")\n \n animation0.config(bg=program_bg)\n label0.grid(row=0)\n animation0.grid(row=1, pady=8)\n\n elif program_status == \"TopTen\":\n labeluser = Label(main_frame, text=\"Bienvenido: \"+str(global_username),\n font=(\"Serif\", 22), bg=program_bg)\n label0 = Label(main_frame, text=\"Estas son las 10 peliculas\\nrecomendadas para usted!\",\n font=(\"Serif\", 16), bg=program_bg)\n data_frame = Frame(main_frame, bg=program_bg)\n count, count_list, count_len = Plugins.GetAnimationFromGif(main_frame, \"data/countdown.gif\") \n count[\"bg\"] = program_bg\n scale0 = Scale(main_frame, orient=\"horizontal\", showvalue=0, relief=FLAT,\n borderwidth=0, from_=0, to=9, sliderrelief=FLAT,\n highlightthickness=0)\n\n label1 = Label(data_frame, text=\" \"*20, font=(\"Mono\", 16), bg=program_bg)\n label2 = Label(data_frame, text=\"\", font=(\"Serif\", 12), bg=program_bg)\n label3 = Label(data_frame, text=\"\", font=(\"Serif\", 12), bg=program_bg)\n \n label4 = Label(main_frame, text=\"+1;\", font=(\"Arial Black\", 24), bg=\"#181818\", fg=\"white\")\n \n button0 = Button(main_frame, text=\"Volver Atras!\",\n command=lambda: ProgramSwitchMode(\"Login\"),\n highlightthickness=0)\n \n labeluser.grid(row=0, columnspan=2, padx=8)\n label0.grid(row=1, columnspan=2)\n label1.pack(fill=BOTH, padx=8)\n label2.pack(fill=X, padx=8)\n label3.pack(fill=X, padx=8)\n \n data_frame.grid(row=2, column=1, sticky=N+S+W+E)\n \n count.grid(row=2, padx=8)\n label4.grid(row=2, sticky=E,padx=12) #topkek\n scale0.grid(row=3, sticky=W+E, padx=8)\n button0.grid(row=3, column=1, padx=8, pady=4, sticky=W+E)\n\n #allow for ProgramUpdateWidgets to modify widgets properties\n updated = True\n \n #UpdateStep function\n def ProgramUpdateWidgets():\n global frame_time, global_timer, smooth_value\n # get program size\n program_width, program_height = master.winfo_width(), master.winfo_height()\n frame_time += 1\n #master.update()\n master.geometry(\"\")\n \n #dont update if no widgets exists\n if updated == False:\n return 0\n try:\n if program_status == \"None\":\n ProgramEnd(main_frame)\n \n if program_status == \"Login\":\n global global_username\n #set scale0 <to> based on listbox0 length\n user_list_length = len(user_list)\n listbox0_max = max(user_list_length - int(listbox0[\"height\"]), 0)\n scale0.config(to=listbox0_max, resolution=0.01)\n \n #set listbox position based on scale\n listbox0_y = int(round(scale0.get() ))\n listbox0.yview(listbox0_y)\n \n global_username = listbox0.get(ACTIVE) \n \n elif program_status == \"Loading\":\n animation0.config(image=animation0_list[(frame_time/400)%animation0_len])\n if frame_time%100 == 0:\n global_timer += 1\n if global_timer >= 200:\n global_timer = 0\n ProgramSwitchMode(\"TopTen\")\n \n elif program_status == \"TopTen\":\n tenth = (count_len)/10.0\n value = tenth * float(scale0.get())\n smooth_value += (value - smooth_value)/1000.0\n \n count.config(image=count_list[int(smooth_value%count_len)])\n \n label1.config(text=str(\"Movie Number \"+str(10-scale0.get())+\": \").center(20))\n label2.config(text=\"sframe: \"+str(round(smooth_value,2)))\n label3.config(text=\"frame: \"+str(value))\n except:\n return 0\n \n def ProgramSwitchMode(mode=\"Loading\"):\n global updated, last_geometry\n last_geometry = Plugins.ProgramGetSize(master)\n main_frame.destroy()\n updated = False\n main(mode)\n \n\n # show main_frame, no longer available to edit\n close_button.pack(side=RIGHT)\n top_bar.pack(fill=BOTH)\n main_frame.pack(fill=BOTH, padx=4, pady=(0,4))\n main_border.pack(fill=BOTH)\n # resize program\n master.update()\n master.geometry(\"\")\n master.update()\n if new_created:\n last_geometry = Plugins.ProgramGetSize(master)\n new_created = False\n else:\n master.update()\n new_geometry = Plugins.ProgramGetSize(master)\n Plugins.ProgramResizeSmooth(master, last_geometry, new_geometry)\n #print last_geometry, new_geometry\n \n # main loop\n master.resizable(width=False, height=False)\n master.protocol(\"WM_DELETE_WINDOW\", lambda: ProgramEnd(master))\n while True:\n master.after(1000/60, lambda: ProgramUpdateWidgets())\n master.update()\n\nif __name__ == \"__main__\":\n main(\"Login\")\n","sub_path":"UI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463297474","text":"# This is my first python application.\r\n# In this app you have to give numbers. After giving numbers you have to enter any non numeric value.\r\n# Then it will start the calculation process.\r\n\r\n\r\nList = []\r\nprint('Please start giving me numbers, I will start calculating as soon as you give me a non integer value')\r\nwhile True:\r\n value = input('Enter a number- ')\r\n try:\r\n value = float(value)\r\n except:\r\n break\r\n List.append(value)\r\nup = 0\r\nfor var in List:\r\n up += var\r\nprint(float(up/len(List)))\r\ninput('Press enter to close program...')\r\n","sub_path":"Average-Calculator.py","file_name":"Average-Calculator.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"484767843","text":"##### Adam Mansuri \r\n\r\nimport time\r\nimport math\r\nimport sys\r\n\r\n\r\n### These are the tiles with the frogs and toads in their original positions\r\ntileList= ['F','F','F',' ','T','T','T']\r\n\r\n\r\n### This code will show a demonstration for the user, so they know how to play the game. This will be presented as a selection in a menu that i will create later on.\r\ndef demonstration():\r\n print(\"The starting positions are: \")\r\n time.sleep(1)\r\n print(\"\")\r\n print(tileList)\r\n time.sleep(1)\r\n print(\"\")\r\n print(\"To win, you would have to move like below: \")\r\n time.sleep(1)\r\n print(\"\")\r\n print(3,4,['F','F',' ','F','T','T','T'])\r\n print(5,3,['F','F','T','F',' ', 'T', 'T'])\r\n print(6,5,['F','F','T','F','T',' ','T'])\r\n print(4,6,['F','F','T',' ', 'T', 'F','T'])\r\n print(2,4,['F', ' ', 'T', 'F', 'T', 'F', 'T'])\r\n print(1,2,[' ', 'F','T','F','T','F','T'])\r\n print(3,1,['T','F',' ', 'F', 'T','F', 'T'])\r\n print(5,3,['T','F','T','F',' ', 'F', 'T'])\r\n print(7,5,['T','F','T','F','T','F',' '])\r\n print(6,7,['T','F','T','F','T',' ', 'F'])\r\n print(4,6,['T','F','T',' ', 'T', 'F','F'])\r\n print(2,4,['T',' ','T','F','T','F','F'])\r\n print(3,2,['T','T',' ','F','T','F','F'])\r\n print(5,3,['T','T','T','F', ' ', 'F','F'])\r\n print(4,5,['T','T','T', ' ', 'F','F','F'])\r\n time.sleep(1)\r\n print(\"\")\r\n print(\"You have won!\")\r\n\r\n\r\n### Here i will use a method(function) to declare a method called correctMove and define it so that it has everything to do with when the user enters something correct.\r\n### In this function i will have to define that the user can move into an empty tile next to the current tile or can jump across another frog/toad to the next empty tile.\r\n### the 'tileList', 'fromTile' and 'toTile' will be passed on so i will put them in as the parameters\r\ndef correctMove(tileList,fromTile,toTile):\r\n if tileList[toTile]!=' ':\r\n return False\r\n if tileList[fromTile] == 'F':\r\n if fromTile>toTile or abs(toTile-fromTile)>2:\r\n return False\r\n else:\r\n if fromTile<toTile or abs(toTile-fromTile)>2:\r\n return False\r\n return True\r\n\r\n\r\n### This is a function which will be called when the user wins the game.\r\n### The code looks complex but its simple. It consisted of me creating 2 boolean flags which were originally false then after the piece of code which defined the user to win, the boolean flag change to true.\r\ndef winGame():\r\n flag=False\r\n flag2=False\r\n for i in range(0,3):\r\n if tileList[i] =='F':\r\n flag= True\r\n for i in range(4,len(tileList)):\r\n if tileList[i]=='T':\r\n flag2= True\r\n if flag==True and flag2== True:\r\n return True\r\n\r\n\r\n\r\n### Now i will create a function so that the user can quit the game. Again i will put this in a menu later on\r\ndef quitGame():\r\n print(\"Game Over, You Quit!\")\r\n sys.exit(1)\r\n\r\n\r\n### Now using all the above functions of correctMove and winGame, i will implement them inside the actual game.\r\ndef startGame(tileList):\r\n print(tileList)\r\n print(\"From which tile: \")\r\n fromTile= int(input())-1 ### I did -1 because the list starts from index 0, and i want the user to select a number starting from 1 and not 0\r\n print(\"To which tile: \")\r\n toTile = int(input())-1\r\n\r\n correct=correctMove(tileList,fromTile, toTile)\r\n\r\n if correct:\r\n value= tileList[fromTile]\r\n tileList[toTile]= value\r\n tileList[fromTile] = ' '\r\n print(\"new tileList:\\t\",tileList)\r\n else:\r\n print(\"Invalid jump!\")\r\n\r\n if winGame==True:\r\n print(\"Congratulation, you have won the game!\")\r\n\r\n quitGame()\r\n\r\n\r\n\r\n\r\n### I will create a function so that the user can replay the game. Again i will put this in a menu later on\r\ndef replayGame(tileList):\r\n print(\"Starting positions are: \", tileList)\r\n startGame(tileList)\r\n\r\n### Now i will build a menu to increase user interaction so that they can select one of the 3 choices: 1)demonstration, 2)play the game or 3)quit the game. Hence, these 3 methods will be implemented inside the menu\r\n###For this i will use a while loop which will contain nested if/else statements\r\nwhile True:\r\n print(\"To quit the game press 2\")\r\n print(\"To replay the game press 0\")\r\n print(\"To see the demonstration press 1\")\r\n print(\"Press 3 to continue game!\")\r\n\r\n userSelection= int(input())\r\n\r\n if(userSelection)==2:\r\n quitGame()\r\n elif(userSelection)==0:\r\n replayGame(tileList)\r\n elif(userSelection)==1:\r\n demonstration()\r\n elif(userSelection)==3:\r\n print(\"Lets Continue!\")\r\n startGame(tileList)\r\n else:\r\n print()\r\n","sub_path":"FrogsandToads.py","file_name":"FrogsandToads.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"12667435","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Created by 秋叶夏风\n\n# 本模块的功能:<>\n\n\nimport sys\n\nfrom PyQt5.QtGui import QIcon, QFont\n\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QToolTip\n\napp = QApplication(sys.argv)\nw = QWidget()\nw.setWindowTitle(\"刘金玉编程\")\napp.setWindowIcon(QIcon(\"./images/车.png\"))\nQToolTip.setFont(QFont(\"隶书\",40))\nw.setToolTip(\"编程创造城市\")\n# 按钮\nbtn = QPushButton(\"老刘\",w)\nbtn.move(50,50)\nbtn.setToolTip(\"你好buton\")\nw.show()\n\napp.exec_()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"code/LJYDemo/Demo5/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"346784291","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: /home/marx/venv3/lib/python3.6/site-packages/tsr/modules/general.py\n# Compiled at: 2018-06-27 08:14:39\n# Size of source mod 2**32: 10003 bytes\nimport datetime, json\nfrom .os_info import path\nimport os.path\nfrom dateutil.relativedelta import relativedelta\nusers = {}\nusername_colour_dict = {}\nusername_to_id = {}\nusers = json.load(open(os.path.join(path.settings, 'users.json')))\nfor entry in users:\n if 'colour' not in users[entry]:\n users[entry]['colour'] = 'end'\n\nsettings = json.load(open(os.path.join(path.settings, 'settings.json')))\n\ndef level_domain(level, domain):\n if not is_int(level):\n raise ValueError('level_domain(level_number, domain_string)')\n neglevel = -int(level)\n return '.'.join(domain.split('.')[neglevel:])\n\n\ndef dictfind(original_dict, **kwargs):\n \"\"\" eg\n >>>d={\n 'foo':{\n 'bar': 11,\n 'bob': 'george',\n },\n 'gimli':{\n 'gandalf':{\n 'frodo':5,\n 'samwise':7,\n },\n 'radagast':11,\n },\n 'jones':{\n 'gandalf':{\n 'frodo':1,\n 'samwise':2,\n },\n 'radagast':3,\n },\n }\n >>>find(d, bar='>5')\n ['foo']\n >>>find(d, gandalf_frodo='>3')\n ['gimli']\n \"\"\"\n ListOnlyKeys = True\n if '_ListOnlyKeys' in kwargs:\n ListOnlyKeys = kwargs['_ListOnlyKeys']\n d = dict(original_dict)\n for kw in kwargs:\n if kw[0] != '_':\n kw_value = kwargs[kw]\n kw_relation = None\n if kw_value[0] in ('*', '>', '<', '='):\n kw_relation = kw_value[0]\n kw_value = kw_value[1:]\n kw_relation_end = None\n if kw_value[(-1)] in ('*', ):\n kw_relation_end = kw_value[(-1)]\n kw_value = kw_value[:-1]\n new_d = {}\n key0 = None\n if '_' in kw:\n key0 = kw.split('_')[0]\n key1 = kw.split('_')[1]\n for key in d:\n if key0 in d[key]:\n if key1 in d[key][key0]:\n this_value = d[key][key0][key1]\n if kw_relation == '>':\n kw_value = int(kw_value)\n if this_value > kw_value:\n new_d[key] = d[key]\n else:\n if kw_relation == '<':\n kw_value = int(kw_value)\n if this_value > kw_value:\n new_d[key] = d[key]\n elif kw_relation == '=' and this_value == kw_value:\n pass\n new_d[key] = d[key]\n\n else:\n if kw_relation_end == '*':\n kw_value = kw_value[:-1]\n for key in d:\n if key.startswith(kw_value):\n new_d[key] = d[key]\n\n else:\n if kw_relation == '*':\n kw_value = kw_value\n for key in d:\n if key.endswith(kw_value):\n new_d[key] = d[key]\n\n else:\n if kw_relation == '>':\n kw_value = int(kw_value)\n for key in d:\n if d[key][kw] > kw_value:\n print((' {}>{}'.format(d[key][kw], kw_value)), end='\\r')\n new_d[key] = d[key]\n\n else:\n if kw_relation == '<':\n kw_value = int(kw_value)\n for key in d:\n if d[key][kw] < kw_value:\n new_d[key] = d[key]\n\n else:\n for key in d:\n if d[key][kw] == kw_value:\n new_d[key] = d[key]\n\n d = dict(new_d)\n\n if ListOnlyKeys:\n return [key for key in d]\n else:\n return d\n\n\ndef userid_colour(userid):\n if type(userid) != 'str':\n userid = str(userid)\n try:\n return users[userid]['colour']\n except:\n raise Exception('userid {0} has no colour. users[{0}] = {1}'.format(userid, users[userid]))\n\n\ndef make_n_char_long(x, n, spacing=' '):\n y = str(x)\n while len(y) < n:\n y += spacing\n\n if len(y) > n:\n y = y[:n]\n return y\n\n\ndef myjoin(*args):\n string = ''\n for arg in args:\n string += ' ' + str(arg)\n\n return string[2:]\n\n\ndef standardise_datetime(datestr):\n if isinstance(datestr, datetime.datetime):\n return datestr\n else:\n if isinstance(datestr, datetime.date):\n return datetime.datetime.combine(datestr, datetime.time(0, 0))\n try:\n return datetime.datetime.strptime(datestr, '%d-%m-%Y')\n except:\n try:\n return datetime.datetime.strptime(datestr, '%Y-%m-%d')\n except:\n datestr = datestr.strip().lower()\n if datestr == 'yesterday':\n return datetime.datetime.now() - datetime.timedelta(days=1)\n if 'ago' in datestr:\n date_ls = datestr.split(' ')\n try:\n n = int(date_ls[0])\n formatIs_n_obj_ago = True\n except:\n formatIs_n_obj_ago = False\n\n if formatIs_n_obj_ago:\n date_type = date_ls[1]\n if date_type in ('second', 'seconds'):\n return datetime.datetime.now() - datetime.timedelta(seconds=n)\n if date_type in ('minute', 'minutes'):\n return datetime.datetime.now() - relativedelta(minutes=n)\n if date_type in ('hour', 'hours'):\n return datetime.datetime.now() - relativedelta(hours=n)\n if date_type in ('day', 'days'):\n return datetime.datetime.now() - datetime.timedelta(days=n)\n if date_type in ('week', 'weeks'):\n return datetime.datetime.now() - datetime.timedelta(days=(n * 7))\n if date_type in ('month', 'months'):\n return datetime.datetime.now() - relativedelta(months=n)\n if date_type in ('year', 'years'):\n return datetime.datetime.now() - relativedelta(years=n)\n if date_type in ('decade', 'decades'):\n return datetime.datetime.now() - relativedelta(years=(n * 10))\n else:\n for char in ('T', ' ', '_'):\n if len(datestr) > 18:\n try:\n try:\n datestr = datestr[:19]\n return datetime.datetime.strptime(datestr, '%Y-%m-%d' + char + '%H:%M:%S')\n except:\n datestr = datestr[:19]\n return datetime.datetime.strptime(datestr, '%d-%m-%Y' + char + '%H:%M:%S')\n\n except:\n pass\n\n try:\n try:\n return datetime.datetime.strptime(datestr, '%Y-%m-%d' + char + '%H:%M')\n except:\n return datetime.datetime.strptime(datestr, '%d-%m-%Y' + char + '%H:%M')\n\n except:\n pass\n\n raise Exception('Unknown datetime string: ' + str(datestr))\n\n\ndef standardise_datetime_str(datestr):\n return str(standardise_datetime(datestr))\n\n\ndef standardise_date(string):\n return standardise_datetime(string).date()\n\n\ndef standardise_date_str(datestr):\n return str(standardise_date(datestr))\n\n\ndef standardise_time(timestr):\n return datetime.datetime.strptime(timestr, '%H:%M').time()\n\n\ndef is_number(x):\n try:\n dummy = float(x)\n return True\n except:\n return False\n\n\ndef is_int(x):\n try:\n dummy = int(x)\n return True\n except:\n return False\n\n\ndef ls_rm_dupl(ls):\n l = []\n for x in ls:\n if x not in l:\n l.append(x)\n\n return l\n\n\ndef ls_in_str(ls, string):\n for element in ls:\n try:\n if element in string:\n return True\n except:\n pass\n\n return False\n\n\ndef mystrip(text):\n while ' ' in text:\n text = text.replace(' ', ' ')\n\n while '\\n\\n' in text:\n text = text.replace('\\n\\n', '\\n')\n\n while ' \\n' in text:\n text = text.replace(' \\n', '\\n')\n\n while '\\n ' in text:\n text = text.replace('\\n ', '\\n')\n\n while '\\n> > ' in text:\n text = text.replace('\\n> > ', '\\n> ')\n\n while '>\\n' in text:\n text = text.replace('>\\n', '')\n\n while '~\\n' in text:\n text = text.replace('~\\n', '\\n')\n\n while '\\n\\n' in text:\n text = text.replace('\\n\\n', '\\n')\n\n while '\\r\\n' in text:\n text = text.replace('\\r\\n', '\\n')\n\n while '\\n\\r' in text:\n text = text.replace('\\n\\r', '\\n')\n\n while '\\n\\n' in text:\n text = text.replace('\\n\\n', '\\n')\n\n return text.strip()","sub_path":"pycfiles/tsr-0.0.3.tar/general.cpython-36.py","file_name":"general.cpython-36.py","file_ext":"py","file_size_in_byte":9940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"619046917","text":"import cv2\r\nimport numpy as np\r\nimport pyzbar.pyzbar as pyzbar\r\nglobal abc\r\n\r\ndef main():\r\n cap=cv2.VideoCapture(0)\r\n string=webcam(cap)\r\n print(string)\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n\r\n\r\ndef webcam(cap):\r\n while True:\r\n aaa=''\r\n _,frame=cap.read()\r\n decodeObjects=pyzbar.decode(frame)\r\n for obj in decodeObjects:\r\n aaa=obj.data\r\n points=obj.polygon\r\n \r\n \r\n if len(points) > 4: \r\n hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))\r\n hull = list(map(tuple, np.squeeze(hull)))\r\n else: \r\n hull = points;\r\n \r\n \r\n n = len(hull) \r\n for j in range(0,n):\r\n cv2.line(frame, hull[j], hull[ (j+1) % n], (255,0,0), 3)\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n cv2.imshow(\"Frame\",frame)\r\n key=cv2.waitKey(1)\r\n if(key==27):\r\n break\r\n if(len(aaa)>0 and aaa!=''):\r\n abc=str(aaa)\r\n #print(abc)\r\n return(abc)\r\n break\r\n\r\n\r\nmain()","sub_path":"classes/com/thinking/machines/student/application/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"368506749","text":"__author__ = 'Newsteinwell 2015-10-06'\n'''\nThis function read an extant file, this file is included with the same folder, and named \"sampled_data.txt\".\n\nSome operation like gauss filter and sampling with the original data to get sampled_data.\n'''\nimport numpy as np\ndef re_sam_data(FC='FC1'):\n sampled_1=[]\n samp_data=open('sampled_data'+FC+'.txt','r')\n for temp in samp_data:\n temp1=temp.replace('\\n','').split(',')\n sampled_1.append([float(temp1[0]),float(temp1[1])])\n return np.array(sampled_1)\n\ndef re_nonsam_data(FC='FC1'):\n sampled_1=[]\n samp_data=open('nonsampled_data'+FC+'.txt','r')\n for temp in samp_data:\n temp1=temp.replace('\\n','').split(',')\n sampled_1.append([float(temp1[0]),float(temp1[1])])\n return np.array(sampled_1)\n","sub_path":"rvm/read_sam_data.py","file_name":"read_sam_data.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"21290863","text":"import boto3\n\nbucket_name=sys.argv[1]\nRegion_Name=sys.argv[2]\nVersioning=sys.argv[3]\nProject_Name=sys.argv[4]\nTeam=sys.argv[5]\nOwner=sys.argv[6]\nInfra_Owner=sys.argv[7]\nBusiness_Unit=sys.argv[8]\n\n\ns3 = boto3.client('s3')\nresponse = s3.list_buckets()\ncreate_s3=s3.create_bucket(Bucket=bucket_name,CreateBucketConfiguration={'LocationConstraint': Region_Name})\ncreate_tag=s3.put_bucket_tagging(Bucket=bucket_name,Tagging={'TagSet': [{'Key': 'Project_Name','Value': Project_Name},{'Key': 'Team','Value': Team},{'Key': 'Owner','Value': Owner},{'Key': 'Infra_Owner','Value': Infra_Owner},{'Key': 'Business_Unit','Value': Business_Unit}]})\ns3_versioning=s3.put_bucket_versioning(Bucket=bucket_name,VersioningConfiguration={'Status': Versioning})\n","sub_path":"S3_Create.py","file_name":"S3_Create.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"299750679","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 8 14:40:39 2016\r\n\r\n@author: Florian Jehn\r\n\"\"\"\r\n# import argv from sys\r\nfrom sys import argv\r\n\r\n# read scriptname and the first argument from argv\r\nscript, filename = argv\r\n\r\n# open the file for reading purposes\r\ntxt = open(filename,\"r\")\r\n\r\n# print the filename\r\nprint(\"Here's your file %r: \" % filename)\r\n\r\n# print the whole file\r\nprint(txt.read())\r\n\r\n# prompt the user for the filename again\r\nprint(\"Type the filename again: \")\r\nfile_again = input(\"> \")\r\n\r\n# open the file once more\r\ntxt_again = open(file_again)\r\n\r\n# print the file once more\r\nprint(txt_again.read())\r\n\r\ntxt.close()\r\ntxt_again.close()","sub_path":"ex15.py","file_name":"ex15.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127442097","text":"# -*- coding: UTF-8 -*-\nfrom AccessControl.SecurityManagement import getSecurityManager\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Five import BrowserView\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom cioppino.twothumbs import rate\nfrom plone import api\n\n\nclass AddonView(BrowserView):\n\n template = ViewPageTemplateFile('addonview.pt')\n\n def __call__(self):\n return self.template()\n\n\nclass SubmitAddon(BrowserView):\n\n def __call__(self):\n api.content.transition(self.context, 'submit')\n api.portal.show_message(\n message=\"Thank you for submitting '%s'\" % self.context.title,\n request=self.request,\n type='info')\n portal_url = api.portal.get().absolute_url()\n self.request.response.redirect(portal_url)\n\n\nclass AddonList(BrowserView):\n\n template = ViewPageTemplateFile('addonlist.pt')\n\n def items(self):\n results = []\n catalog = getToolByName(self.context, 'portal_catalog')\n brains = catalog.unrestrictedSearchResults(\n portal_type='addon',\n sort_on='sortable_title',\n review_state='pending',\n )\n for brain in brains:\n results.append(dict(\n title=brain.Title,\n state=brain.review_state,\n pypi_link=brain.pypi_link,\n ))\n return results\n\n def can_review(self):\n security = getSecurityManager()\n if security.checkPermission(\n 'paragon.site: Review Addon', self.context):\n return True\n\n\nclass AddonTable(BrowserView):\n \"\"\"\n \"\"\"\n\n template = ViewPageTemplateFile('addontable.pt')\n\n def items(self):\n results = []\n catalog = getToolByName(self.context, 'portal_catalog')\n brains = catalog(portal_type='addon')\n for brain in brains:\n obj = brain.getObject()\n tally = rate.getTally(obj)\n number_of_votes = tally['ups'] + tally['downs']\n if not number_of_votes:\n average_vote = '-'\n else:\n average_vote = (tally['ups'] - tally['downs']) \\\n / number_of_votes\n if average_vote > 0:\n average_vote = '+%s' % average_vote\n results.append(dict(\n title=brain.Title,\n url=brain.getURL(),\n pypi_link=brain.pypi_link,\n github_link=obj.github_link,\n state=brain.review_state,\n categories=', '.join(obj.categories),\n submitter=obj.name,\n tally=tally,\n number_of_votes=number_of_votes,\n average_vote=average_vote,\n ))\n return results\n","sub_path":"src/paragon/site/browser/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"135234458","text":"from flask import Flask\nfrom flask import render_template\nfrom search import search\nfrom flask import *\nimport os\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef first():\n return render_template('FloodRelief.html')#predict.html\n@app.route('/req1', methods=['POST'])\ndef req1():\n inp = request.form['inp'];\n if(len(inp)>0):\n res=search(inp.strip())\n # out= json.dumps({'status':'OK','name':res[0],'address':res[1],'camp':res[2]});\n out=res.to_json()\n print(out)\n\n return out\n else:\n print(\"no inp\")\n return json.dumps({'status':'OK','name':'','address':'','camp':''});\n@app.route('/favicon.ico')\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, 'static'),\n 'favicon.ico', mimetype='image/vnd.microsoft.icon')\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"28378388","text":"\n\nimport sys\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom grakel.utils import graph_from_networkx\nfrom tqdm import tqdm\nfrom utils import load_file, preprocessing, get_vocab\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom grakel.kernels import Kernel\nfrom grakel.kernels import ShortestPath , PyramidMatch\nfrom grakel.kernels import WeisfeilerLehman, VertexHistogram\nfrom grakel.datasets import fetch_dataset\nfrom grakel import Graph\nfrom timeit import default_timer as timer\nfrom gpcharts import figure\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV\n\n\ndef spgk(sp_g1, sp_g2, norm1, norm2):\n \"\"\" \n Compute spgk kernel\n \"\"\"\n if norm1 == 0 or norm2==0:\n return 0\n else:\n kernel_value = 0\n for node1 in sp_g1:\n if node1 in sp_g2:\n kernel_value += 1\n for node2 in sp_g1[node1]:\n if node2 != node1 and node2 in sp_g2[node1]:\n kernel_value += (1.0/sp_g1[node1][node2]) * (1.0/sp_g2[node1][node2])\n\n kernel_value /= (norm1 * norm2)\n \n return kernel_value\n\ndef create_graphs_of_words1(docs, vocab, window_size):\n graphs = list()\n sizes = list()\n degs = list()\n print(vocab)\n for idx,doc in enumerate(docs):\n G = nx.Graph()\n for i in range(len(doc)):\n if doc[i] not in G.nodes():\n G.add_node(doc[i])\n G.nodes[doc[i]]['label'] = vocab[doc[i]]\n \n \n for i in range(len(doc)):\n for j in range(i+1, i+window_size):\n if j < len(doc):\n G.add_edge(doc[i], doc[j])\n \n graphs.append(G)\n \n return graphs\n\n\n\ndef create_graph_of_words(docs, voc, window_size):\n graphs = []\n for doc in docs:\n edges = {}\n unique_words = set()\n for i in range(len(doc)):\n unique_words.add(doc[i])\n for j in range(i+1, i+window_size):\n if j < len(doc):\n unique_words.add(doc[j])\n edge_tuple1 = (doc[i], doc[j])\n if edge_tuple1 in edges:\n edges[edge_tuple1] += 1\n else:\n edges[edge_tuple1] = 1\n node_labels = {word:voc[word] for word in unique_words}\n g = Graph(edges, node_labels=node_labels)\n graphs.append(g)\n\n return graphs\n\n\ndef main():\n \"\"\" \n Main function\n \"\"\"\n if len(sys.argv) != 5:\n print('Wrong number of arguments!!! Run as follows:')\n print('spgk.py <filenamepos> <filenameneg> <windowsize> <depth>')\n else:\n filename_pos = sys.argv[1]\n filename_neg = sys.argv[2]\n window_size = int(sys.argv[3])\n depth = int(sys.argv[4])\n docs_pos = load_file(filename_pos)\n docs_pos = preprocessing(docs_pos)\n labels_pos = []\n for i in range(len(docs_pos)):\n labels_pos.append(1)\n\n docs_neg = load_file(filename_neg)\n docs_neg = preprocessing(docs_neg)\n labels_neg = []\n for i in range(len(docs_neg)):\n labels_neg.append(0)\n\n docs = docs_pos\n docs.extend(docs_neg)\n labels = labels_pos\n labels.extend(labels_neg)\n labels = np.array(labels)\n train_data, test_data, y_train, y_test = train_test_split(docs, labels, test_size=0.33, random_state=42)\n vocab = get_vocab(train_data,test_data)\n print(\"Vocabulary Size: \", len(vocab))\n \n \n \n # Create graph-of-words representations\n G_train = create_graph_of_words(train_data, vocab, window_size) \n G_test = create_graph_of_words(test_data, vocab, window_size)\n \n # Values of C parameter of SVM\n C_grid = (10. ** np.arange(-4,6,1) / len(G_train)).tolist()\n\n # Creates pipeline\n estimator = make_pipeline(\n ShortestPath(normalize=True),\n GridSearchCV(SVC(kernel='precomputed'), dict(C=C_grid),\n scoring='accuracy', cv=10))\n\n # Performs cross-validation and computes accuracy\n n_folds = 10\n acc = accuracy_score(G_test, cross_val_predict(estimator, G_train, G_test, cv=n_folds))\n print(\"Accuracy:\", str(round(acc*100, 2)) + \"%\") \n \n\n \n\nif __name__ == \"__main__\":\n main()","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87545900","text":"from django.conf.urls import include, url, patterns\nfrom django.contrib import admin\n\nfrom Hypearave import settings\nfrom blog.views import PostListView, PostDetailView\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^search/', include('haystack.urls')),\n\n url(r'^channel/(?P<channel>\\d+)/$', PostListView.as_view(), name='channel'),\n url(r'^post/(?P<pk>\\d+)/$', PostDetailView.as_view(), name='post'),\n]\n\nif settings.DEBUG:\n # static files (social, css, javascript, etc.)\n urlpatterns += patterns('',\n (r'^media/(?P<path>.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT})\n )\n","sub_path":"Hypearave/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"160919561","text":"import socket\nfrom .Frame import Frame\nfrom .Handshake import Handshake\n\n\nclass Server:\n \"\"\"\n A simple, single threaded, web socket server.\n \"\"\"\n def __init__(self, host='localhost', port=1337):\n self._handshake = Handshake()\n self._frame = Frame()\n\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self._socket.bind((host, port))\n\n self._on_message_handler = None\n self._on_close_handler = None\n self._running = False\n self._conn = None\n self._address = None\n\n self._received_payload = ''\n\n def start(self):\n \"\"\"\n Starts the server,\n \"\"\"\n print('Start')\n self._socket.listen(1)\n self._conn, self._address = self._socket.accept()\n self._running = True\n\n data = self._conn.recv(1024)\n self._conn.sendall(self._handshake.perform(data).encode(\"utf-8\"))\n\n while self._running:\n header = self._conn.recv(24) # Max web socket header length\n\n if len(data) > 0:\n self._frame = Frame()\n\n try:\n self._frame.parse(header)\n except IndexError:\n self._running = False\n continue\n\n if self._frame.terminate:\n self._running = False\n continue\n\n data = bytearray()\n data.extend(header)\n offset = self._frame.get_payload_offset()\n data.extend(self._conn.recv(offset))\n\n if self._frame.utf8:\n request = self._frame.get_payload(data).decode(\"utf-8\")\n self._received_payload += request.lstrip('\\x00')\n\n if self._frame.utf8 and self._frame.fin:\n self._on_message_handler.on_message(self._received_payload)\n self._received_payload = ''\n\n print('Stop')\n self.stop()\n\n def send_message(self, txt):\n \"\"\"\n Sends a message if the server is in running state.\n \"\"\"\n if not self._running:\n return\n\n self._frame = Frame()\n raw_data = self._frame.create(txt)\n self._conn.send(raw_data)\n\n def stop(self):\n \"\"\"\n Stops the server by sending the fin package to the client and closing the socket.\n \"\"\"\n self._running = False\n try:\n self._conn.send(self._frame.close())\n except BrokenPipeError:\n print('Ignored BrokenPipeError')\n\n self._conn.close()\n if self._on_close_handler:\n print('Triggering on_close')\n self._on_close_handler.on_close()\n\n def on_message(self, handler):\n \"\"\"\n Sets the on message handler.\n \"\"\"\n print('Setting on message handler')\n self._on_message_handler = handler\n self._on_message_handler.set_web_socket_server(self)\n\n def on_close(self, handler):\n \"\"\"\n Sets the on connection closed handler.\n \"\"\"\n print('Setting on close handler')\n self._on_close_handler = handler\n self._on_close_handler.set_web_socket_server(self)","sub_path":"SublimeText3Plugin/WebSocket/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"555543567","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.init import kaiming_uniform\nfrom Loss import MultilabelCrossEntropyLoss\nimport torchvision.models as models\n\nclass MemoryFlowNet(nn.Module):\n\n def __init__(self, opt):\n super(MemoryFlowNet, self).__init__()\n\n self.conv1_1 = nn.Conv2d(3, 64, 3, 1, 1)\n self.bn1_1 = nn.BatchNorm2d(64)\n self.relu1_1 = nn.ReLU()\n self.conv1_2 = nn.Conv2d(64, 64, 3, 1, 1)\n self.bn1_2 = nn.BatchNorm2d(64)\n self.relu1_2 = nn.ReLU()\n self.pool1 = nn.MaxPool2d(2,2)\n # self.conv1_memory = nn.Conv2d(32*5, 32, 3, 1, 1)\n\n self.conv2_1 = nn.Conv2d(64, 128, 3, 1, 1)\n self.bn2_1 = nn.BatchNorm2d(128)\n self.relu2_1 = nn.ReLU()\n self.conv2_2 = nn.Conv2d(128, 128, 3, 1, 1)\n self.bn2_2 = nn.BatchNorm2d(128)\n self.relu2_2 = nn.ReLU()\n self.pool2 = nn.MaxPool2d(2,2)\n # self.conv2_memory = nn.Conv2d(64*5, 64, 3, 1, 1)\n\n self.conv3_1 = nn.Conv2d(128, 128, 3, 1, 1)\n self.bn3_1 = nn.BatchNorm2d(128)\n self.relu3_1 = nn.ReLU()\n self.conv3_2 = nn.Conv2d(128, 128, 3, 1, 1)\n self.bn3_2 = nn.BatchNorm2d(128)\n self.relu3_2 = nn.ReLU()\n self.conv3_3 = nn.Conv2d(128, 128, 3, 1, 1)\n self.bn3_3 = nn.BatchNorm2d(128)\n self.relu3_3 = nn.ReLU()\n self.pool3 = nn.MaxPool2d(2,2)\n self.conv3_memory = nn.Conv2d(128*5, 128, 3, 1, 1)\n self.bn3_memory = nn.BatchNorm2d(128)\n self.relu3_memory = nn.ReLU()\n\n self.conv4_1 = nn.Conv2d(256, 256, 3, 1, 1)\n self.bn4_1 = nn.BatchNorm2d(256)\n self.relu4_1 = nn.ReLU()\n self.conv4_2 = nn.Conv2d(256, 256, 3, 1, 1)\n self.bn4_2 = nn.BatchNorm2d(256)\n self.relu4_2 = nn.ReLU()\n self.conv4_3 = nn.Conv2d(256, 256, 3, 1, 1)\n self.bn4_3 = nn.BatchNorm2d(256)\n self.relu4_3 = nn.ReLU()\n self.pool4 = nn.MaxPool2d(2, 2)\n self.conv4_memory = nn.Conv2d(256 * 5, 256, 3, 1, 1)\n self.bn4_memory = nn.BatchNorm2d(256)\n self.relu4_memory = nn.ReLU()\n\n self.conv5_1 = nn.Conv2d(512, 512, 3, 1, 1)\n self.bn5_1 = nn.BatchNorm2d(512)\n self.relu5_1 = nn.ReLU()\n self.conv5_2 = nn.Conv2d(512, 512, 3, 1, 1)\n self.bn5_2 = nn.BatchNorm2d(512)\n self.relu5_2 = nn.ReLU()\n self.conv5_3 = nn.Conv2d(512, 512, 3, 1, 1)\n self.bn5_3 = nn.BatchNorm2d(512)\n self.relu5_3 = nn.ReLU()\n self.pool5 = nn.MaxPool2d(2, 2)\n self.conv5_memory = nn.Conv2d(512 * 5, 512, 3, 1, 1)\n self.bn5_memory = nn.BatchNorm2d(512)\n self.relu5_memory = nn.ReLU()\n\n self.fc1 = nn.Linear(1024*7*7, 4096)\n self.relu_fc1 = nn.ReLU()\n self.drop1 = nn.Dropout(p=0.5)\n self.fc2 = nn.Linear(4096, 4096)\n self.relu_fc2 = nn.ReLU()\n self.drop2 = nn.Dropout(p=0.5)\n self.fc3 = nn.Linear(4096, 157)\n\n self.memory = {'conv1': [torch.zeros(1, 32, 112, 112).cuda() for _ in range(5)],\n 'conv2': [torch.zeros(1, 64, 56, 56).cuda() for _ in range(5)],\n 'conv3': [torch.zeros(1, 128, 28, 28).cuda() for _ in range(5)],\n 'conv4': [torch.zeros(1, 256, 14, 14).cuda() for _ in range(5)],\n 'conv5': [torch.zeros(1, 512, 7, 7).cuda() for _ in range(5)]}\n\n self.initialize_weights()\n\n def forward(self, inputs):\n batch_size = inputs.size(0)\n seq_len = inputs.size(1)\n self.init_memory(batch_size)\n\n for i in range(seq_len):\n out = self.relu1_1(self.bn1_1(self.conv1_1(inputs[:, i])))\n out = self.relu1_2(self.bn1_2(self.conv1_2(out)))\n out = self.pool1(out)\n # memory_out = self.conv1_memory(Variable(torch.cat(self.memory['conv1'], 1)).cuda())\n # self.memory['conv1'].pop(0)\n # self.memory['conv1'].append(out.detach().data)\n # out = torch.cat([out, memory_out], 1)\n\n out = self.relu2_1(self.bn2_1(self.conv2_1(out)))\n out = self.relu2_2(self.bn2_2(self.conv2_2(out)))\n out = self.pool2(out)\n # memory_out = self.conv2_memory(Variable(torch.cat(self.memory['conv2'], 1)).cuda())\n # self.memory['conv2'].pop(0)\n # self.memory['conv2'].append(out.detach().data)\n # out = torch.cat([out, memory_out], 1)\n\n out = self.relu3_1(self.bn3_1(self.conv3_1(out)))\n out = self.relu3_2(self.bn3_2(self.conv3_2(out)))\n out = self.relu3_3(self.bn3_3(self.conv3_3(out)))\n out = self.pool3(out)\n memory = torch.cat(self.memory['conv3'], 1)\n memory_out = self.conv3_memory(Variable(memory).cuda())\n memory_out = self.relu3_memory(self.bn3_memory(memory_out))\n self.memory['conv3'].pop(0)\n self.memory['conv3'].append(out.data)\n out = torch.cat([out, memory_out], 1)\n\n out = self.relu4_1(self.bn4_1(self.conv4_1(out)))\n out = self.relu4_2(self.bn4_2(self.conv4_2(out)))\n out = self.relu4_3(self.bn4_3(self.conv4_3(out)))\n out = self.pool4(out)\n memory = torch.cat(self.memory['conv4'], 1)\n memory_out = self.conv4_memory(Variable(memory).cuda())\n memory_out = self.relu4_memory(self.bn4_memory(memory_out))\n self.memory['conv4'].pop(0)\n self.memory['conv4'].append(out.data)\n out = torch.cat([out, memory_out], 1)\n\n out = self.relu5_1(self.bn5_1(self.conv5_1(out)))\n out = self.relu5_2(self.bn5_2(self.conv5_2(out)))\n out = self.relu5_3(self.bn5_3(self.conv5_3(out)))\n out = self.pool5(out)\n memory = torch.cat(self.memory['conv5'], 1)\n memory_out = self.conv5_memory(Variable(memory).cuda())\n memory_out = self.relu5_memory(self.bn5_memory(memory_out))\n self.memory['conv5'].pop(0)\n self.memory['conv5'].append(out.data)\n out = torch.cat([out, memory_out], 1)\n\n out = out.view(-1, 1024*7*7)\n out = self.drop1(self.relu_fc1(self.fc1(out)))\n out = self.drop2(self.relu_fc2(self.fc2(out)))\n out = self.fc3(out)\n\n return out\n\n def init_memory(self, batch_size):\n self.memory = {'conv1': [torch.zeros(batch_size, 32, 112, 112).cuda() for _ in range(5)],\n 'conv2': [torch.zeros(batch_size, 64, 56, 56).cuda() for _ in range(5)],\n 'conv3': [torch.zeros(batch_size, 128, 28, 28).cuda() for _ in range(5)],\n 'conv4': [torch.zeros(batch_size, 256, 14, 14).cuda() for _ in range(5)],\n 'conv5': [torch.zeros(batch_size, 512, 7, 7).cuda() for _ in range(5)]}\n\n def _init_layer(self, layer, name):\n # for layer in layers:\n if str(layer).startswith(name):\n kaiming_uniform(layer.weight.data)\n if layer.bias is not None:\n layer.bias.data.zero_()\n\n def initialize_weights(self):\n self._init_layer(self.conv1_1, 'Conv')\n self._init_layer(self.conv1_2, 'Conv')\n # self._init_layer(self.conv1_memory, 'Conv')\n self._init_layer(self.conv2_1, 'Conv')\n self._init_layer(self.conv2_2, 'Conv')\n # self._init_layer(self.conv2_memory, 'Conv')\n self._init_layer(self.conv3_1, 'Conv')\n self._init_layer(self.conv3_2, 'Conv')\n self._init_layer(self.conv3_3, 'Conv')\n self._init_layer(self.conv3_memory, 'Conv')\n self._init_layer(self.conv4_1, 'Conv')\n self._init_layer(self.conv4_2, 'Conv')\n self._init_layer(self.conv4_3, 'Conv')\n self._init_layer(self.conv4_memory, 'Conv')\n self._init_layer(self.conv5_1, 'Conv')\n self._init_layer(self.conv5_2, 'Conv')\n self._init_layer(self.conv5_3, 'Conv')\n self._init_layer(self.conv5_memory, 'Conv')\n self._init_layer(self.fc1, 'Linear')\n self._init_layer(self.fc2, 'Linear')\n self._init_layer(self.fc3, 'Linear')\n\nif __name__ == \"__main__\":\n torch.cuda.set_device(1)\n\n model = models.vgg16_bn(pretrained=True)\n net = MemoryFlowNet({}).cuda()\n a = model.state_dict()\n for param in model.state_dict():\n print(param)\n inputs = torch.FloatTensor(16, 3, 224, 224)\n mask = torch.randn(16, 157)\n targets = mask.ge(0.5)\n res = net(Variable(inputs).cuda())\n crit = MultilabelCrossEntropyLoss().cuda()\n\n loss = crit(res, Variable(targets.float()).cuda())\n\n\n print(res)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529493565","text":"import serial\nfrom . import constants\ndef connection(ipaddress,port):\n\tserport = serial.serial_for_url(\"socket://\"+ipaddress+\":\"+port+\"/logging=debug\")\n\tserport.close()\n\t#serport.port = constants.COM_PORT\n\tserport.baudrate = constants.COM_BAUD\n\tserport.bytesize = constants.COM_SIZE\n\tserport.parity = constants.COM_PARITY\n\tserport.stopbits = constants.COM_STOP\n\tserport.timeout = constants.COM_TIMEOUT\n\ttry:\n\t serport.open()\n\texcept serial.SerialException as e:\n\t s= \"%s : Could not open serial port %s: %s\\n\" % (localtime, serport.portstr, e)\n\t sys.stderr.write(s)\n\t problem += 1\n\tserport.close()\n\treturn serport\n","sub_path":"build/lib/heatmiserV3/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"73147847","text":"import threading\nimport socket\nimport json\nimport numpy as np\nimport utils\nimport requests\nimport base64\nimport hashlib\nimport struct\n\n'''\nPython处理前端javascript发来的数据解码和编码参考以下内容,针对其中BUG有修改\nhttps://blog.csdn.net/ice110956/article/details/34118203\n'''\n#支持的API类型,如果token不在list中则认为无效\nAPI_Surport_List = ['SR']\nues_tf_serving = False\ntf_serving_url = 'http://localhost:8501/v1/models/{}:predict'\nif not ues_tf_serving:\n\tyysb = utils.SpeechRecognition(test_flag=False)\n\n\ndef SR_recognize(wavs,pre_type):\n hanzi =''\n am_url = tf_serving_url.format('am')\n lm_url = tf_serving_url.format('lm')\n if ues_tf_serving:\n x,_,_ = utils.get_wav_Feature(wavsignal=wavs)\n try:\n receipt = requests.post(am_url,data='{\"instances\":%s}' % x.tolist()).json()['predictions'][0]\n receipt = np.array([receipt],dtype=np.float32)\n except:\n return _,'声学模型调用异常'\n _, pinyin = utils.decode_ctc(receipt, utils.pny_vocab)\n pinyin = [[utils.pny_vocab.index(p) for p in ' '.join(pinyin).strip('\\n').split(' ')]]\n if pre_type == 'H':\n #curl -d '{\"instances\": [[420,58]]}' -X POST http://localhost:8501/v1/models/lm:predict\n try:\n hanzi = requests.post(lm_url,data='{\"instances\": %s}' % pinyin).json()['predictions'][0]\n except:\n return _,'语言模型调用异常'\n hanzi = ''.join(utils.han_vocab[idx] for idx in hanzi)\n else:\n if pre_type == 'H':\n pinyin,hanzi = yysb.predict(wavs)\n else:\n pinyin = yysb.predict(wavs,only_pinyin = True)\n return pinyin,hanzi\n\n\ndef encode_data(data):\n data = data.encode('utf-8')\n token = b\"\\x81\"\n length = len(data)\n if length < 126:\n token += struct.pack(\"B\", length)\n elif length <= 0xFFFF:\n token += struct.pack(\"!BH\", 126, length)\n else:\n token += struct.pack(\"!BQ\", 127, length)\n #struct为Python中处理二进制数的模块,二进制流为C,或网络流的形式。\n data = token + data\n return data\n\n\ndef tcplink(sock, addr):\n print('Accept new connection from %s:%s...' % addr)\n js_flag = False\n js_saver = b''#防止数据过长时单次接收不全\n while True:\n all_data = sock.recv(524288)\n if not all_data:\n break\n js_saver += all_data\n all_data = js_saver#all_data从js_saver处获取目前为止的全部数据\n try:\n datas = all_data.decode('utf-8')\n except:#处理前端js发来的websocket数据,还要进行解码处理\n js_flag = True\n code_len = all_data[1] & 127\n if code_len == 126:\n masks = all_data[4:8]\n all_data = all_data[8:]\n elif code_len == 127:\n masks = all_data[10:14]\n all_data = all_data[14:]\n else:\n masks = all_data[2:6]\n all_data = all_data[6:]\n datas = \"\"\n for i,d in enumerate(all_data):\n datas += chr(d ^ masks[i % 4])\n try:\n if datas.find('token') < 0 or datas.find('pre_type') < 0:\n continue\n datas = json.loads(datas)\n js_saver = b''\n except BaseException as e:\n print(e)\n continue\n token = datas['token']\n pre_type = datas['pre_type']\n receipt_data = list(datas['data'])\n \n if(token not in API_Surport_List):\n sock.send(b'token unsupported')\n\t\t\n if len(receipt_data)>0:\n if token == 'SR':\n wavs = np.array([int(w) for w in receipt_data])\n _,r = SR_recognize(wavs, pre_type)\n else:\n pass\n else:\n r = ''\n \n if js_flag:\n r = encode_data(r)\n else:\n r = r.encode('utf-8')\n sock.send(r)\n sock.close()\n print('Connection from %s:%s closed.\\n' % addr)\n\n\nif __name__ == \"__main__\":\n IPs = socket.gethostbyname_ex(socket.gethostname())[-1]\n # family=AF_INET - IPv4地址\n # family=AF_INET6 - IPv6地址\n # type=SOCK_STREAM - TCP套接字\n # type=SOCK_DGRAM - UDP套接字\n # type=SOCK_RAW - 原始套接字 \n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 监听端口:\n s.bind(('172.16.100.29', 9999))\n s.listen(255)# 参数255可以理解为连接队列的大小\n while True:\n # 接受一个新连接:\n # accept方法是一个阻塞方法如果没有客户端连接到服务器代码不会向下执行\n client, addr = s.accept()\n data = str(client.recv(1024))\n header_dict = {}\n header, _ = data.split(r'\\r\\n\\r\\n', 1)\n for line in header.split(r'\\r\\n')[1:]:\n key, val = line.split(': ', 1)\n header_dict[key] = val\n\n if 'Sec-WebSocket-Key' not in header_dict:\n print('This socket is not websocket, client close.')\n client.close()\n continue\n\n magic_key = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n sec_key = header_dict['Sec-WebSocket-Key'] + magic_key\n key = base64.b64encode(hashlib.sha1(bytes(sec_key, encoding='utf-8')).digest())\n key_str = str(key)[2:30]\n\n response = 'HTTP/1.1 101 Switching Protocols\\r\\n' \\\n 'Connection: Upgrade\\r\\n' \\\n 'Upgrade: websocket\\r\\n' \\\n 'Sec-WebSocket-Accept: {0}\\r\\n' \\\n 'WebSocket-Protocol: chat\\r\\n\\r\\n'.format(key_str)\n client.send(bytes(response, encoding='utf-8'))#针对普通js建立的websocket一定要回一个建立连接\n # 创建新线程来处理TCP连接:\n t = threading.Thread(target=tcplink, args=(client, addr))\n t.start()\n","sub_path":"AboutDL/语音识别ASRT/service_socket.py","file_name":"service_socket.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"259844400","text":"# Задача 5. Вариант 11.\n#Напишите программу, которая бы при запуске случайным образом отображала имя одного из девяти оленей Санта Клауса. \n \n# Kurchatov N. V.\n# 11.04.2016\n\nimport random\nx=random.randint(1,9)\nif x==1:\n\tname=\"Дэшер\"\nelif x==2:\n\tname = \"Дэнсер\"\nelif x==3:\n\tname = \"Прэнсер\"\nelif x==4:\n\tname = \"Виксен\"\nelif x==5:\n\tname = \"Комет\"\nelif x==6:\n\tname = \"Кь��пид\"\nelif x==7:\n\tname = \"Дондер\"\nelif x==8:\n\tname = \"Блитцен\"\nelif x==9:\n\tname = \"Рудольф\"\t\n\t\nprint (\"Имя одного из оленей Санты - \"+name)\ninput(\"Нажмите Enter для выхода\")","sub_path":"INBa/2015/KURCHATOV_N_V/z5_11.py","file_name":"z5_11.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"441813869","text":"import os\n\nimport numpy as np\nfrom preprocessing.cropper import Cropper\n\n\n\nclass TrainTestSampleGen(object):\n\n def __init__(self, ucf_path, hmdb_path):\n if ucf_path != '':\n self.train_data_label, self.test_data_label = self.ucf_read_train_test_split(ucf_path)\n if hmdb_path != '':\n self.train_data_label, self.test_data_label = self.hmdb_read_train_test_split(hmdb_path)\n\n def ucf_read_train_test_split(self, path):\n \"\"\"\n Read the name of train and test samples from the txt files which are stored under path, split them into train,\n test lists.\n :param path: The path of folder stores the train test split txt files\n :return: two lists of dict, train and test which contain the video name and labels for train and test.\n \"\"\"\n # get the test train split txt file\n train = []\n test = []\n for (dirpath, dirnames, filenames) in os.walk(path):\n train += [os.path.join(path, file) for file in filenames if file.startswith('trainlist')]\n test += [os.path.join(path, file) for file in filenames if file.startswith('testlist')]\n train.sort()\n test.sort()\n\n # read test train data name and label from the txt file\n train_data_labels = []\n test_data_labels = []\n for tra, test in zip(train, test):\n with open(tra) as f:\n names_labels = f.readlines()\n data = [line.split(' ')[0].split('/')[-1].split('.')[0] for line in names_labels]\n label = [line.split(' ')[0].split('/')[0] for line in names_labels]\n train_data_labels.append({'data': data, 'label': label})\n with open(test) as f:\n names_labels = f.readlines()\n data = [line.split('/')[-1].split('.')[0] for line in names_labels]\n label = [line.split('/')[0] for line in names_labels]\n test_data_labels.append({'data': data, 'label': label})\n return train_data_labels, test_data_labels\n\n def train_test_split(self, path, dataset, idx, crop=False):\n \"\"\"\n Read the data that names are given in self.ucf_train_data_labels and self.ucf_test_data_labels.\n Save the data and label into a dict. Each time this function is called, only read one train or test split.\n :param path: feature store path\n :param dataset: ucf or hmdb\n :return: the dicts with the format {'data': data, 'label': labels}\n \"\"\"\n if dataset == 'ucf':\n train_data_label = self.ucf_train_data_label[idx].copy()\n test_data_label = self.ucf_test_data_label[idx].copy()\n else:\n train_data_label = self.hmdb_train_data_label[idx].copy()\n test_data_label = self.hmdb_test_data_label[idx].copy()\n\n if crop == True:\n train_data = [Cropper(np.load(os.path.join(path, name + '.npy')), (224, 224)).crop_image() for name in\n train_data_label['data']]\n test_data = [Cropper(np.load(os.path.join(path, name + '.npy')), (224, 224)).crop_image() for name in\n test_data_label['data']]\n else:\n train_data = [np.load(os.path.join(path, name + '.npy')) for name in train_data_label['data']]\n test_data = [np.load(os.path.join(path, name + '.npy')) for name in test_data_label['data']]\n\n train_data_label['data'] = train_data\n test_data_label['data'] = test_data\n return train_data_label, test_data_label\n\n def hmdb_read_train_test_split(self, path):\n \"\"\"\n Read the name of train and test samples from the txt files which are stored under path, split them into train,\n test lists.\n :param path: The path of folder stores the train test split txt files\n :return: two lists of dict, train and test which contain the video name and labels for train and test.\n \"\"\"\n # read file names according to the split number from 1 to 3\n action_splits = []\n for (dirpath, dirnames, filenames) in os.walk(path):\n for i in range(1, 4, 1):\n action_splits.append(\n sorted([os.path.join(path, f) for f in filenames if f.split('.')[0].endswith(str(i))]))\n\n # fetch the data and labels for all 3 splits\n train_data_labels = []\n test_data_labels = []\n for s in action_splits:\n train_data = []\n train_label = []\n test_data = []\n test_label = []\n for a in s:\n with open(a) as f:\n name_labels = f.readlines()\n train = [line.split(' ')[0].split('.')[0] for line in name_labels if\n line.rstrip().split(' ')[-1] == '1']\n train_data += train\n train_label += [a.split('/')[-1][:a.split('/')[-1].index('test')-1] for i in range(len(train))]\n test = [line.split(' ')[0].split('.')[0] for line in name_labels if\n line.rstrip().split(' ')[-1] == '2']\n test_data += test\n test_label += [a.split('/')[-1][:a.split('/')[-1].index('test')-1] for i in range(len(test))]\n train_data_labels.append({'data': train_data, 'label': np.array(train_label)})\n test_data_labels.append({'data': test_data, 'label': np.array(test_label)})\n return train_data_labels, test_data_labels\n\nif __name__ == '__main__':\n ucf_path = \"/home/boy2/UCF101/ucf101_dataset/features/testTrainSplits\"\n hmdb_path = \"/home/boy2/UCF101/hmdb51_dataset/features/testTrainSplits\"\n tts = TrainTestSampleGen(ucf_path, hmdb_path)\n tts.hmdb_read_train_test_split(hmdb_path)\n","sub_path":"src/trainTestSamplesGen.py","file_name":"trainTestSamplesGen.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"409279987","text":"#!/usr/bin/env python3\r\n\r\nimport os\r\n\r\nreplacechars = {\r\n '_':'-'\r\n}\r\n\r\nfilelist = os.listdir()\r\nfor file in filelist:\r\n if os.path.isdir(file):\r\n continue\r\n a = list(file)\r\n for i,val in enumerate(a):\r\n if replacechars.get(val):\r\n a[i]=replacechars[val]\r\n b = ''.join(a)\r\n if file!=b:\r\n os.rename(file,b)\r\n print(b)","sub_path":"others/filereplacechar.py","file_name":"filereplacechar.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"114113470","text":"import pyaudio\nimport numpy as np\nimport wave\nimport matplotlib.pyplot as plt\n\np = pyaudio.PyAudio()\nfreqs=np.array([0])\np.get_default_input_device_info()\nstream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=2048)\nframes = []\nRECORD_SECONDS = 30\nnchunks = int(RECORD_SECONDS * 44100 / 2048)\nfor i in range(0, nchunks):\n try:\n data = stream.read(2048)\n except IOError as ex: #error que ens dona (Input Overflowed)\n if ex[1] != pyaudio.paInputOverflowed:\n raise\n data = '\\x00' * 2048\n frames.append(data)\n swidth = 2\n chunk = 2048\n window = np.blackman(chunk)\n indata = np.array(wave.struct.unpack(\"%dh\"%(len(data)/swidth),\\\n data))*window\n # S'agafen els valors de la FFT i s'eleven al quadrat\n fftData=abs(np.fft.rfft(indata))**2\n # es troba el màxim\n which = fftData[1:].argmax() + 1\n # s'utilitza la interpolació quadràtica al màxim\n if which != len(fftData)-1:\n y0,y1,y2 = np.log(fftData[which-1:which+2:])\n x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)\n # es troba la freqüència\n thefreq = (which+x1)*44100/chunk\n else:\n thefreq = which*44100/chunk\n if 100<=thefreq<=10000:\n #print ('La freqüència és de %f Hz.' % (thefreq))\n print (thefreq)\n #plt.plot(i,thefreq,\"ro\")\n freqs=np.insert(freqs, -1, float(thefreq))\n freqs_t=np.insert(freqs, -1, (i, float(thefreq)))\n a, b = freqs[-1], freqs[-2]\n freqs[-1], freqs[-2] = b, a\n#plt.show()\n","sub_path":"Antics/direct_red.py","file_name":"direct_red.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"4001623","text":"import pandas as pd\nfrom bokeh.charts import Bar, output_file, show\nfrom bokeh.layouts import column\nfrom bokeh.models import (HoverTool, BoxSelectTool, BoxZoomTool, ResetTool,\n PanTool, WheelZoomTool, ResizeTool)\n\n\nclass AlignViz2(object):\n\n def alignment_stats(self, input_path_file, output_path_file_csv,\n output_path_file_html):\n df = pd.read_json(input_path_file, orient='index')\n df.to_csv(output_path_file_csv + '.csv',\n index=True, sep='\\t')\n\n samples = []\n alignment_length = []\n alignment_freq = []\n for index, row in df.iterrows():\n for key, value in row['stats_per_reference'].items():\n samples.extend([\n index + '(' + key + ')'] * int(self.nr_items_align(value)))\n for k, v in value.items():\n if k == 'alignment_length_and_freqs':\n for keys, values in v.items():\n alignment_length.extend([float(keys)])\n alignment_freq.extend([values])\n\n data1 = {}\n data1['samples'] = samples\n data1['aligned read length'] = alignment_length\n data1['frequency'] = alignment_freq\n\n bar1 = Bar(\n data1, values='frequency', label='aligned read length',\n stack='samples', agg='sum',\n title=\"Alignment read length and frequency\",\n legend='top_left', width=1200, bar_width=1.0,\n palette=['Blue', 'Aqua', 'SeaGreen', 'SpringGreen', 'Brown',\n 'Peru', 'Purple', 'Violet'],\n tools=[\n HoverTool(tooltips=[(\n \"Read length\", \"@x\"), (\"Frequency\", \"@y\")]),\n PanTool(), BoxSelectTool(), BoxZoomTool(),\n WheelZoomTool(), ResizeTool(), ResetTool()])\n\n output_file(output_path_file_html + '.html')\n show(bar1)\n \n def nr_items_align(self, value):\n item_nr_align = []\n for k, v in value.items():\n if k == 'alignment_length_and_freqs':\n for keys, values in v.items():\n item_nr_align.extend([keys])\n return(len(item_nr_align))\n\n def process_stats(self, input_path_file, output_path_file_csv,\n output_path_file_html):\n df = pd.read_json(input_path_file, orient='index')\n df.to_csv(output_path_file_csv + '.csv', index=True, sep='\\t')\n\n # plotting read processing(poly/single A removed or unmodified)\n conditions = []\n for row in df.iterrows():\n conditions.extend([\n 'poly(A) removed', 'single(A) removed', 'unmodified'])\n\n samples1 = []\n for index, row in df.iterrows():\n samples1.extend([index] * 3)\n\n read_nr = []\n for index, row in df.iterrows():\n read_nr.extend([\n row['polya_removed'], row['single_a_removed'],\n row['unmodified']])\n\n data1 = {}\n data1['condition'] = conditions\n data1['sample'] = samples1\n data1['Nr. of reads'] = read_nr\n\n bar1 = Bar(\n data1, values='Nr. of reads', label='sample',\n stack='condition',\n agg='sum', title=\"Input read types\", legend='top_right',\n palette=['darkseagreen', 'salmon', 'darkslateblue'],\n tools=[\n HoverTool(tooltips=[(\n \"Sample\", \"@x\"), (\"Nr of reads\", \"@y\")]),\n PanTool(), BoxSelectTool(), BoxZoomTool(),\n WheelZoomTool(), ResizeTool(), ResetTool()])\n\n samples2 = []\n read_length = []\n frequency = []\n for index, row in df.iterrows():\n for key, value in row[\n 'read_length_after_processing_and_freq'].items():\n samples2.extend([index] * int(self.nr_items_pro(key)))\n read_length.extend([float(key)])\n frequency.extend([value])\n\n data2 = {}\n data2['samples'] = samples2\n data2['read length'] = read_length\n data2['frequency'] = frequency\n\n bar2 = Bar(\n data2, values='frequency', label='read length',\n stack='samples', agg='sum',\n title=\"Input read length and frequency\",\n legend='top_left', palette=[\n 'darkseagreen', 'salmon', 'darkslateblue', 'olive'],\n width=1200, bar_width=1.0,\n tools=[\n HoverTool(tooltips=[(\n \"Read length\", \"@x\"), (\"Frequency\", \"@y\")]),\n PanTool(), BoxSelectTool(), BoxZoomTool(),\n WheelZoomTool(), ResizeTool(), ResetTool()])\n\n bar = column(bar1, bar2)\n output_file(output_path_file_html + '.html')\n show(bar)\n \n def nr_items_pro(self, key):\n item_nr_pro = []\n item_nr_pro.extend([key])\n return(len(item_nr_pro))\n \n\n","sub_path":"reademptionlib/vizalign2.py","file_name":"vizalign2.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"138620393","text":"\n# %%\nimport pymongo\nimport keyring\nimport pandas as pd\nimport requests\nimport pyocr\nfrom pdf2image import convert_from_path\nimport sys\nfrom pathlib import Path\n\n\n#%%\nclass MongoClient:\n def __init__(self):\n self.conn = pymongo.MongoClient(keyring.get_password('sentencias-db', 'default'))\n self.db = self.conn.sentencias\n self.collection = self.db.sentencia\n \n def query(self, query:dict = {}):\n ''' Regresa un dataframe a partir de una consulta de mongo.\n args:\n query: Diccionario con filtros de la consulta.\n returns:\n Dataframe de la consulta.\n '''\n docs = []\n cursor = self.collection.find(query)\n for doc in cursor:\n docs.append(doc)\n data = pd.DataFrame.from_dict(docs)\n return data\n\nclass Pdf2Text(MongoClient):\n def __init__(self, input_path = Path(), output_path = Path()):\n self.input_path = input_path\n self.output_path = pyocr.get_available_tools()\n tools = pyocr.get_available_tools()\n if len(tools) == 0:\n print(\"No OCR tool found\")\n sys.exit(1)\n self.tool = tools[0]\n self.lang = 'spa'\n\n def pdf2string(self, pdf_path):\n ''' Usando el path de un archivo pdf extraemos el texto mediante OCR de Tesseract.'''\n images = self.pdf2img(pdf_path) \n txt = ''\n for img in enumerate(images):\n txt += self.img2string(img)\n\n def img2string(self, img):\n ''' Usando una imagen de un pdf, regresa la cadena de strings contenida en la misma.'''\n txt = self.tool.image_to_string(img, lang=self.lang, builder=pyocr.builders.TextBuilder())\n return txt\n\n def pdf2img(self, pdf_path):\n ''' Convierte paginas de un pdf en imagenes.'''\n return convert_from_path(pdf_path)\n\n\n#%%\nif __name__ == '__main__':\n txts = []\n client = MongoClient()\n data = client.query()\n converter = Pdf2Text()\n temp_path = Path('temp.pdf')\n for pdf_link in data['pdf links']:\n response = requests.get(pdf_link)\n with open(temp_path, 'wb') as out:\n out.write(response.content)\n txt = converter.pdf2string(temp_path)\n txts.append(txt)\n\n\n\n\n\n","sub_path":"lib/MongoClient.py","file_name":"MongoClient.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"145778373","text":"import cv2\nimport numpy as np\nimport imutils\n# import pytesseract\nfrom collections import Counter\nfrom pandas import DataFrame as df\nPATH_CROPPED = './cropped/'\nPATH_OTHERS = 'D:/python/others/'\nPATH = PATH_OTHERS\n'''水平投影'''\n\n\ndef getHProjection(image):\n hProjection = np.zeros(image.shape, np.uint8)\n print('------1-------')\n # 图片高与宽\n (h, w) = image.shape\n print(h, w)\n # 长度与图像高度一致的数组\n h_ = [0] * h\n # 循环统计每一行白色像素的个数\n for y in range(h):\n for x in range(w):\n if image[y, x] == 255:\n h_[y] += 1\n\n # 绘制水平投影图像\n for y in range(h):\n for x in range(h_[y]):\n hProjection[y, x] = 255\n\n\n # cv2.imshow('hProjection2', hProjection)\n # cv2.waitKey(0)\n\n return h_\n\n\ndef getVProjection(image):\n vProjection = np.zeros(image.shape, np.uint8)\n (h, w) = image.shape\n\n w_ = [0] * w\n\n for x in range(w):\n for y in range(h):\n if image[y, x] == 255:\n w_[x] += 1\n\n for x in range(w):\n for y in range(h - w_[x], h):\n vProjection[y, x] = 255\n\n # cv2.imshow('vProjection', vProjection)\n cv2.waitKey(0)\n return w_\n\n\ndef fill_color(img, seedpoint):\n copyimg = img.copy()\n h, w = img.shape[:2]\n mask = np.zeros([h + 2, w + 2], np.uint8)\n mask[seedpoint[0]:seedpoint[2], seedpoint[1]:seedpoint[3]] = 0\n cv2.floodFill(copyimg, mask, (seedpoint[0] + 1, seedpoint[1] + 1), (0, 255, 255),\n flags=cv2.FLOODFILL_MASK_ONLY)\n # cv2.imshow('fill_color',copyimg)\n\n\ndef modify_position(w, threshold=6):\n t = get_threshold(w, threshold)\n w_counter = Counter(w)\n weight = []\n for i in t:\n \tweight.append(w_counter[i])\n\n m_mean = int(np.average(tuple(t), weights=weight))\n print(m_mean)\n # m_mean = sum(t)//len(t)\n m_max = max(t)\n w_ = []\n for item in w:\n if item < m_max and item > 0:\n w_.append(m_mean)\n # elif item < m_max:\n # w_.append(m_mean)\n else:\n \tw_.append(item)\n return w_, m_mean\n\n\ndef get_threshold(w, threshold=6):\n\tw_ = [0 if item < 2 else item for item in w]\n\tt = sorted(list(set(w_)))[1:threshold]\n\treturn t\n\n\ndef main(file):\n\torigineImage = cv2.imread(file)\n\tprint(file)\n\t# cv2.imshow('begin', origineImage)\n\torigineImage = imutils.resize(origineImage, width=1280)\n\t# 图片灰度化\n\timg = cv2.cvtColor(origineImage, cv2.COLOR_RGB2GRAY)\n # cv2.imshow('gray', img)\n # 二值化\n\tretval, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n\t# cv2.imshow('binary', img)\n\tcv2.waitKey(0)\n # img = cv2.GaussianBlur(img,(3,3),0)\n # img = cv2.blur(img,(3,3))\n # img = cv2.medianBlur(img,5)\n # img = cv2.bilateralFilter(img,9,75,75)\n # cv2.imshow('Gauss',img)\n \n\n # contours, hierarchy = cv2.findContours(img,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)\n # cv2.imshow('contours',img)\n # kernel = np.ones((3, 3), np.uint8)\n # img = cv2.erode(img, kernel)\n # cv2.imshow('eroimg',img)\n # for i in range(len(contours)):\n # \tcv2.drawContours(img,contours,i,(0,255,255),3)\n # \tcv2.fillPoly(img,[contours[i]],(255,255,0))\n # cv2.imshow('fill',img)\n # print(type(contours),contours)\n # print(file)\n\t(h, w) = img.shape\n\tPosition = []\n # 水平投影\n\tH = getHProjection(img)\n\t# print(H)\n\tstart = 0\n\tH_Start = []\n\tH_End = []\n # 根据水平投影获取垂直分割位置\n\tfor i in range(len(H)):\n\t if H[i] > 0 and start == 0:\n\t H_Start.append(i)\n\t start = 1\n\t if H[i] <= 0 and start == 1:\n\t H_End.append(i)\n\t start = 0\n # 分割行,分割之后再进行列分割列并保存分割位置\n\t# print(H_Start)\n\t# print(H_End)\n\tfor i in range(len(H_Start)):\n\t # 获取行图像\n\t cropImg = img[H_Start[i]:H_End[i], 0:w]\n\t # cv2.imshow('cropImg', cropImg)\n\t # 对行图像进行垂直投影\n\t W = getVProjection(cropImg)\n\t # print(W)\n\t threshold = 10\n\t W, mean = modify_position(W, threshold)\n\t # print(W)\n\t WStart = 0\n\t WEnd = 0\n\t W_Start = 0\n\t W_End = 0\n\t for j in range(len(W)):\n\t if W[j] > mean and WStart == 0:\n\t W_Start = j\n\t WStart = 1\n\t WEnd = 0\n\t if (j >= w-1 and WStart == 1) or (W[j] <=0 and WStart == 1):\n\t W_End = j\n\t WStart = 0\n\t WEnd = 1\n\t if WEnd == 1:\n\t Position.append([W_Start, H_Start[i], W_End, H_End[i]])\n\t WEnd = 0\n\n\t# new_Position = modify_position(Position)\n\t# print(Position)\n\tfor m in range(len(Position)):\n\t cv2.rectangle(origineImage, (Position[m][0], Position[m][1]),\n\t (Position[m][2], Position[m][3]), (0, 229, 238), 1)\n\t # fill_color(origineImage,Position[m])\n\n\tcv2.imshow('image', origineImage)\n\tcv2.waitKey(0)\n\treturn Position\n\n\nif __name__ == '__main__':\n\timport os\n\ttotal_position = {}\n\tfor i, file in enumerate(os.listdir(PATH)):\n\t # print(file)\n\t position = []\n\t if file.split('.')[1] == 'png':\n\t position = main(PATH+file)\n\t total_position[file] = position\n\t # if i > 25:\n\t # break\n\timport json\n\twith open('total_position.json', 'w') as f:\n\t json.dump(total_position, f, ensure_ascii=False, indent=2)\n\t# main(PATH+'20200308120114_1.jpg')\n","sub_path":"cropimage.py","file_name":"cropimage.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"544121678","text":"import argo.interaction\nfrom argo.interaction import HasProtocolState\n\nfrom typing import Any, List\n\nclass CryptolStartSetup(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, name : str) -> None:\n super(CryptolStartSetup, self).__init__(\n 'SAW/Cryptol/start setup',\n {'name': name},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass CryptolLoadFile(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, filename : str) -> None:\n super(CryptolLoadFile, self).__init__(\n 'SAW/Cryptol/load file',\n {'file': filename},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass CryptolLoadModule(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, module_name : str) -> None:\n super(CryptolLoadModule, self).__init__(\n 'SAW/Cryptol/load module',\n {'module': module_name},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass CryptolFinishSetup(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState) -> None:\n super(CryptolFinishSetup, self).__init__(\n 'SAW/Cryptol/finish setup',\n {},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMStartSetup(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, name : str) -> None:\n super(LLVMStartSetup, self).__init__(\n 'SAW/LLVM/start setup',\n {'name': name},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMFinishSetup(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState) -> None:\n super(LLVMFinishSetup, self).__init__('SAW/LLVM/finish setup', {}, connection)\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMLoadModule(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState,\n name : str,\n bitcode_file : str) -> None:\n super(LLVMLoadModule, self).__init__(\n 'SAW/LLVM/load module',\n {'name': name, 'bitcode file': bitcode_file},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMReturn(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, return_value : Any) -> None:\n super(LLVMReturn, self).__init__('SAW/LLVM/return', {'value': return_value}, connection)\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMVerify(argo.interaction.Command):\n def __init__(\n self,\n connection : HasProtocolState,\n module : str,\n function : str,\n lemmas : List[str],\n check_sat : bool,\n setup : str,\n tactic : str,\n lemma_name : str) -> None:\n params = {'module': module,\n 'function': function,\n 'lemmas': lemmas,\n 'check sat': check_sat,\n 'setup': setup,\n 'tactic': tactic,\n 'lemma name': lemma_name}\n super(LLVMVerify, self).__init__('SAW/LLVM/verify', params, connection)\n\n def process_result(self, _res : Any) -> Any:\n return None\n","sub_path":"python/saw/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"169526097","text":"phrase = input(\"Give me a phrase\\n\")\n\ndef create_thesaurus(filename):\n fread = open(filename, 'r')\n thesaurus = {}\n for line in fread:\n line = line.strip() #Gives back a new string without the \\n at the end\n line_parts = line.split(',')\n key = line_parts[0]\n value = line_parts[1:]\n thesaurus[key] = value\n return thesaurus\n\ndef removing_punctuation(phrase):\n new_string = \"\"\n for character in phrase:\n if character.isalpha() == False and character.isnumeric() == False and character.isspace() == False:\n continue\n else:\n new_string += character\n return new_string\n\ndef substituting_words(phrase, filename):\n import random\n thesaurus = create_thesaurus(filename)\n phrase_minus_punctuation = removing_punctuation(phrase)\n word_list = phrase_minus_punctuation.split(' ')\n new_phrase = []\n for word in word_list:\n key = word.lower()\n if key in thesaurus:\n list_of_synonyms = thesaurus[key]\n random_word = random.choice(list_of_synonyms)\n new_phrase.append(random_word.upper())\n else:\n new_phrase.append(word)\n new_string = ' '.join(new_phrase)\n return new_string\n \n \nprint(substituting_words(phrase, 'thesaurus.txt'))\n","sub_path":"Python/Class 10/lousy_plasma2.py","file_name":"lousy_plasma2.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"172645216","text":"import requests\nimport sqlite3\nimport datetime\nimport random\nimport json\ndb = '__HOME__/team29/commands.db'\nauthorized_users = ['ch3nj']\n\ncommands = {0: 'forward', 1: 'back', 2: 'left', 3: 'right'}\n\ndef request_handler(request):\n random.seed()\n if request['method'] == 'GET':\n values = request['values']\n if values['type'] == 'command':\n conn = sqlite3.connect(db)\n c = conn.cursor()\n out = None\n try:\n c.execute('''CREATE TABLE command_table (command int, timing timestamp);''')\n out = \"database constructed\"\n except:\n recent = datetime.datetime.now()- datetime.timedelta(seconds = 15)\n recent_commands = c.execute('''SELECT * FROM command_table WHERE timing > ? ORDER BY timing DESC''',(recent,)).fetchall()\n if len(recent_commands) == 0:\n out = 'stop'\n else:\n out = commands[recent_commands[random.randint(0, len(recent_commands)-1)][0]]\n conn.commit()\n conn.close()\n return out\n if values['type'] == 'graph':\n conn = sqlite3.connect(db)\n c = conn.cursor()\n out = []\n recent = datetime.datetime.now()- datetime.timedelta(seconds = 15)\n for num in commands:\n out.append({'command': commands[num], 'amount': len(c.execute('''SELECT * FROM command_table WHERE command = ? AND timing > ? ORDER BY timing DESC''',(num, recent)).fetchall())})\n conn.close()\n return json.dumps(out)\n\n elif request['method'] == 'POST':\n conn = sqlite3.connect(db)\n c = conn.cursor()\n command = request['form']['command']\n c.execute('''INSERT into command_table VALUES (?,?)''',(command, datetime.datetime.now())).fetchall()\n conn.commit()\n conn.close()\n return \"done\"\n","sub_path":"server/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"103958815","text":"# Copyright 2016 The Pixeldp Authors. 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# Based on https://github.com/tensorflow/models/tree/master/research/resnet\n\n\"\"\"ResNet Train/Eval module.\n\"\"\"\nimport time\nimport six\nimport sys\nimport os\nimport json\n\nimport cifar_input\nimport numpy as np\nimport pixeldp_resnet_conv1\nimport pixeldp_resnet_img_noise\nimport pixeldp_cnn_conv1\n# import pixeldp_resnet_img_noise\nimport tensorflow as tf\n\nimport utils\n\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_string('dataset', 'cifar10', 'cifar10 or cifar100.')\ntf.app.flags.DEFINE_string('mode', 'train', 'train or eval.')\n# Download CIFAR10 or CIFAR100 from:\n# e.g. https://www.cs.toronto.edu/~kriz/cifar-100-binary.tar.gz\ntf.app.flags.DEFINE_string('train_data_path',\n '/home/mathias/data/cifar10_data/cifar-10-batches-bin/data_batch*',\n 'Filepattern for training data.')\ntf.app.flags.DEFINE_string('eval_data_path',\n '/home/mathias/data/cifar10_data/cifar-10-batches-bin/test_batch*',\n 'Filepattern for eval data')\ntf.app.flags.DEFINE_string('model_dir', 'model',\n 'Directory to keep training outputs.')\ntf.app.flags.DEFINE_integer('eval_data_size', 5000,\n 'Size of test set to eval on.')\ntf.app.flags.DEFINE_integer('max_steps', 60000,\n 'Max number of steps for training a model.')\ntf.app.flags.DEFINE_string('data_dir', 'data',\n 'Directory to keep the checkpoints. Should be a '\n 'parent directory of FLAGS.model_dir.')\ntf.app.flags.DEFINE_integer('num_gpus', 1,\n 'Number of gpus used for training. (0 or 1)')\n\ndef evaluate(hps, model, dir_name=None, rerun=False):\n \"\"\"Evaluate the ResNet and log prediction counters to compute\n sensitivity.\"\"\"\n if dir_name == None:\n dir_name = FLAGS.data_dir + \"/\" + FLAGS.model_dir\n\n if os.path.isfile(dir_name + \"/eval_data.json\") and not rerun:\n # run only new models\n return\n\n if FLAGS.dataset == 'mnist':\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n dataset = mnist.test\n images = tf.placeholder(tf.float32,\n [hps.batch_size, 784],\n name='x-input')\n labels = tf.placeholder(tf.int64,\n [hps.batch_size],\n name='y-input')\n elif FLAGS.dataset == 'cifar10' or FLAGS.dataset == 'cifar100':\n images, labels = cifar_input.build_input(\n FLAGS.dataset,\n FLAGS.eval_data_path,\n hps.batch_size,\n hps.image_standardization,\n FLAGS.mode\n )\n model = model.Model(hps, images, labels, FLAGS.mode)\n model.build_graph()\n saver = tf.train.Saver()\n summary_writer = tf.summary.FileWriter(dir_name)\n\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\n tf.train.start_queue_runners(sess)\n\n best_precision = 0.0\n try:\n ckpt_state = tf.train.get_checkpoint_state(dir_name)\n except tf.errors.OutOfRangeError as e:\n tf.logging.error('Cannot restore checkpoint: %s', e)\n\n tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)\n saver.restore(sess, ckpt_state.model_checkpoint_path)\n\n # Make predictions on the dataset, keep the label distribution\n data = {\n 'predictions': [],\n 'pred_truth': [],\n }\n total_prediction, correct_prediction = 0, 0\n eval_data_size = FLAGS.eval_data_size\n eval_batch_size = hps.batch_size\n eval_batch_count = int(eval_data_size / eval_batch_size)\n for i in six.moves.range(eval_batch_count):\n if FLAGS.dataset == 'mnist':\n xs, ys = dataset.next_batch(hps.batch_size, fake_data=False)\n args = {model.noise_scale: 1.0,\n model._images: xs,\n model._labels: ys}\n elif FLAGS.dataset == 'cifar10' or FLAGS.dataset == 'cifar100':\n args = {model.noise_scale: 1.0}\n\n (\n summaries,\n loss,\n predictions,\n truth,\n train_step,\n ) = sess.run(\n [\n model.summaries,\n model.cost,\n model.predictions,\n model.labels,\n model.global_step,\n ],\n args)\n\n print(\"Done: {}/{}\".format(eval_batch_size*i, eval_data_size))\n truth = np.argmax(truth, axis=1)[:hps.batch_size]\n prediction_votes = np.zeros([hps.batch_size, hps.num_classes])\n predictions = np.argmax(predictions, axis=1)\n for i in range(hps.n_draws):\n for j in range(hps.batch_size):\n prediction_votes[j, predictions[i*hps.batch_size + j]] += 1\n predictions = np.argmax(prediction_votes, axis=1)\n\n data['predictions'] += prediction_votes.tolist()\n data['pred_truth'] += (truth == predictions).tolist()\n\n print(\"{} / {}\".format(np.sum(truth == predictions), len(predictions)))\n\n correct_prediction += np.sum(truth == predictions)\n total_prediction += predictions.shape[0]\n\n current_precision = 1.0 * correct_prediction / total_prediction\n print(current_precision)\n print()\n\n # For Parseval, get true sensitivity, use to rescale the actual attack\n # bound as the nosie assumes this to be 1 but often it is not.\n if hps.noise_scheme == 'l2_l2_s1':\n # Parseval updates usually have a sensitivity higher than 1\n # despite the projection: we need to rescale when computing\n # sensitivity.\n sensitivity_multiplier = float(sess.run(\n model.sensitivity_multiplier,\n {model.noise_scale: 1.0}\n ))\n else:\n sensitivity_multiplier = 1.0\n with open(dir_name + \"/sensitivity_multiplier.json\", 'w') as f:\n d = [sensitivity_multiplier]\n f.write(json.dumps(d))\n\n # Compute robustness and add it to the eval data.\n dp_mechs = {\n 'l2_l2_s1': 'gaussian',\n 'l1_l2_s1': 'gaussian',\n 'l1_l1_s1': 'laplace',\n 'l1_l1': 'laplace',\n 'l1_l2': 'gaussian',\n 'l2': 'gaussian',\n 'l1': 'laplace',\n }\n robustness = [utils.robustness_size(\n counts=x,\n dp_attack_size=hps.attack_norm_bound,\n dp_epsilon=1.0,\n dp_delta=0.05,\n dp_mechanism=dp_mechs[hps.noise_scheme]\n ) / sensitivity_multiplier for x in data['predictions']]\n data['robustness'] = robustness\n data['sensitivity_mult_used'] = sensitivity_multiplier\n\n # Log eval data\n with open(dir_name + \"/eval_data.json\", 'w') as f:\n f.write(json.dumps(data))\n\n # Print stuff\n precision = 1.0 * correct_prediction / total_prediction\n best_precision = max(precision, best_precision)\n\n precision_summ = tf.Summary()\n precision_summ.value.add(\n tag='Precision', simple_value=precision)\n summary_writer.add_summary(precision_summ, train_step)\n best_precision_summ = tf.Summary()\n best_precision_summ.value.add(\n tag='Best Precision', simple_value=best_precision)\n summary_writer.add_summary(best_precision_summ, train_step)\n summary_writer.add_summary(summaries, train_step)\n tf.logging.info('loss: %.3f, precision: %.3f, best precision: %.3f' %\n (loss, precision, best_precision))\n summary_writer.flush()\n\ndef train(hps, model, dir_name=None):\n \"\"\"Training loop.\"\"\"\n if dir_name == None:\n dir_name = FLAGS.data_dir + \"/\" + FLAGS.model_dir\n\n if FLAGS.dataset == 'mnist':\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n dataset = mnist.train\n images = tf.placeholder(tf.float32,\n [hps.batch_size, 784],\n name='x-input')\n labels = tf.placeholder(tf.int64,\n [hps.batch_size],\n name='y-input')\n elif FLAGS.dataset == 'cifar10' or FLAGS.dataset == 'cifar100':\n images, labels = cifar_input.build_input(\n FLAGS.dataset,\n FLAGS.eval_data_path,\n hps.batch_size,\n hps.image_standardization,\n FLAGS.mode\n )\n model = model.Model(hps, images, labels, FLAGS.mode)\n model.build_graph()\n\n param_stats = tf.contrib.tfprof.model_analyzer.print_model_analysis(\n tf.get_default_graph(),\n tfprof_options=tf.contrib.tfprof.model_analyzer.\n TRAINABLE_VARS_PARAMS_STAT_OPTIONS)\n sys.stdout.write('total_params: %d\\n' % param_stats.total_parameters)\n\n tf.contrib.tfprof.model_analyzer.print_model_analysis(\n tf.get_default_graph(),\n tfprof_options=tf.contrib.tfprof.model_analyzer.FLOAT_OPS_OPTIONS)\n\n truth = tf.argmax(model.labels, axis=1)\n predictions = tf.argmax(model.predictions, axis=1)\n one_hot_preds = tf.one_hot(predictions, depth=hps.num_classes, dtype=tf.float32)\n votes = tf.reshape(one_hot_preds, [hps.n_draws, hps.batch_size, hps.num_classes])\n predictions = tf.argmax(tf.reduce_sum(votes, axis=0), axis=1)\n precision = tf.reduce_mean(tf.to_float(tf.equal(predictions, truth)))\n\n summary_hook = tf.train.SummarySaverHook(\n save_steps=100,\n output_dir=dir_name,\n summary_op=tf.summary.merge([model.summaries,\n tf.summary.scalar('Precision', precision)]))\n\n logging_hook = tf.train.LoggingTensorHook(\n tensors={'step': model.global_step,\n 'loss': model.cost,\n 'precision': precision},\n every_n_iter=100)\n\n class _LearningRateSetterHook(tf.train.SessionRunHook):\n \"\"\"Sets learning_rate based on global step.\"\"\"\n\n def begin(self):\n self._lrn_rate = 0.1\n self._schedule = list(zip(hps.lrn_rte_changes, hps.lrn_rte_vals))\n\n def before_run(self, run_context):\n return tf.train.SessionRunArgs(\n model.global_step, # Asks for global step value.\n feed_dict={model.lrn_rate: self._lrn_rate}) # Sets learning rate\n\n def after_run(self, run_context, run_values):\n train_step = run_values.results\n if len(self._schedule) > 0 and train_step >= self._schedule[0][0]:\n # Update learning rate according to the schedule.\n self._lrn_rate = self._schedule[0][1]\n self._schedule = self._schedule[1:]\n\n print(\"START TRAINING\")\n steps = 0\n with tf.train.MonitoredTrainingSession(\n checkpoint_dir=dir_name,\n hooks=[logging_hook,\n _LearningRateSetterHook(),\n tf.train.StopAtStepHook(last_step=FLAGS.max_steps),],\n chief_only_hooks=[summary_hook],\n # Since we provide a SummarySaverHook, we need to disable default\n # SummarySaverHook. To do that we set save_summaries_steps to 0.\n save_summaries_steps=0,\n config=tf.ConfigProto(allow_soft_placement=True)) as mon_sess:\n while not mon_sess.should_stop():\n s = 1.0 - min(0.99975**steps, 0.9)\n if s > 0.9: s = 1.0 # this triggers around 10k steps\n\n if FLAGS.dataset == 'mnist':\n xs, ys = dataset.next_batch(hps.batch_size, fake_data=False)\n args = {model.noise_scale: s,\n model._images: xs,\n model._labels: ys}\n elif FLAGS.dataset == 'cifar10' or FLAGS.dataset == 'cifar100':\n args = {model.noise_scale: s}\n\n mon_sess.run(model.train_op, args)\n steps += 1\n\ndef run_one():\n if FLAGS.num_gpus == 0:\n dev = '/cpu:0'\n elif FLAGS.num_gpus == 1:\n dev = '/gpu:0'\n else:\n raise ValueError('Only support 0 or 1 gpu.')\n\n if FLAGS.dataset == 'mnist':\n image_size = 28\n num_classes = 10\n relu_leakiness = 0.0\n lrn_rate = 0.01\n lrn_rte_changes = []\n lrn_rte_vals = []\n if FLAGS.mode == 'train':\n batch_size = 128\n n_draws = 1\n elif FLAGS.mode == 'eval':\n batch_size = 100\n n_draws = 500\n else:\n lrn_rate = 0.1\n lrn_rte_changes = [40000, 60000, 80000]\n lrn_rte_vals = [0.01, 0.001, 0.0001]\n if FLAGS.mode == 'train':\n batch_size = 128\n n_draws = 1\n elif FLAGS.mode == 'eval':\n batch_size = 4\n n_draws = 500\n\n if FLAGS.dataset == 'cifar10':\n image_size = 32\n num_classes = 10\n relu_leakiness = 0.1\n elif FLAGS.dataset == 'cifar100':\n image_size = 32\n num_classes = 100\n relu_leakiness = 0.1\n\n # noise_schemes for pixeldp_img_noise:\n # - l1: L1 attack bound, L1 sensitivity (Laplace mech.).\n # - l2: L2 attack bound, L2 sensitivity (Gaussian mech.).\n # noise_schemes for pixeldp_conv1:\n # - l1_l1: L1 attack bound with L1 sensitivity, reparametrization\n # trick (Laplace).\n # - l1_l1_s1: L1 attack bound with L1 sensitivity, sensitivity=1\n # (Laplace).\n # - l1_l2: L1 attack bound with L2 sensitivity, reparametrization\n # (Gaussian).\n # - l1_l2_s1: L1 attack bound with L2 sensitivity, sensitivity=1\n # (Gaussian).\n # - l2_l2_s1: L2 attack bound with L2 sensitivity, sensitivity<=1\n # (Gaussian).\n hps = utils.HParams(batch_size=batch_size,\n num_classes=num_classes,\n image_size=image_size,\n lrn_rate=lrn_rate,\n lrn_rte_changes=lrn_rte_changes,\n lrn_rte_vals=lrn_rte_vals,\n num_residual_units=4,\n use_bottleneck=False,\n weight_decay_rate=0.0002,\n relu_leakiness=relu_leakiness,\n optimizer='mom',\n image_standardization=False,\n dropout=False,\n n_draws=n_draws,\n noise_scheme='l2_l2_s1',\n attack_norm_bound=0.3)\n\n # _model can be:\n # pixeldp_resnet_conv1 pixeldp_resnet_img_noise\n # pixeldp_cnn_conv1 pixeldp_cnn_img_noise\n _model = pixeldp_cnn_conv1\n with tf.device(dev):\n if FLAGS.mode == 'train':\n train(hps, _model)\n elif FLAGS.mode == 'eval':\n evaluate(hps, _model)\n\ndef main(_):\n run_one()\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"125165767","text":"# ex:ts=4:sw=4:sts=4:et\n# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-\nfrom __future__ import absolute_import\nimport re\nimport json\nimport copy\nimport os\n\nfrom svtplay_dl.service import Service\nfrom svtplay_dl.utils import filenamify\nfrom svtplay_dl.log import log\nfrom svtplay_dl.fetcher.rtmp import RTMP\nfrom svtplay_dl.fetcher.hls import hlsparse\nfrom svtplay_dl.subtitle import subtitle\nfrom svtplay_dl.error import ServiceError\n\n\nclass Kanal5(Service):\n supported_domains = ['kanal5play.se', 'kanal9play.se', 'kanal11play.se']\n\n def __init__(self, url):\n Service.__init__(self, url)\n self.cookies = {}\n self.subtitle = None\n\n def get(self, options):\n match = re.search(r\".*video/([0-9]+)\", self.url)\n if not match:\n yield ServiceError(\"Can't find video file\")\n return\n\n video_id = match.group(1)\n if options.username and options.password:\n # get session cookie\n data = self.http.request(\"get\", \"http://www.kanal5play.se/\", cookies=self.cookies)\n authurl = \"https://kanal5swe.appspot.com/api/user/login?callback=jQuery171029989&email=%s&password=%s&_=136250\" % \\\n (options.username, options.password)\n data = self.http.request(\"get\", authurl, cookies=data.cookies).text\n match = re.search(r\"({.*})\\);\", data)\n jsondata = json.loads(match.group(1))\n if jsondata[\"success\"] is False:\n yield ServiceError(jsondata[\"message\"])\n return\n authToken = jsondata[\"userData\"][\"auth\"]\n self.cookies = {\"authToken\": authToken}\n options.cookies = self.cookies\n\n url = \"http://www.kanal5play.se/api/getVideo?format=FLASH&videoId=%s\" % video_id\n data = self.http.request(\"get\", url, cookies=self.cookies).text\n data = json.loads(data)\n options.cookies = self.cookies\n if not options.live:\n options.live = data[\"isLive\"]\n\n if options.output_auto:\n directory = os.path.dirname(options.output)\n options.service = \"kanal5\"\n\n title = \"%s-s%s-%s-%s-%s\" % (data[\"program\"][\"name\"], data[\"seasonNumber\"], data[\"episodeText\"], data[\"id\"], options.service)\n title = filenamify(title)\n if len(directory):\n options.output = os.path.join(directory, title)\n else:\n options.output = title\n\n if self.exclude(options):\n yield ServiceError(\"Excluding video\")\n return\n\n if data[\"hasSubtitle\"]:\n yield subtitle(copy.copy(options), \"json\", \"http://www.kanal5play.se/api/subtitles/%s\" % video_id)\n\n if options.force_subtitle:\n return\n\n show = True\n if \"streams\" in data.keys():\n for i in data[\"streams\"]:\n if i[\"drmProtected\"]:\n yield ServiceError(\"We cant download drm files for this site.\")\n return\n steambaseurl = data[\"streamBaseUrl\"]\n bitrate = i[\"bitrate\"]\n if bitrate > 1000:\n bitrate = bitrate / 1000\n options2 = copy.copy(options)\n options2.other = \"-W %s -y %s \" % (\"http://www.kanal5play.se/flash/K5StandardPlayer.swf\", i[\"source\"])\n options2.live = True\n yield RTMP(options2, steambaseurl, bitrate)\n\n url = \"http://www.kanal5play.se/api/getVideo?format=IPAD&videoId=%s\" % video_id\n data = self.http.request(\"get\", url, cookies=self.cookies)\n data = json.loads(data.text)\n if \"reasonsForNoStreams\" in data:\n show = False\n if \"streams\" in data.keys():\n for i in data[\"streams\"]:\n streams = hlsparse(options, self.http.request(\"get\", i[\"source\"]), i[\"source\"])\n for n in list(streams.keys()):\n yield streams[n]\n if \"reasonsForNoStreams\" in data and show:\n yield ServiceError(data[\"reasonsForNoStreams\"][0])\n\n def find_all_episodes(self, options):\n program = re.search(\".*/program/(\\d+)\", self.url)\n if not program:\n log.error(\"Can't find program id in url\")\n return None\n baseurl = \"http://www.kanal5play.se/content/program/%s\" % program.group(1)\n data = self.http.request(\"get\", baseurl).text\n sasong = re.search(\"/program/\\d+/sasong/(\\d+)\", data)\n if not sasong:\n log.error(\"Can't find seasong id\")\n return None\n seasong = int(sasong.group(1))\n episodes = []\n n = 0\n more = True\n while more:\n url = \"%s/sasong/%s\" % (baseurl, seasong)\n data = self.http.request(\"get\", url)\n if data.status_code == 404:\n more = False\n else:\n regex = re.compile(r'href=\"(/play/program/\\d+/video/\\d+)\"')\n for match in regex.finditer(data.text):\n if n == options.all_last:\n break\n url2 = \"http://www.kanal5play.se%s\" % match.group(1)\n if url2 not in episodes:\n episodes.append(url2)\n n += 1\n seasong -= 1\n\n return episodes\n","sub_path":"lib/svtplay_dl/service/kanal5.py","file_name":"kanal5.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371093344","text":"from django.urls import path\nfrom .views import (index, MailHtml, Staff, Logout, Login, login_html, StaffDailyList, DailyCreate, news , SecurityNews,\n SecurityNewsDetail, AllStaffDetail, RssNews, SelfNews, ApiAllStaffDetail, ApiStaffDetail,\n DeleteDaily)\n\nurlpatterns = [\n # path('/', admin.site.urls),\n path('', SelfNews.as_view()),\n path('safe', SecurityNews.as_view()),\n path('feed', RssNews.as_view()),\n path('sendmail', MailHtml.as_view()),\n path('staffinfo', Staff.as_view()),\n path('logout/', Logout.as_view(), name=\"logout\"),\n path('accounts/login/', login_html, name=\"login\"),\n # path('auth/login/', Login.as_view()),\n path('daily/<pk>/', StaffDailyList.as_view(), name='StaffDailyList'),\n path('create/daily/', DailyCreate.as_view()),\n path('news/', SecurityNews.as_view()),\n path('news/<pk>/', SecurityNewsDetail.as_view(), name=\"news-detail\"),\n path('index/', index),\n path('alldaily', AllStaffDetail.as_view()),\n path('api/all_detail', ApiAllStaffDetail.as_view()),\n path('api/staff_detail/<str:name>/', ApiStaffDetail.as_view()),\n path('delete/<pk>', DeleteDaily.as_view()),\n]\n","sub_path":"scheduled/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"237052495","text":"from django.shortcuts import render\nfrom facebook_business.adobjects.adsinsights import AdsInsights\nfrom facebook_business.adobjects.campaign import Campaign as RemoteCampaign\n\nfrom app.service.adaccount_service import AdAccountService\nfrom app.views.constants import DATE_PRESET_CHOICES\nfrom copy import deepcopy\n\nADACCOUNT_CHOICES = [\n ('this_adaccount', 'Tài khoản hiện tại'),\n ('all_adaccounts', 'Tất cả tài khoản')\n]\n\nOBJECTIVE_CHOICES = {\n (RemoteCampaign.Objective.post_engagement, \"Tương tác\"),\n (RemoteCampaign.Objective.conversions, \"Chuyển đổi\"),\n (RemoteCampaign.Objective.messages, \"Tin nhắn\"),\n (RemoteCampaign.Objective.video_views, 'Xem video')\n}\n\nBREAKDOWNS_CHOICES = [\n (AdsInsights.Breakdowns.impression_device, 'Thiết bị hiển thị'),\n (AdsInsights.Breakdowns.age, 'Độ tuổi'),\n (AdsInsights.Breakdowns.gender, 'Giới tính'),\n (AdsInsights.Breakdowns.region, 'Tỉnh thành'),\n (AdsInsights.Breakdowns.publisher_platform, 'Nền tảng'),\n (AdsInsights.Breakdowns.device_platform, 'Thiết bị'),\n (AdsInsights.Breakdowns.hourly_stats_aggregated_by_advertiser_time_zone, 'Giờ trong ngày'),\n ('publisher_platform_platform_position', 'Vị trí hiển thị'),\n ('age_gender', 'Độ tuổi + giới tính'),\n ('publisher_platform_platform_position_impression_device', 'Vị trí + thiết bị hiển thị'),\n]\n\n\ndef analysis(request):\n params = {\n 'objective' : request.GET.get('objective', RemoteCampaign.Objective.post_engagement),\n 'date_preset': request.GET.get('date_preset', AdsInsights.DatePreset.last_30d),\n 'breakdowns' : request.GET.get('breakdowns', AdsInsights.Breakdowns.impression_device),\n 'adaccount' : request.GET.get('adaccount', ADACCOUNT_CHOICES[0][0])\n }\n if params['breakdowns'] == 'publisher_platform_platform_position_impression_device':\n params['breakdowns'] = ['publisher_platform', 'platform_position', 'impression_device']\n adsinsights_dlist = AdAccountService.get_adsinsight_by_breakdowns(**params)\n params['breakdowns'] = 'publisher_platform_platform_position_impression_device'\n elif params['breakdowns'] == 'publisher_platform_platform_position':\n params['breakdowns'] = ['publisher_platform', 'platform_position']\n adsinsights_dlist = AdAccountService.get_adsinsight_by_breakdowns(**params)\n params['breakdowns'] = 'publisher_platform_platform_position'\n elif params['breakdowns'] == 'age_gender':\n params['breakdowns'] = ['age', 'gender']\n adsinsights_dlist = AdAccountService.get_adsinsight_by_breakdowns(**params)\n params['breakdowns'] = 'age_gender'\n else:\n adsinsights_dlist = AdAccountService.get_adsinsight_by_breakdowns(**params)\n\n summary = AdAccountService.get_adsinsight_by_breakdowns_summary(adsinsights_dlist)\n\n context = {\n \"OBJECTIVE_CHOICES\" : OBJECTIVE_CHOICES,\n \"BREAKDOWNS_CHOICES\" : BREAKDOWNS_CHOICES,\n \"DATE_PRESET_CHOICES\": DATE_PRESET_CHOICES,\n \"ADACCOUNT_CHOICES\" : ADACCOUNT_CHOICES,\n \"adsinsights_dlist\" : adsinsights_dlist,\n \"params\" : params,\n \"summary\" : summary\n }\n\n return render(request, \"app/analysis/analysis.html\", context)\n","sub_path":"app/views/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"158247672","text":"from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.shortcuts import get_object_or_404, render\n\nfrom .models import Category, Product, ProductImage\n\n\ndef product_all(request):\n products = Product.objects.prefetch_related('product_image').filter(is_active=True)\n return render(request, 'catalogue/index.html', {'products': products})\n\n\ndef category_list(request, category_slug=None):\n category = get_object_or_404(Category, slug=category_slug)\n products = Product.objects.filter(\n category__in=Category.objects.get(slug=category_slug).get_descendants(include_self=True)\n )\n paginator = Paginator(products, 10)\n page = request.GET.get('page')\n try:\n product = paginator.page(page)\n except PageNotAnInteger:\n product = paginator.page(1)\n except EmptyPage:\n product = paginator.page(paginator.num_pages)\n return render(request, 'catalogue/category.html', {\n 'category': category,\n 'products': products,\n 'page': page,\n 'product': product,\n })\n\n\ndef product_detail(request, slug):\n product = get_object_or_404(Product, slug=slug, is_active=True)\n\n return render(request, 'catalogue/single.html', {'product': product})\n\n\n\n\n\n\n","sub_path":"ecommerce/ecommerce/apps/catalogue/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83599177","text":"from numpy import sin, cos, cumsum, dot, zeros\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom sympy.physics.mechanics import kinetic_energy\nfrom numpy import array, linspace, deg2rad, ones, concatenate\nfrom sympy import lambdify, atan, atan2, Matrix, simplify\nfrom sympy.mpmath import norm\nfrom pydy.codegen.code import generate_ode_function\nfrom scipy.integrate import odeint\nimport math\nimport numpy as np\nimport single_pendulum_setup as sp\nimport double_pendulum_particle_setup as pp\nimport double_pendulum_rb_setup as rb\nimport triple_pendulum_setup as tp\nimport pickle\n\n\n\nnumerical_constants = array([0.5,\n 0.5,\n 0.75,\n 0.75,\n 1.0,\n 1.0,\n 9.81])\n\nparameter_dict = dict(zip(tp.constants, numerical_constants))\n\n\ngravity_dict = dict(zip([sp.g, pp.g, rb.g, tp.g], [9.81,9.81, 9.81, 9.81]))\nglobal_mass_dict = dict(zip([sp.s_mass], [tp.a_mass+tp.b_mass+tp.c_mass]))\nsp_forcing = -1*simplify(sp.forcing - sp.s_torque) + sp.s_torque\nsp_eq = (sp.mass_matrix.inv()*sp_forcing)[0].subs(gravity_dict)\nsp_eq_torque_only = sp.s_torque*(sp.mass_matrix.inv())[0].subs(global_mass_dict).subs(parameter_dict)\nsp_eq = sp_eq.subs(global_mass_dict).subs(parameter_dict)\n\nsp_eq_string = str(sp_eq)\nsp_eq_vars = str([sp.s_length, sp.theta_s, sp.s_torque])\nfile = open('sp_eq.pkl', 'wb')\npickle.dump([sp_eq_string, sp_eq_vars], file)\nfile.close()\n\nsp_eq_torque_only_string = str(sp_eq)\nsp_eq_torque_only_vars = str([sp.s_length, sp.s_torque])\nfile = open('sp_eq_torque_only.pkl', 'wb')\npickle.dump([sp_eq_torque_only_string, sp_eq_torque_only_vars], file)\nfile.close()\n\n\ncom_eq_string = str(tp.com.subs(parameter_dict))\ncom_eq_vars = str((tp.theta_a, tp.theta_b, tp.theta_c))\nfile = open('com_eq.pkl', 'wb')\npickle.dump([com_eq_string, com_eq_vars], file)\nfile.close()\n\n\n\ncom_dot_eq_string = str(tp.com_dot.subs(parameter_dict))\ncom_dot_eq_vars = str([tp.theta_a, tp.theta_b, tp.theta_c, \n tp.omega_a, tp.omega_b, tp.omega_c])\nfile = open('com_dot_eq.pkl', 'wb')\npickle.dump([com_dot_eq_string, com_dot_eq_vars], file)\nfile.close()\n\n\nsolved_pp_com_ddot_t1_string = str(pp.des_t1_acc)\nsolved_pp_com_ddot_t1_vars = str([pp.one_length, pp.two_length, pp.one_mass, pp.two_mass, pp.theta1, pp.theta2, pp.omega1, pp.omega2, pp.des_com_ang_acc_x, pp.des_com_ang_acc_y])\nfile = open('solved_pp_com_ddot_t1.pkl', 'wb')\npickle.dump([solved_pp_com_ddot_t1_string, solved_pp_com_ddot_t1_vars], file)\nfile.close()\n\n\nsolved_pp_com_ddot_t2_string = str(pp.des_t2_acc)\nsolved_pp_com_ddot_t2_vars = str([pp.one_length, pp.two_length, pp.one_mass, pp.two_mass, pp.theta1, pp.theta2, pp.omega1, pp.omega2, pp.des_com_ang_acc_x, pp.des_com_ang_acc_y])\nfile = open('solved_pp_com_ddot_t2.pkl', 'wb')\npickle.dump([solved_pp_com_ddot_t2_string, solved_pp_com_ddot_t2_vars], file)\nfile.close()\n\n\nsolved_rb_com_ddot_t1_string = str(rb.des_t1_acc)\nsolved_rb_com_ddot_t1_vars = str([rb.one_length, rb.one_com_x, rb.one_com_y, rb.two_com_x, rb.two_com_y, rb.one_mass, rb.two_mass, rb.theta1, rb.theta2, rb.omega1, rb.omega2, rb.des_com_ang_acc_x, rb.des_com_ang_acc_y])\nfile = open('solved_rb_com_ddot_t1.pkl', 'wb')\npickle.dump([solved_rb_com_ddot_t1_string, solved_rb_com_ddot_t1_vars], file)\nfile.close()\n\n\nsolved_rb_com_ddot_t2_string = str(rb.des_t2_acc)\nsolved_rb_com_ddot_t2_vars = str([rb.one_length, rb.one_com_x, rb.one_com_y, rb.two_com_x, rb.two_com_y, rb.one_mass, rb.two_mass, rb.theta1, rb.theta2, rb.omega1, rb.omega2, rb.des_com_ang_acc_x, rb.des_com_ang_acc_y])\nfile = open('solved_rb_com_ddot_t2.pkl', 'wb')\npickle.dump([solved_rb_com_ddot_t2_string, solved_rb_com_ddot_t2_vars], file)\nfile.close()\n\nbc_com_string = str(tp.com_bc_in_a.subs(parameter_dict))\nbc_com_vars = str([tp.theta_b, tp.theta_c])\nfile = open('bc_com.pkl', 'wb')\npickle.dump([bc_com_string, bc_com_vars], file)\nfile.close()\n\n\nbc_com_inertial_string = str(tp.com_bc.subs(parameter_dict))\nbc_com_inertial_vars = str([tp.theta_a, tp.theta_b, tp.theta_c])\nfile = open('bc_com_inertial.pkl', 'wb')\npickle.dump([bc_com_inertial_string, bc_com_inertial_vars], file)\nfile.close()\n\n\nbc_com_dot_string = str(tp.com_bc_dot_in_a.subs(parameter_dict))\nbc_com_dot_vars = str([tp.theta_b, tp.theta_c, tp.omega_b, tp.omega_c])\nfile = open('bc_com_dot.pkl', 'wb')\npickle.dump([bc_com_dot_string, bc_com_dot_vars], file)\nfile.close()\n\na_com_string = str(tp.com_a.subs(parameter_dict))\na_com_vars = str([tp.theta_a])\nfile = open('a_com.pkl', 'wb')\npickle.dump([a_com_string, a_com_vars], file)\nfile.close()\n\na_com_dot_string = str(tp.com_a_dot.subs(parameter_dict))\na_com_dot_vars = str([tp.theta_a, tp.omega_a])\nfile = open('a_com_dot.pkl', 'wb')\npickle.dump([a_com_dot_string, a_com_dot_vars], file)\nfile.close()\n\npp_inverse_dynamics_string = str( pp.inverse_dynamics.subs(gravity_dict))\npp_inverse_dynamics_vars = str([pp.one_length, pp.two_length, pp.one_mass, pp.two_mass, pp.theta1, pp.theta2, pp.omega1, pp.omega2, pp.alpha1, pp.alpha2])\nfile = open('pp_inverse_dynamics.pkl', 'wb')\npickle.dump([pp_inverse_dynamics_string, pp_inverse_dynamics_vars], file)\nfile.close()\n\n\nrb_inverse_dynamics_string = str(rb.inverse_dynamics.subs(gravity_dict))\nrb_inverse_dynamics_vars = str([rb.one_length, rb.one_com_x, rb.one_com_y, rb.two_com_x, rb.two_com_y, rb.one_com_x_dot, rb.one_com_y_dot, rb.two_com_x_dot, rb.two_com_y_dot, rb.one_mass, rb.two_mass, rb.theta1, rb.theta2, rb.omega1, rb.omega2, rb.alpha1, rb.alpha2])\nfile = open('rb_inverse_dynamics.pkl', 'wb')\npickle.dump([rb_inverse_dynamics_string, rb_inverse_dynamics_vars], file)\nfile.close()\n\nargs_ode_funcs = str([tp.mass_matrix_full, tp.forcing_vector_full, \n tp.constants, tp.coordinates,\n tp.speeds, tp.specified])\nfile = open('args_ode_funcs.pkl', 'wb')\npickle.dump(args_ode_funcs, file)\nfile.close()\n\n\n","sub_path":"equivalent_acrobot/pickle_funcs.py","file_name":"pickle_funcs.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"309475948","text":"from ..models.users import User\nimport time\nfrom vk.exceptions import VkAPIError\n\n\nclass Manager(object):\n def __init__(self, db_sessuib_class, bots, group_id):\n self.session = db_sessuib_class()\n self.bots = bots\n self.group_id = group_id\n\n def process(self):\n for bot in [b for b in self.bots if b.ready()]: # only ready bots\n try:\n self._invite_users(bot)\n except VkAPIError as e:\n if e.is_captcha_needed():\n print(e.message)\n bot.sleep(3)\n continue\n\n def _invite_users(self, bot):\n users = self.session.query(User).filter_by(bot_id=bot.uid) \\\n .filter_by(is_in_friend_list=True) \\\n .filter_by(is_group_invite_sent=False)\n\n for user in users:\n time.sleep(5)\n self._invite_specific_user(user, bot)\n\n self.session.commit()\n\n def _invite_specific_user(self, u, bot):\n is_member = bot.api.groups.isMember(\n group_id=self.group_id, user_id=u.uid)\n\n if not is_member:\n # if user not a member then (re)send group invite\n print('inviting user %s to group' % u.uid)\n bot.api.groups.invite(group_id=self.group_id, user_id=u.uid)\n\n # even if already in group set property to True\n # to prevent further invites\n u.is_group_invite_sent = True\n","sub_path":"inviter/modules/invite_manager.py","file_name":"invite_manager.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"49295419","text":"\"\"\"\n Capstone Project. Code written by PUT_YOUR_NAME_HERE.\n Fall term, 2018-2019.\n\"\"\"\n\nimport rosebotics_new as rb\nimport ev3dev.ev3 as ev3\nimport time\n\n\ndef main():\n \"\"\" Runs YOUR specific part of the project \"\"\"\n red = rb.Color.RED.value\n blue = rb.Color.BLUE.value\n green = rb.Color.GREEN.value\n nocolor = rb.Color.NO_COLOR.value\n brown = rb.Color.BROWN.value\n white = rb.Color.WHITE.value\n yellow = rb.Color.YELLOW.value\n black = rb.Color.BLACK.value\n\n # robot = rb.Snatch3rRobot()\n # robot.drive_system.go_straight_inches(20)\n drive_polygon(5, 10)\n # line_follow()\n # drive_until_color(red)\n # robot.drive_system.turn_degrees\n #detectItem()\n # ColorSorting(red, blue, green, yellow, green)\n\ndef detectItem():\n robot = rb.Snatch3rRobot()\n sensor = robot.proximity_sensor\n\n while True:\n if ((70 * ((sensor.get_distance_to_nearest_object())/100)) < 15) and ((70 * ((sensor.get_distance_to_nearest_object())/100)) > 9):\n ev3.Sound.beep()\n\n\n\ndef drive_polygon(n, inches):\n x = rb.Snatch3rRobot()\n drivesystem = x.drive_system\n # degrees = ((n - 2) * 180) / n\n # degrees = 180 - degrees\n degrees = (360/n)\n\n for k in range(n):\n drivesystem.go_straight_inches(inches)\n drivesystem.spin_in_place_degrees(-degrees)\n\n\ndef line_follow():\n robot = rb.Snatch3rRobot()\n drivesystem = robot.drive_system\n colorsensor = robot.color_sensor\n drivesystem.start_moving()\n while True:\n if colorsensor.get_reflected_intensity() > 10:\n drivesystem.spin_in_place_degrees(10)\n drivesystem.start_moving(50,50)\n\n\ndef drive_until_color(color):\n robot = rb.Snatch3rRobot()\n drivesystem = robot.drive_system\n colorsensor = robot.color_sensor\n drivesystem.start_moving(50,50)\n\n while True:\n colorsensor.wait_until_color_is(color)\n drivesystem.stop_moving()\n break\n\n\n\n\n# Capstone Project\n\ndef ColorSorting(red, white, yellow, black, green):\n robot = rb.Snatch3rRobot()\n colorsensor = robot.color_sensor\n drivesystem = robot.drive_system\n ev3.Sound.set_volume(100)\n drivesystem.start_moving(20,20)\n\n while True:\n if colorsensor.get_color() == red:\n ev3.Sound.speak(\"Hello\")\n if colorsensor.get_color() == white:\n ev3.Sound.speak(\"to\")\n if colorsensor.get_color() == yellow:\n ev3.Sound.speak(\"the\")\n if colorsensor.get_color() == black:\n ev3.Sound.speak(\"world\")\n if colorsensor.get_color() == green:\n ev3.Sound.speak(\"Greetings humans\")\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\nmain()\n","sub_path":"src/harrisap.py","file_name":"harrisap.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"580308518","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport re\nimport sys\nfrom pyspark import SparkConf, SparkContext\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\n\n\n# In[ ]:\n\n\n#set context\nconf = SparkConf()\nsc = SparkContext(conf=conf)\n\n\n# In[ ]:\n\n\nmax_iter = 20\nclusters = 10\n\n\n# In[ ]:\n\n\ndef split(l):\n line=l.split(' ')\n val = [float(s) for s in line if s is not ''] \n return tuple(val)\n\ndef combine_with_cluster(l,clu):\n return [(l,c) for c in clu]\n\ndef calc_dist(l, norm=2):\n dist = np.linalg.norm(np.array(l[0])-np.array(l[1]),ord=norm)\n return (l[0],(dist,l[1]))\n\ndef calc_new_cluster(l):\n l = list(l)\n size = len(l)\n agg = sum(np.array(l))\n return tuple(agg/size)\n\ndef get_costs(init_clusters,norm):\n costs = []\n curr_clusters = init_clusters\n for i in range(max_iter): # k - means algorithm\n combos = docs.flatMap(lambda l:combine_with_cluster(l,curr_clusters)) #get (vec,clu) pairs\n combos_w_euc_dist = combos.map(lambda l:calc_dist(l,norm)) #add the distance to said cluster\n combos_w_euc_dist_grouped = combos_w_euc_dist.groupByKey()\n closest = combos_w_euc_dist_grouped.mapValues(lambda val: min(list(val))) # filter such that only the closest (dist,clust) remains as value for a vector\n costs += [sum(closest.map(lambda l:l[1][0]).collect())] #add costs for this clustering\n curr_clusters = closest.map(lambda l : (l[1][1],l[0])).groupByKey() #sort all vectors to its cluster\n new_clusters = curr_clusters.map(lambda l: calc_new_cluster(l[1])) #calculate new clusters\n curr_clusters = new_clusters.collect()\n print('Current cost is', costs[-1])\n return costs\n\n\n# In[ ]:\n\n\n#read file in\ndocs = sc.textFile('./data/data.txt').map(split)\nc1 = sc.textFile('./data/c1.txt').map(split)\nc2 = sc.textFile('./data/c2.txt').map(split)\n\n\n# In[ ]:\n\n\ncluster_rand = c1.collect()\ncluster_max = c2.collect()\n\n\n# In[ ]:\n\n\ncosts_rand = get_costs(cluster_rand,2)\n\ncosts_max = get_costs(cluster_max,2)\n\n# costs_max = []\n# curr_clusters = cluster_max\n# for i in range(max_iter): # k - means algorithm\n# combos = docs.flatMap(lambda l:combine_with_cluster(l,curr_clusters)) #get (vec,clu) pairs\n# combos_w_euc_dist = combos.map(lambda l:calc_dist(l,None)) #add the distance to said cluster\n# combos_w_euc_dist_grouped = combos_w_euc_dist.groupByKey()\n# closest = combos_w_euc_dist_grouped.mapValues(lambda val: min(list(val))) # filter such that only the closest (dist,clust) remains as value for a vector\n# costs_max += [sum(closest.map(lambda l:l[1][0]).collect())] #add costs for this clustering\n# curr_clusters = closest.map(lambda l : (l[1][1],l[0])).groupByKey() #sort all vectors to its cluster\n# new_clusters = curr_clusters.map(lambda l: calc_new_cluster(l[1])) #calculate new clusters\n# curr_clusters = new_clusters.collect()\n# print('Current cost is', costs_max[-1])\n\n\n# In[ ]:\n\n\nplt.plot(costs_rand, label = 'Random')\nplt.plot(costs_max, label= 'Max Dist')\nplt.legend()\nplt.ylabel('Cost')\nplt.xlabel('Iteration No.')\nplt.title('Cost of k-mean algo using euclidean distance')\n\n\n# In[ ]:\n\n\ncosts_rand_man = get_costs(cluster_rand,1)\ncosts_max_man = get_costs(cluster_max,1)\n\n\n# In[ ]:\n\n\nplt.plot(costs_rand_man, label = 'Random')\nplt.plot(costs_max_man, label= 'Max Dist')\nplt.legend()\nplt.ylabel('Cost')\nplt.xlabel('Iteration No.')\nplt.title('Cost of k-mean algo using manhattan distance')\n\n\n# In[ ]:\n\n\na = sc.parallelize([(\"a\",(0,(2,2))), (\"b\",(0,(3,6))), (\"c\",(3,(5,2))), (\"d\",(4,(3,1))),(\"d\",(2,(3,9))),(\"a\",(1,(3,3)))]).groupByKey()\ndef test(val):\n return min(val)\nmaxKey = a.mapValues(lambda val: min(list(val)))\nmaxKey.collect()\n\n\n# In[ ]:\n\n\na = (3,2)\nb = (3,1)\nsum(np.array([a,b]))/len([a,b])\n\n","sub_path":"HW2/q2/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371535292","text":"from django.shortcuts import redirect,render\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom .forms import RegisterForm\n\ndef register(request):\n form_class = RegisterForm\n form = form_class(request.POST or None)\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request,f'welcome {username},your account has created successfully')\n return redirect('login')\n\n else:\n form = form_class()\n return render (request,'users/register.html',{'form':form})\n\n@login_required\ndef profilepage(request):\n return render(request,'users/profile.html')\n\n\n\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"351962198","text":"class Person:\n counter=0\n current_year=2018\n is_christmas=False\n def __init__(self, full_name, year):\n Person.counter+=1 #what will happen when you remove the \"Person.\"?\n self.id = Person.counter\n self.full_name = full_name\n self.year = year\n def __str__(self):\n return \"{}:{},{}\".format(self.id, self.full_name, self.year)\n def get_age(self):\n return Person.current_year-self.year\n def get_friendly_name(self):\n first_name = self.full_name.split()[0]\n if Person.is_christmas:\n return first_name+'\\U0001F384'\n else:\n return first_name\n\n #@classmethod<- in python2 you need @staticmethod decorator or @classmethod decorator\n def celebrate_new_year(): #you can ignore the warning.\n Person.is_christmas=True\n Person.current_year+=1\n def go_back_to_work():\n Person.is_christmas=False\n\np1 = Person('Homer Simpson', 1982) # create the first person in our program\nprint(Person.counter) # 1\nprint('{}: {}, {}'.format(p1.id, p1.full_name, p1.year)) # 1: Homer Simpson, 1982\np2 = Person('Maggie Simpson', 2017) # create the second person in our program\nprint(Person.counter) # 2\nprint('{}: {}, {}'.format(p2.id, p2.full_name, p2.year)) # 2: Maggie Simpson, 2017\np3 = Person('Burns', 0) # both the given `full_name` and `year` are invalid\nprint(Person.counter) # 3\nprint('{}: {}, {}'.format(p3.id, p3.full_name, p3.year)) # 3: Joe Bloggs, 2000\np = Person('Charles Montgomery Burns', 1937)\nprint(p.__str__()) # 1: Charles Montgomery Burns, 1937\nprint(p) # 1: Charles Montgomery Burns, 1937\nprint(Person.current_year) # 2018\nprint(Person.is_christmas) # False\nprint(p.get_age()) # 81\nprint(p.get_friendly_name()) # Charles\n# continued from above . . .\nPerson.celebrate_new_year()\nprint(Person.current_year) # 2019\nprint(Person.is_christmas) # True\nprint(p.get_age()) # 82\nprint(p.get_friendly_name()) # Charles \n\nPerson.go_back_to_work()\nprint(Person.current_year) # 2019\nprint(Person.is_christmas) # False\nprint(p.get_age()) # 82\nprint(p.get_friendly_name()) # Charles","sub_path":"Tut13/Person.py","file_name":"Person.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"314006078","text":"# © 2017 Sergio Teruel <sergio.teruel@tecnativa.com>\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom odoo import _, api, fields, models\nfrom odoo.exceptions import UserError\n\n\nclass StockPickingOperationWizard(models.TransientModel):\n _name = 'stock.picking.operation.wizard'\n _description = 'Stock Picking Operation Wizard'\n\n def _prepare_default_values(self, picking):\n return {'location_dest_id': picking.location_dest_id.id}\n\n @api.model\n def default_get(self, fields):\n res = super(StockPickingOperationWizard, self).default_get(fields)\n active_model = self.env.context['active_model']\n active_ids = self.env.context['active_ids'] or []\n picking = self.env[active_model].browse(active_ids)\n res.update(self._prepare_default_values(picking))\n return res\n\n def _default_old_dest_location_id(self):\n stock_picking_obj = self.env['stock.picking']\n pickings = stock_picking_obj.browse(self.env.context['active_ids'])\n first_move_line = pickings.mapped('move_line_ids')[:1]\n return first_move_line.location_dest_id.id\n\n def _get_allowed_locations(self):\n return ['internal']\n\n def _get_allowed_location_domain(self):\n return [('usage', 'in', self._get_allowed_locations())]\n\n def _get_allowed_picking_states(self):\n return ['assigned']\n\n location_dest_id = fields.Many2one(\n comodel_name='stock.location',\n string='Actual destination location',\n required=True,\n readonly=True,\n )\n old_location_dest_id = fields.Many2one(\n comodel_name='stock.location',\n string='Old destination location',\n default=_default_old_dest_location_id,\n domain=lambda self: self._get_allowed_location_domain(),\n )\n new_location_dest_id = fields.Many2one(\n comodel_name='stock.location',\n string='New destination location',\n required=True,\n domain=lambda self: self._get_allowed_location_domain(),\n )\n change_all = fields.Boolean(\n string='Change All',\n help='Check if you want change all operations without filter '\n 'by old location')\n\n def check_allowed_pickings(self, pickings):\n forbidden_pickings = pickings.filtered(\n lambda x: x.state not in self._get_allowed_picking_states())\n if forbidden_pickings:\n raise UserError(_(\n 'You can not change operations destination location if '\n 'picking state is not in %s') % ','.join(\n self._get_allowed_picking_states()))\n pickings_with_chained_moves = pickings.filtered(\n lambda x: x.move_lines.mapped('move_dest_ids'))\n if pickings_with_chained_moves:\n raise UserError(_(\n 'You cannot change destination location if any of the moves '\n 'has a destination move.'))\n\n def action_apply(self):\n stock_picking_obj = self.env['stock.picking']\n pickings = stock_picking_obj.browse(self.env.context['active_ids'])\n self.check_allowed_pickings(pickings)\n move_lines = pickings.mapped('move_line_ids')\n\n vals = {'location_dest_id': self.new_location_dest_id.id}\n if self.change_all:\n # Write all operations destination location\n move_lines.write(vals)\n else:\n # Only write operations destination location if the location is\n # the same that old location value\n matched_op = move_lines.filtered(\n lambda x: x.location_dest_id == self.old_location_dest_id)\n matched_op.write(vals)\n return {'type': 'ir.actions.act_window_close'}\n","sub_path":"stock_picking_operation_type_location_change/wizards/stock_picking_wizard.py","file_name":"stock_picking_wizard.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623463509","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# import required modules\nimport time\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(22,GPIO.IN,pull_up_down=GPIO.PUD_UP)\n\nwhile True:\n try: \n GPIO.wait_for_edge(22,GPIO.RISING) \n t1 = time.time()\n GPIO.wait_for_edge(22,GPIO.FALLING)\n t2=time.time()\n if((t2-t1)*170)<4:\n print(\"Zeit in s:\")\n print(t2-t1)\n print(\"Abstand in m:\")\n print((t2-t1)*170)\n \n# reset GPIO settings if user pressed Ctrl+C\n except KeyboardInterrupt:\n print(\"Measurement stopped by user\")\n GPIO.cleanup()\nGPIO.cleanup()\n\n\n","sub_path":"edge3.py","file_name":"edge3.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"431038898","text":"import threading\nfrom pprint import pprint\nimport time\nimport random\n\ncondition = threading.Condition()\n\ncontainer = []\n\ncounter = 1\n\nmore_to_come = True\n\ndef produce():\n \n global container\n global counter\n global more_to_come\n \n for i in range(5):\n \n time.sleep(random.randrange(2, 5))\n condition.acquire()\n \n item = \"News item #\" + str(counter)\n \n container.append(item)\n counter += 1\n \n print(\"\\nProduced:\", item)\n condition.notify_all()\n \n condition.release()\n \n more_to_come = False\n\ndef consume():\n \n global more_to_come\n \n while(more_to_come):\n \n condition.acquire()\n condition.wait()\n \n time.sleep(random.random())\n print(threading.current_thread().getName(), \" acquired: \", container[-1])\n \n condition.release()\n \nproducer_thread = threading.Thread(target = produce)\n\nconsumer_one_thread = threading.Thread(target=consume, name=\"News Site One\",)\nconsumer_two_thread = threading.Thread(target=consume, name=\"News Site Two\",)\nconsumer_three_thread = threading.Thread(target=consume, name=\"News Site Three\",)\n\nthreads = [producer_thread, consumer_one_thread, consumer_two_thread, consumer_three_thread,]\n\nfor t in threads:\n t.start()\n \nfor t in threads:\n t.join()\n\ntime.sleep(1)\nprint(\"\\nAll done\")\n","sub_path":"Projects/Learning/Advancded_Python/threading/ConditionSync.py","file_name":"ConditionSync.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287293077","text":"#! python\n\nfrom math import pi\nfrom decimal import Decimal, getcontext\n\nunidade = input('Informe a unidade: ')\nraio = input('Informe o raio: ')\nraio_2 = float(raio) ** 2\n\ngetcontext().prec = 5\n\narea = (Decimal(pi)) * (Decimal(raio_2))\nprint(f'Area: {area} {unidade}')\n\nprint('Nome do módulo', __name__)\n","sub_path":"Códigos/Fundamentos/Fundamentos_projetos/area_circulo_v5.py","file_name":"area_circulo_v5.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69509278","text":"import io\nimport pytest\n\nfrom unittest import TestCase\nfrom unittest.mock import patch\n\n\n@pytest.mark.describe('Shopping List Calculator II Tests - Outputs')\nclass TestPrint(TestCase):\n\n @pytest.mark.it('Print statements are correctly formatted')\n @patch('sys.stdout', new_callable=io.StringIO)\n def test_output(self, mock_stdout):\n from p2 import (\n total,\n tax,\n total_total,\n )\n\n stdout_list = mock_stdout.getvalue().split('\\n')\n assert stdout_list[0].strip() == f\"TOTAL: ${total}\"\n assert stdout_list[1].strip() == f\"TAX: ${tax}\"\n assert stdout_list[2].strip() == f\"TOTAL TOTAL: ${total_total}\"\n\n\n@pytest.mark.describe('Shopping List Calculator II - Variables')\nclass TestShoppingListItems(TestCase):\n\n @pytest.mark.it('`total` is the sum of item_prices')\n def test_item_total(self):\n from p1 import (\n item_price_1,\n item_price_2,\n item_price_3,\n item_price_4,\n item_price_5,\n )\n\n from p2 import total\n\n assert total == pytest.approx(item_price_1 + item_price_2 +\n item_price_3 + item_price_4 + item_price_5, 0.1)\n\n @pytest.mark.it('`tax` is `total` * `TAX_RATE`')\n def test_item_tax(self):\n from p2 import (\n total,\n TAX_RATE,\n tax\n )\n\n assert tax == pytest.approx(total * TAX_RATE * 0.01, 0.1)\n\n @pytest.mark.it('`total_total` is `total` + `tax`')\n def test_item_total_total(self):\n from p2 import (\n total,\n tax,\n total_total,\n )\n\n assert total_total == pytest.approx(total + tax, 0.1)\n","sub_path":"pset_basic_data_types/shopping_list/tests/test_p2.py","file_name":"test_p2.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322055898","text":"from GaussianMixture import GMM\nimport pandas as pd\nimport numpy as np\nimport random\n\n# define column names\nnames = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']\n# names = ['pelvic incidence', 'pelvic tilt', 'lumbar lordosis angle', 'sacral slope',\n# 'pelvic radius', 'grade of spondylolisthesis', 'class']\n# names = ['id', 'clump_thickness', 'size_uniformity', 'shape_uniformity', 'marginal_adhesion', 'epithelial_size',\n# 'bare_nucleoli', 'bland_chromatin', 'normal_nucleoli', 'mitoses', 'class']\n\n# loading data\ndataset = pd.read_csv('iris.data.txt', names=names).values\n# dataset = pd.read_csv('column_3C.dat.txt', names=names).values\n# dataframe = pd.read_csv('breast-cancer-wisconsin.data.csv', names=names)\n# dataframe = dataframe.drop(['id', 'bare_nucleoli'], axis=1)\n# dataframe = pd.read_csv('dermatology.csv')\n# dataframe = dataframe.drop(['age'], axis=1)\n# dataset = dataframe.values\n\n# artificial dataset\n# features_1 = np.array([[random.uniform(-0.1, 0.1), random.uniform(-0.1, 0.1), 0] for _ in range(50)])\n# features_2 = np.array([[random.uniform(-0.1, 0.1), random.uniform(0.9, 1.1), 0] for _ in range(50)])\n# features_3 = np.array([[random.uniform(0.9, 1.1), random.uniform(-0.1, 0.1), 0] for _ in range(50)])\n# features_4 = np.array([[random.uniform(0.9, 1.1), random.uniform(0.9, 1.1), 1] for _ in range(50)])\n# dataset = np.concatenate([features_1, features_2, features_3, features_4], axis=0)\n\nbayesClassifier = GMM()\ndataset = bayesClassifier.normalize_dataset(dataset)\naccuracies = []\n\nfor j in range(0, 20):\n print(\"realization %d\" % j)\n train_X, train_y, test_X, test_y = bayesClassifier.train_test_split(dataset)\n\n separated_data = bayesClassifier.separate_by_class(train_X, train_y)\n model = {}\n for classValue, classData in separated_data.items():\n model[classValue] = []\n model[classValue] = (bayesClassifier.train_model(np.array(classData), 3, 50, 1))\n predictions = bayesClassifier.predict(test_X, model)\n accuracies.append(bayesClassifier.evaluate(test_y, predictions))\n print(bayesClassifier.confusion_matrix(test_y, predictions))\n bayesClassifier.plot_decision_boundaries(train_X, train_y, test_X, test_y, j)\n\nprint('accuracies: {}'.format(accuracies))\nprint('mean: {}'.format(np.mean(accuracies)))\nprint('std: {}'.format(np.std(accuracies)))\nbayesClassifier.show_plot_decision_boundaries()\n","sub_path":"MachineLearning/python-gaussianmix/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"588830538","text":"# -*- encoding: utf-8 -*-\n\n#--------------------------------------------#\n# Python 3\n#\n# Matheus Victor.\n#--------------------------------------------#\n#\n# Base de criptografia => Cifra de Cesar \n#\n#--------------------------------------------#\n\n# Imports\nimport sys\t# Pacotes de argumentos do sistema\n\n# Variáveis\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\nROT = 13\n\n# Criptografa\ndef encrypt(message):\n\tcrypt_character = ''\n\tfor character in message:\n\t\tif character in ALPHABET:\n\t\t\tcharacter_index = ALPHABET.index(character) # Verifica qual o indice em relação ao alfabeto\n\t\t\tcrypt_character += ALPHABET[(character_index + ROT) % len(ALPHABET)] # faz a rotação\n\t\telse:\n\t\t\tcrypt_character += character\n\tprint(crypt_character)\n\n# Descriptografa\ndef decrypt(message):\n\tcrypt_character = ''\n\tfor character in message:\n\t\tcharacter_index = ALPHABET.index(character) # Verifica qual o indice em relação ao alfabeto\n\t\tcrypt_character += ALPHABET[(character_index - ROT) % len(ALPHABET)] # faz a rotação\n\tprint(crypt_character)\n\n# Função principal\ndef main():\n\tcommand = sys.argv[1].lower()\n\tmessage = sys.argv[2].lower()\n\t\n\tif command == 'encrypt':\n\t\tencrypt(message)\n\telif command == 'decrypt':\n\t\tdecrypt(message)\n\nif __name__ == '__main__':\n\tmain()\n\t\n","sub_path":"Security/caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"261403677","text":"# Server Manager\n# This object is responsible for everything the server does\n# It receives and processes all client input, accepts new clients, and stores them properly\n# Also maintains all the different games, their states\n\nimport sys\nimport random\nimport time\nimport socket\nimport threading\n# our own custom libraries/modules\nfrom server.user.user import *\nfrom protocol.protocol import *\nfrom game.game import *\n\nclass Manager:\n\n def __init__(self):\n self.users = [] # list of users\n self.games = [] # list of games\n\n self.kill = False # kill switch\n \n self.idCounter = 1 # an id counter for assigning ids to clients\n self.gameCounter = 1 # a game id counter for assigning ids to games\n\n # return the next id to use\n def getId(self):\n self.idCounter += 1\n return self.idCounter - 1\n # return the next game id to use\n def getIdG(self):\n self.gameCounter += 1\n return self.gameCounter - 1\n # get user given a specific id\n def getUser(self, id):\n for user in self.users:\n if (user.id == id):\n return user\n return None\n # get user by id or name\n def getUser2(self, idname):\n idn = str(idname)\n try:\n user = self.getUser(int(idn))\n if (user != None):\n return user\n except Exception:\n 0\n for user in self.users:\n if (user.name == idname):\n return user\n return None\n # create a user with its given socket\n def createUser(self, sock):\n user = User(self)\n user.initSocket(sock)\n\n self.users.append(user)\n print(\"Accepted new client - client given ID \"+str(user.id))\n\n message = Protocol.message().setAction(Protocol.Action.SENDID) \\\n .setData(user.id) \\\n .build()\n user.send(message)\n # keeps clients alive by pinging them a message if no activity within 60 seconds\n def keepAlive(self):\n # pinging clients thread\n def pingClients():\n # ignore message to send to keep clients alive\n message = Protocol.message().setAction(Protocol.Action.IGNORE) \\\n .build()\n\n while True:\n time.sleep(0.1)\n\n if (self.kill == True): # if the server requested to exit\n break\n\n t = time.time()\n for user in self.users: # loop through users\n if (t - user.lastTouched > 60): # been 60 seconds since user has any activity\n user.send(message) # send ignore message\n user.lastTouched = t\n\n # create thread for waiting on clients\n t = threading.Timer(0.0, pingClients, () )\n t.start()\n\n # create a game\n def createGame(self, user1, user2):\n game = Game.createGame(user1.id, user1.name, user2.id, user2.name)\n self.games.append(game)\n game.id = self.getIdG()\n\n game.p1.user = user1\n user1.game = game\n game.p2.user = user2\n user2.game = game\n\n s = str(user1.id)+\",\"+user1.name+\",\"+str(user2.id)+\",\"+user2.name\n message = Protocol.message().setAction(Protocol.Action.STARTGAME) \\\n .setData(s) \\\n .build()\n user1.send(message)\n user2.send(message)\n print(\"Created game ID \"+str(game.id)+\" with players ID \"+str(user1.id)+\" and \"+str(user2.id))\n # get a game from a given game id\n def getGame(self, id):\n for game in self.games:\n if game.id == id:\n return game\n return None\n\n # removes a game\n def removeGame(self, game, endmessage=False):\n # if end message is true, let the game participants know a user was exited\n if (endmessage):\n message = Protocol.message().setAction(Protocol.Action.GAMEEND) \\\n .setData(-1) \\\n .build()\n game.sendMessage(message)\n\n game.cleanup() # request a cleanup from the users involved in the game\n self.games.remove(game) # remove the game from the list\n print(\"Game ID \"+str(game.id)+\" ended\")\n\n\n # process a message sent by a specific user\n def processMessage(self, user, message):\n # use the protocol class to turn the messages into objects we can understand\n ps = Protocol.process(message)\n if (isinstance(ps, list)):\n # if we got a list of protocol messages\n for p in ps:\n self.processProtocol(user, p, message)\n else:\n # if we just got a single protocol message\n self.processProtocol(user, ps, message)\n def processProtocol(self, user, protocol, message):\n p = protocol\n if (p.action == Protocol.Action.SETNAME):\n # client requested to set name\n user.name = p.data\n print(\"Set client \"+str(user.id)+\" name to \"+user.name)\n elif (p.action == Protocol.Action.GETPLAYERS):\n # client wants a list of players\n a = []\n for u in self.users:\n if (u.id == user.id or # user is the one requesting list of players\n u.game != None): # user is in game\n continue\n a.append(str(u.id)+\",\"+u.name)\n s = \",\".join(a)\n message = Protocol.message().setAction(Protocol.Action.RETURNPLAYERS) \\\n .setData(s) \\\n .build()\n user.send(message)\n elif (p.action == Protocol.Action.GETGAMES):\n # client requested list of games\n a = []\n for game in self.games:\n a.append(str(game.id)+\",\"+\\\n str(game.p1.id)+\",\"+str(game.p2.id))\n s = \",,\".join(a)\n message = Protocol.message().setAction(Protocol.Action.RETURNGAMES) \\\n .setData(s) \\\n .build()\n user.send(message)\n elif (p.action == Protocol.Action.REQUESTGAME):\n # client wants to start a game\n if (user.game != None): # already in a game\n return\n user2 = self.getUser2(p.data) # get the user the client wants to start a game with\n if (user2 == None):\n # user doesn't exist\n message = Protocol.message().setAction(Protocol.Action.PLAYERNOTFOUND) \\\n .build()\n user.send(message)\n return\n if (user2.game != None):\n # user is busy in a game\n message = Protocol.message().setAction(Protocol.Action.PLAYERREJECT) \\\n .build()\n user.send(message)\n return\n # we're good, start a game\n self.createGame(user, user2)\n elif (p.action == Protocol.Action.REQUESTOBSERVE):\n # client wants to begin observing a game\n if (user.game != None): # can't already be in a game\n return\n try:\n gameid = int(p.data) # this can raise an exception, if the clienet didn't enter an integer game id\n game = self.getGame(gameid)\n if game == None: # game doesn't exist, so raise an exception\n raise\n # found the game, observe it now\n game.obs.append(user) # add user to list of observers\n user.game = game\n # here we build a string consisting of the game data, its players, and its board state\n s = game.buildPlayers()\n s += \">\"\n s += game.buildState()\n s += \">\"\n message = Protocol.message().setAction(Protocol.Action.ACCEPTOBSERVE) \\\n .setData(s) \\\n .build()\n user.send(message)\n except Exception:\n # something went wrong, let the client know can't observe\n message = Protocol.message().setAction(Protocol.Action.FAILOBSERVE) \\\n .build()\n user.send(message)\n elif (p.action == Protocol.Action.ENDOBSERVE):\n # client wants to stop observing\n if user.game == None:\n return\n user.game.obs.remove(user) # remove from observer list\n user.game = None\n elif (p.action == Protocol.Action.MAKEMOVE):\n # client wants to make a move\n if (user.game == None):\n return\n game = user.game\n\n if (game.inGame(user.id)):\n # attempt to make a move with the coordinates provided\n coord = p.data.split(\",\")\n x = int(coord[0])\n y = int(coord[1])\n res = game.makeMove(user.id, x, y)\n else:\n # client is just observing\n res = \"You aren't in the game\"\n\n if (res != True):\n # if result isn't true, the move wasn't successfully made\n message = Protocol.message().setAction(Protocol.Action.BADMOVE) \\\n .setData(res) \\\n .build()\n user.send(message)\n else:\n # the move was successfully made, let players know game state was updated\n message = Protocol.message().setAction(Protocol.Action.GAMEUPDATE) \\\n .setData(str(user.id)+\",\"+p.data) \\\n .build()\n game.sendMessage(message)\n\n res = game.getResult() # get the result of the current board to see if game is over\n if (res > -1):\n # game over\n uid = 0 # draw\n if res == 1: # p1 won\n uid = game.p1.id\n if res == 2: # p2 won\n uid = game.p2.id\n message = Protocol.message().setAction(Protocol.Action.GAMEEND) \\\n .setData(uid) \\\n .build()\n game.sendMessage(message)\n # remove the game\n self.removeGame(game)\n elif (p.action == Protocol.Action.MESSAGESEND):\n # client wants to send a message to everybody in the game\n if (user.game == None):\n return\n message = Protocol.message().setAction(Protocol.Action.MESSAGEUPDATE) \\\n .setData(str(user.id)+\",\"+user.name+\",\"+p.data) \\\n .build()\n user.game.sendMessage(message, user)\n else:\n print(\"Got unknown message:\", message)\n\n # removes a user\n def removeUser(self, user):\n if (self.kill):\n return\n self.users.remove(user)\n print(\"Client \"+str(user.id)+\" disconnected\")\n # if in a game, end it\n if (user.game != None):\n if user.game.inGame(user.id): # player in game, end it\n self.removeGame(user.game, True)\n else: # just an observer\n user.game.obs.remove(user)\n\n\n # close\n def close(self):\n message = Protocol.message().setStatusCode(Protocol.Status.CLOSE) \\\n .build()\n for user in self.users[:]:\n user.send(message)\n user.sock.close()\n\n\n\n\n\n","sub_path":"tictactwo/server/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":11961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289721840","text":"# from multiprocessing import Pool\r\n# import time\r\n\r\n# COUNT = 50000000\r\n# def countdown(n):\r\n# while n>0:\r\n# n -= 1\r\n\r\n# if __name__ == '__main__':\r\n# pool = Pool(processes=2)\r\n# start = time.time()\r\n# r1 = pool.apply_async(countdown, [COUNT//2])\r\n# r2 = pool.apply_async(countdown, [COUNT//2])\r\n# pool.close()\r\n# pool.join()\r\n# end = time.time()\r\n# print('Time taken in seconds -', end - start)\r\n\r\nimport time\r\nfrom timeit import default_timer as timer\r\nfrom multiprocessing import Pool, cpu_count\r\n\r\n\r\ndef square(n):\r\n\r\n time.sleep(2)\r\n\r\n return n * n\r\n\r\n\r\ndef main():\r\n\r\n start = timer()\r\n\r\n print(f'starting computations on {cpu_count()} cores')\r\n\r\n values = (2, 4, 6, 8)\r\n\r\n with Pool() as pool:\r\n res = pool.map(square, values)\r\n print(res)\r\n\r\n end = timer()\r\n print(f'elapsed time: {end - start}')\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"dev_test/multiprocessing_test.py","file_name":"multiprocessing_test.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642048536","text":"from numpy import *\nfrom MoonMap import MoonMap\n\n# 任务介绍:\n# 小行星探测器在小行星上跳跃行走,目标点始终设定为原点。\n# 输入网络的地图为32*32,每像素代表4m*4m的区域,即总共128m*128m的区域\n# 为方便网络对地图的理解,设定达到原点附近的半径为8的区域就视为到达目标\n# agent-env交互方案:\n# agent接收探测器所有角点均离开地面时的状态和相应的global_map,local_map;输出期望的姿态角速度\n# env接收agent的action后,无控仿真至碰撞,然后按此时期望姿态下是否有角点在地面以下,向前或向后搜索碰前状态,\n\n\nACTION_DIM = 3\nSTATE_DIM = 16\n\n# 地图参数\nMAP_DIM = 32\nGLOBAL_PIXEL_METER = 4\nLOCAL_PIXEL_METER = 1\n\n# 小行星与探测器的相关参数\ng = array([0, 0, -0.001])\nI_star = array([[0.055, 0, 0], [0, 0.055, 0], [0, 0, 0.055]])\nI_star_inv = array([[1 / 0.055, 0, 0], [0, 1 / 0.055, 0], [0, 0, 1 / 0.055]])\nU = eye(3)\nJ_wheel = array([[0.002, 0, 0], [0, 0.002, 0], [0, 0, 0.002]])\nUJ_inv = array([[500, 0, 0], [0, 500, 0], [0, 0, 500]])\nm = 5\nl_robot = array([0.2, 0.2, 0.2])\nmu = 0.45\n# k:地面刚度数据,有待考证\nk = 4.7384 * 10 ** 4\nrecovery_co = 0.95\n# mu0:静摩擦系数\nmu0 = 0.48\nlx = l_robot[0]\nly = l_robot[1]\nlz = l_robot[2]\n# vertex_b : 体坐标系下初始各角点相对质心的位置,dim:3*8\nvertex_b = array([[lx, lx, lx, lx, -lx, -lx, -lx, -lx],\n [-ly, -ly, ly, ly, -ly, -ly, ly, ly],\n [-lz, lz, lz, -lz, -lz, lz, lz, -lz]])\nMIN_ENERGY = 0.001\nMAX_VXY = 1.5\nMAX_VZ = 0.2\n\n# RK4算法参数\nSTEP_LENGTH = 0.001\n\n\ndef wheel_model(M, w):\n flag = abs(w) >= 100\n w[flag] = 0\n M = minimum(0.1, maximum(-0.1, M))\n return M, w\n\n\n# check: OK\ndef mat_q(q):\n mq = array([[q[0], -q[1], -q[2], -q[3]],\n [q[1], q[0], -q[3], q[2]],\n [q[2], q[3], q[0], -q[1]],\n [q[3], -q[2], q[1], q[0]]])\n return mq\n\n\n# check:OK\ndef crossMatrix(w):\n wx = array([[0, -w[2], w[1]],\n [w[2], 0, -w[0]],\n [-w[1], w[0], 0]])\n return wx\n\n\n# check:OK\n# 四元数转换为姿态余弦矩阵\ndef q_to_DCM(q):\n a = q[0] * eye(3) - crossMatrix(q[1:4])\n DCM = dot(reshape(q[1:4], [-1, 1]), reshape(q[1:4], [1, -1])) + dot(a, a)\n return DCM\n\n\n# check:OK\n# 计算惯性系下的各角点参数\ndef vertex(terrain_map, state):\n XYZc, v, q, w = state[0:3], state[3:6], state[6:10], state[10:13]\n q /= sqrt(q.dot(q))\n DCM = q_to_DCM(q)\n vertex_s = dot(DCM.T, vertex_b) + reshape(XYZc, [-1, 1])\n vertex_high = vertex_s[2, :] - terrain_map.get_high(vertex_s[0, :], vertex_s[1, :])\n vertex_v = dot(DCM.T, dot(crossMatrix(w), vertex_b)) + reshape(v, [-1, 1])\n return vertex_s, vertex_high, vertex_v\n\n\n# check:OK\n# 动力学微分方程,flag标记是否发生碰撞,true为在碰撞,\ndef dynamic(terrain_map, state, M_wheel=zeros(3), flag=ones([8]) < 0, v0=zeros(8), normal=ones([3, 8])):\n XYZc, v, q, w, w_wheel = state[0:3], state[3:6], state[6:10], state[10:13], state[13:16]\n q /= sqrt(q.dot(q))\n M_wheel, w_wheel = wheel_model(M_wheel, w_wheel)\n d_w_wheel = UJ_inv.dot(M_wheel)\n F = zeros([3, 8])\n T = zeros([3, 8])\n DCM = q_to_DCM(q)\n vertex_s, vertex_high, vertex_v = vertex(terrain_map, state)\n Teq = cross(w, I_star.dot(w) + U.dot(J_wheel).dot(w_wheel)) + U.dot(J_wheel).dot(d_w_wheel)\n for j in range(0, 8):\n if flag[j]:\n r_one = vertex_b[:, j]\n high = vertex_high[j]\n normal_one = normal[:, j]\n invade_s = -dot(array([0, 0, high]), normal_one)\n if invade_s < 0:\n continue\n vertex_v_one = vertex_v[:, j]\n invade_v = -dot(vertex_v_one, normal_one)\n vt = vertex_v_one - dot(vertex_v_one, normal_one) * normal_one\n vt_value = sqrt(dot(vt, vt))\n if abs(v0[j]) < 0.00001:\n v0[j] = 0.00001 * sign(v0[j])\n c = 0.75 * (1 - recovery_co ** 2) * k * (invade_s ** 1.5) / v0[j]\n Fn_value = k * (invade_s ** 1.5) + c * invade_v\n if Fn_value < 1e-8:\n Fn_value = 1e-8\n Fn = Fn_value * normal_one\n if vt_value >= 0.0006:\n Ft = -mu * Fn_value * vt / vt_value\n else:\n # 具体方程及求解过程见 笔记\n\n A = eye(3) / m - linalg.multi_dot([crossMatrix(r_one), I_star_inv, crossMatrix(r_one), DCM])\n A_inv = linalg.inv(A)\n b = crossMatrix(r_one).dot(I_star_inv).dot(Teq) + dot(w, r_one) * w - dot(w, w) * r_one\n alpha = (Fn.dot(Fn) + A_inv.dot(b).dot(Fn)) / (A_inv.dot(Fn).dot(Fn))\n Ft = -A_inv.dot(dot(A - alpha * eye(3), Fn) + b)\n Ft_value = sqrt(Ft.dot(Ft))\n if Ft_value >= mu0 * Fn_value:\n Ft = mu0 * Fn_value * Ft / Ft_value\n F[:, j] = Ft + Fn\n T[:, j] = cross(r_one, DCM.dot(Ft + Fn))\n F = sum(F, 1) + m * g\n T = sum(T, 1)\n M_star = T - Teq\n d_XYZc = v\n d_v = F / m\n d_q = 0.5 * dot(mat_q(q), concatenate((zeros(1), w)))\n d_w = I_star_inv.dot(M_star)\n d_state = concatenate((d_XYZc, d_v, d_q, d_w, d_w_wheel))\n return d_state\n\n\n# check:OK\ndef RK4(terrain_map, t, state, step_length, M_wheel=zeros(3), flag=ones([8]) < 0, v0=zeros(8), normal=ones([3, 8])):\n h = step_length\n k1 = dynamic(terrain_map, state, M_wheel, flag, v0, normal)\n k2 = dynamic(terrain_map, state + h * k1 / 2, M_wheel, flag, v0, normal)\n k3 = dynamic(terrain_map, state + h * k2 / 2, M_wheel, flag, v0, normal)\n k4 = dynamic(terrain_map, state + h * k3, M_wheel, flag, v0, normal)\n state += h * (k1 + 2 * k2 + 2 * k3 + k4) / 6\n state[6:10] /= linalg.norm(state[6:10])\n t += h\n return t, state\n\n\nclass Env:\n s_dim = STATE_DIM\n a_dim = ACTION_DIM\n a_bound = 0.1*ones(a_dim)\n\n def __init__(self):\n self.t = 0\n self.t0 = 0\n self.state = array([0, 0, 5, 0.12, -0.08, 0, 1, 0, 0, 0, 0.2, -0.1, 0.15, -1.9, 1.5, -1.2])\n self.state0 = self.state.copy()\n self.terrain_map = MoonMap(3, MAP_DIM, GLOBAL_PIXEL_METER)\n self.map_seed = 3\n self.r_obj = MAP_DIM * GLOBAL_PIXEL_METER / 3\n\n def cut_r_obj(self):\n self.r_obj = max(self.r_obj / 3, GLOBAL_PIXEL_METER)\n\n # 生成地图\n def set_map_seed(self, sd=1):\n self.map_seed = sd\n self.terrain_map = MoonMap(sd, MAP_DIM, GLOBAL_PIXEL_METER)\n\n # check:\n # 设定初始状态,即探测器与地面的撞前状态\n # 暂时不设定难度,(根据初始xy坐标与原点(目标)的距离,分10个难度,默认为最高难度)\n def set_state_seed(self, sd=1):\n random.seed(sd)\n minXY = self.r_obj + 3 * GLOBAL_PIXEL_METER\n maxXY = MAP_DIM * GLOBAL_PIXEL_METER / 2 - 3 * GLOBAL_PIXEL_METER\n minVxy = 0.05\n maxVxy = 0.2\n XY_theta = random.random() * 2 * pi\n XY = ((maxXY - minXY) * random.random() + minXY) * array([cos(XY_theta), sin(XY_theta)])\n v_theta = random.random() * 2 * pi\n v_xy = ((maxVxy - minVxy) * random.random() + minVxy) * array([cos(v_theta), sin(v_theta)])\n vz = 0.07 * random.random() + 0.03\n q = random.rand(4)\n q /= linalg.norm(q)\n w = random.rand(3) - 0.5\n w_wheel = random.rand(3) * 2 - 1\n state_syn = concatenate([XY, zeros(1), v_xy, array([vz]), q, w, w_wheel])\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, state_syn)\n zf = -min(vertex_high) + 1e-8\n\n self.state = concatenate([XY, array([zf]), v_xy, array([vz]), q, w, w_wheel])\n self.t = 0\n self.state0 = self.state.copy()\n return self.map_seed, self.observe_state(), self.terrain_map.map_matrix, self.terrain_map.get_local_map(self.state[0:2])\n\n # check:\n # step env接收agent的action后的状态转移\n # 输入action即碰前角速度与姿态,输出新的state,reward以及标志该次仿真是否达到目的地的done,是否速度过小导致停止的stop\n # 先按假想的无控进行仿真,若探测器在空中时间小于MIN_FLY_TIME,按无控进行仿真\n # ?探测器在空中角动量守恒,应该可以计算出与action对应的飞轮转速?\n def step(self, act):\n t0 = self.t\n state0 = self.state.copy()\n flag, v0, normal = self.controlSim(act)\n pre_energy = self.energy()\n self.collisionSim(flag, v0, normal)\n after_energy = self.energy()\n loss_energy = pre_energy - after_energy\n if loss_energy <= 0:\n raise Exception(\"Energy improved!\")\n stop_bool = self.energy() < MIN_ENERGY\n over_map = (abs(self.state[0:2]) > (MAP_DIM * GLOBAL_PIXEL_METER - GLOBAL_PIXEL_METER)).any()\n over_speed = linalg.norm(self.state[3:5]) > MAX_VXY or linalg.norm(self.state[5]) > MAX_VZ\n done_bool = (abs(self.state[0:2]) < self.r_obj/2).all()\n reward_value = self.reward(done_bool, stop_bool, state0, t0, over_speed, over_map)\n return self.observe_state(), self.terrain_map.get_local_map(self.state[0:2]), reward_value, done_bool or stop_bool or over_map\n\n # check:\n # 碰撞仿真,直至所有顶点均与地面脱离\n # 更新t,state\n def collisionSim(self, flag, v0, normal):\n if not flag.any():\n raise Exception(\"Invalid collisionSim!\")\n while flag.any():\n self.t, self.state = RK4(self.terrain_map, self.t, self.state, STEP_LENGTH, zeros(3), flag, v0, normal)\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n slc1 = logical_and(flag, vertex_high > 0)\n flag[slc1] = False\n v0[slc1] = 0\n slc2 = logical_and(logical_not(flag), vertex_high <= 0)\n flag[slc2] = True\n normal[:, slc2] = self.terrain_map.get_normal(vertex_s[0, slc2], vertex_s[1, slc2])\n v0[slc2] = -sum(vertex_v[:, slc2] * normal[:, slc2], 0)\n\n # check:\n # 模拟无控仿真,直至有顶点与地面接触\n # 更新t,state,并返回进行碰撞仿真所需参数flag(碰撞标志),v0(碰撞点初始速度),normal(碰撞点初始法向量)\n # 额外返回这一段的仿真时长即探测器在空中的时间\n def controlSim(self, act):\n dw = act.copy()\n\n v0 = zeros(8)\n last_t, last_state = self.t, self.state.copy()\n flag = ones(8) < 0\n normal = ones([3, 8])\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n if (vertex_high <= 0).any():\n raise Exception(\"Invalid controlSim!\")\n # 先按0.1s的间隔仿真,找到碰撞的大致时间\n while (vertex_high > 0).all():\n last_t, last_state = self.t, self.state.copy()\n w, w_wheel = self.state[10:13], self.state[13:16]\n M_wheel = -I_star.dot(dw) - cross(w, I_star.dot(w) + U.dot(J_wheel).dot(w_wheel))\n self.t, self.state = RK4(self.terrain_map, self.t, self.state, STEP_LENGTH * 100, M_wheel)\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n # 再回到碰撞前,按0.001s的间隔仿真\n self.t, self.state = last_t, last_state.copy()\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n while (vertex_high > 0).all():\n w, w_wheel = self.state[10:13], self.state[13:16]\n M_wheel = -I_star.dot(dw) - cross(w, I_star.dot(w) + U.dot(J_wheel).dot(w_wheel))\n self.t, self.state = RK4(self.terrain_map, self.t, self.state, STEP_LENGTH, M_wheel)\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n slc = vertex_high <= 0\n flag[slc] = True\n normal[:, slc] = self.terrain_map.get_normal(vertex_s[0, slc], vertex_s[1, slc])\n v0[slc] = -sum(vertex_v[:, slc] * normal[:, slc], 0)\n if (v0 < 0).any():\n raise Exception(\"Invalid v0!\")\n return flag, v0, normal\n\n # 输出强化学习的state\n def observe_state(self):\n o_s = self.state.copy()\n o_s[0:2] /= (MAP_DIM * GLOBAL_PIXEL_METER / 2)\n o_s[0:2] = minimum(maximum(o_s[0:2], -1), 1-1e-3)\n o_s[-3:] /= 200\n o_s[10:13] /= 2\n return o_s\n\n def reward(self, done_bool, stop_bool, pre_state, pre_t, over_speed, over_map):\n def _cos_vec(a, b):\n f = dot(a, b) / (linalg.norm(a) * linalg.norm(b))\n return f\n\n if done_bool:\n reward_value = 10\n elif over_map:\n reward_value = -3\n elif stop_bool:\n reward_value = (linalg.norm(self.state0[0:2]) - linalg.norm(self.state[0:2])) / \\\n max(linalg.norm(self.state0[0:2]), linalg.norm(self.state[0:2]))\n elif over_speed:\n reward_value = -2\n else:\n d = (linalg.norm(pre_state[0:2]) - linalg.norm(self.state[0:2])) / \\\n max(linalg.norm(pre_state[0:2]), linalg.norm(self.state[0:2]))\n c_pre = _cos_vec(-pre_state[0:2], pre_state[3:5])\n c = _cos_vec(-self.state[0:2], self.state[3:5])\n v_xy = linalg.norm(self.state[3:5])\n reward_value = (c - c_pre) + (v_xy*c - v_xy*sqrt(1-c**2)) + d - 0.0001 * (self.t - pre_t)\n return reward_value\n\n def energy(self):\n v, w = self.state[3:6], self.state[10:13]\n eg = 0.5*m*dot(v, v) + 0.5*reshape(w, [1, 3]).dot(I_star).dot(w)\n return eg\n\n\nif __name__ == '__main__':\n env = Env()\n env.cut_r_obj()\n env.cut_r_obj()\n for i in range(10):\n ep_reward = 0\n ave_dw = 0\n r = 0\n step = 0\n sed = random.randint(1, 10000)\n env.set_map_seed(sed)\n env.set_state_seed(sed)\n for step in range(200):\n action = random.rand(3)*env.a_bound*2 - env.a_bound\n ave_dw += linalg.norm(action)\n next_s, lm, r, done = env.step(action)\n ep_reward += r\n print(r, done)\n if done:\n break\n print(\"episode: %10d ep_reward:%10.5f last_reward:%10.5f ave_w:%10.5f\" % (\n i, ep_reward, r, ave_dw / (step + 1)))\n","sub_path":"env_plan2.py","file_name":"env_plan2.py","file_ext":"py","file_size_in_byte":14273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"130888566","text":"\"\"\"\nDatabase models of common objects\n\nauthor: officialcryptomaster@gmail.com\n\"\"\"\nfrom decimal import Decimal\nfrom enum import Enum\nfrom zero_ex.json_schemas import assert_valid\nfrom pydex_app.database import PYDEX_DB as db\nfrom pydex_app.constants import NULL_ADDRESS\nfrom pydex_app.constants import ZERO_STR, MAX_INT_STR\nfrom utils.zeroexutils import ZeroExWeb3Client\nfrom utils.miscutils import try_, now_epoch_msecs, epoch_secs_to_local_time_str, epoch_msecs_to_local_time_str\n\n\nclass OrderStatus(Enum):\n \"\"\"Enumeration of order statuses.\n Guarantees that:\n - 0 means there is no obvious problems but it may be unfundable\n - positive status means order is confirmed to be fillable\n - negative status means order is confirmed to not be fillable\n \"\"\"\n INVALID = -10 # We will probably never insert these into the database\n UNFILLABLE_UNFUNDED = -7\n UNFILLABLE_CANCELLED_PARTIALLY_FILLED = -6\n UNFILLABLE_CANCELLED = -5\n UNFILLABLE_EXPIRED_PARTIALLY_FILLED = -4\n UNFILLABLE_EXPIRED = -3\n UNFILLABLE_FILLED = -2\n UNFILLABLE = -1\n MAYBE_FILLABLE = 0\n FILLABLE = 1\n FILLABLE_FULLY = 2\n FILLABLE_PARTIALLY = 3\n\n\nclass SignedOrder(db.Model):\n \"\"\"SignedOrder model which provides persistence and convenience\n methods around dealing with 0x SignedOrder type\n \"\"\"\n hash = db.Column(db.String(42), unique=True, primary_key=True) # pylint: disable=no-member\n # ETH addresses are 40 bytes (add 2 more bytes for leading '0x')\n maker_address = db.Column(db.String(42), nullable=False) # pylint: disable=no-member\n taker_address = db.Column(db.String(42), default=NULL_ADDRESS) # pylint: disable=no-member\n exchange_address = db.Column(db.String(42), nullable=False) # pylint: disable=no-member\n fee_recipient_address = db.Column(db.String(42), default=NULL_ADDRESS) # pylint: disable=no-member\n sender_address = db.Column(db.String(42), default=NULL_ADDRESS) # pylint: disable=no-member\n # in theory, amounts can be 32 bytes, in practive, we will only allow 16 bytes\n maker_asset_amount = db.Column(db.String(32), nullable=False) # pylint: disable=no-member\n taker_asset_amount = db.Column(db.String(32), nullable=False) # pylint: disable=no-member\n # while in theory fees can be 32 bytes, in practice, we will allow 16 bytes\n maker_fee = db.Column(db.String(32), default=\"0\") # pylint: disable=no-member\n taker_fee = db.Column(db.String(32), default=\"0\") # pylint: disable=no-member\n # salt is 32 bytes or 256 bits which is at most 78 chars in decimal\n salt = db.Column(db.String(78), nullable=False) # pylint: disable=no-member\n # integer seconds since unix epoch (interpret as UTC timestamp)\n expiration_time_secs = db.Column(db.Integer, nullable=False) # pylint: disable=no-member\n # asset data for ERC20 is 36 bytes, and 68 bytes for ERC721, so that is a\n # maximum of 132 hex chars plus 2 chars for the leading '0x'\n maker_asset_data = db.Column(db.String(134), nullable=False) # pylint: disable=no-member\n taker_asset_data = db.Column(db.String(134), nullable=False) # pylint: disable=no-member\n signature = db.Column(db.String(256), nullable=False) # pylint: disable=no-member\n bid_price = db.Column(db.String(32)) # pylint: disable=no-member\n ask_price = db.Column(db.String(32)) # pylint: disable=no-member\n # integer milliseconds since unix epoch when record was created (interpret as UTC timestamp)\n created_at = db.Column(db.Integer, # pylint: disable=no-member\n nullable=False,\n default=now_epoch_msecs)\n # integer milliseconds since unix epoch since last update to record (interpret as UTC timestamp)\n last_updated_at = db.Column(db.Integer, # pylint: disable=no-member\n nullable=False,\n default=now_epoch_msecs,\n onupdate=now_epoch_msecs)\n # integer status from `OrderStatus` enum.\n order_status = db.Column(db.Integer, # pylint: disable=no-member\n index=True,\n nullable=False,\n default=OrderStatus.MAYBE_FILLABLE.value)\n # cumulative taker fill amount from order that has actually been filled\n fill_amount = db.Column(db.String(32)) # pylint: disable=no-member\n _sort_price = None # not a DB column\n\n def __str__(self):\n return (\n f\"[SignedOrder](hash={self.hash}\"\n f\" | order_status={try_(OrderStatus, self.order_status)}\"\n f\" | bid_price={self.bid_price}\"\n f\" | ask_price={self.ask_price}\"\n f\" | maker_asset_amount={self.maker_asset_amount}\"\n f\" | taker_asset_amount={self.taker_asset_amount}\"\n f\" | maker_asset_data={self.maker_asset_data}\"\n f\" | taker_asset_data={self.taker_asset_data}\"\n f\" | maker_address={self.maker_address}\"\n f\" | taker_address={self.taker_address}\"\n f\" | expires={try_(epoch_secs_to_local_time_str, self.expiration_time_secs)}\"\n f\" | create_at={try_(epoch_msecs_to_local_time_str, self.created_at)}\"\n f\" | last_updated_at={try_(epoch_msecs_to_local_time_str, self.last_updated_at)}\"\n )\n\n __repr__ = __str__\n\n def to_json(\n self,\n include_hash=False,\n include_signature=True,\n ):\n \"\"\"Get a json representation of the SignedOrder\"\"\"\n order = {\n \"makerAddress\": self.maker_address,\n \"takerAddress\": self.taker_address,\n \"makerFee\": self.maker_fee,\n \"takerFee\": self.taker_fee,\n \"senderAddress\": self.sender_address,\n \"makerAssetAmount\": self.maker_asset_amount,\n \"takerAssetAmount\": self.taker_asset_amount,\n \"makerAssetData\": self.maker_asset_data,\n \"takerAssetData\": self.taker_asset_data,\n \"exchangeAddress\": self.exchange_address,\n \"salt\": self.salt,\n \"feeRecipientAddress\": self.fee_recipient_address,\n \"expirationTimeSeconds\": self.expiration_time_secs,\n }\n if include_hash:\n if not self.hash:\n self.update_hash()\n order[\"hash\"] = self.hash\n if include_signature:\n order[\"signature\"] = self.signature\n return order\n\n def update_bid_ask_prices(self):\n \"\"\"Update the bid and ask prices and return the order for chaining\"\"\"\n self.update_bid_price()\n self.update_ask_price()\n return self\n\n def update_hash(self):\n \"\"\"Update the hash of the order and return the order for chaining\"\"\"\n self.hash = self.get_order_hash(self)\n return self\n\n def update(self):\n \"\"\"Ensure any fields that need calculation are updated\n TODO(CM): consider making use of properties to make this more convenient\n \"\"\"\n self.update_bid_ask_prices()\n self.update_hash()\n return self\n\n def update_bid_price(self, default_price=ZERO_STR):\n \"\"\"Bid price is price of taker asset per unit of maker asset\n (i.e. price of taker asset which maker is bidding to buy)\n \"\"\"\n try:\n self.bid_price = \"{:.18f}\".format(\n Decimal(self.taker_asset_amount) / Decimal(self.maker_asset_amount))\n except: # noqa E722 pylint: disable=bare-except\n self.bid_price = default_price\n return self\n\n def update_ask_price(self, default_price=MAX_INT_STR):\n \"\"\"Ask price is price of maker asset per unit of taker asset\n (i.e. price of maker asset the maker is asking to sell)\n \"\"\"\n try:\n self.ask_price = \"{:.18f}\".format(\n Decimal(self.maker_asset_amount) / Decimal(self.taker_asset_amount))\n except: # noqa E722 pylint: disable=bare-except\n self.ask_price = default_price\n return self\n\n @property\n def sort_price(self):\n \"\"\"Get a price for sorting orders\n This is useful for full set order which result in a mix of bids and asks\n (hint: make use of `set_bid_price_as_sort_price` and its equivalent\n `set_bid_price_as_sort_price`)\n \"\"\"\n return self._sort_price\n\n def set_bid_as_sort_price(self):\n \"\"\"Set the self._sort_price field to be the self.bid_price\n This can be useful for sorting full set orders\n \"\"\"\n self._sort_price = self.bid_price\n return self\n\n def set_ask_as_sort_price(self):\n \"\"\"Set the self._sort_price field to be the self.ask_price\n This can be useful for sorting full set orders\n \"\"\"\n self._sort_price = self.ask_price\n return self\n\n @classmethod\n def get_order_hash(cls, signed_order):\n \"\"\"Returns hex string hash of 0x SignedOrder object\"\"\"\n return ZeroExWeb3Client.get_order_hash(signed_order.to_json())\n\n @classmethod\n def from_json(\n cls,\n order_json,\n check_validity=False,\n include_signature=True,\n ):\n \"\"\"Given a json representation of a signed order, return a SignedOrder object\n\n Keyword arguments:\n order_json -- a dict conforming to \"/signedOrderSchema\" or \"/orderSchema\"\n (dependign on whether `include_signature` is set to True or False)\n schemas can be found at:\n <https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas/schemas>\n check_validity -- whether we should do an explicit check to make sure the\n passed in dict adheres to the required schema (default: True)\n include_signature -- whether the object is expected to have the signature on it\n or not. This will affect whether \"/signedOrderSchema\" or \"/orderSchema\" is\n used for validation (default: True)\n \"\"\"\n order = cls()\n if check_validity:\n if include_signature:\n assert_valid(order_json, \"/signedOrderSchema\")\n else:\n assert_valid(order_json, \"/orderSchema\")\n order.maker_address = order_json[\"makerAddress\"]\n order.taker_address = order_json[\"takerAddress\"]\n order.maker_fee = order_json[\"makerFee\"]\n order.taker_fee = order_json[\"takerFee\"]\n order.sender_address = order_json[\"senderAddress\"]\n order.maker_asset_amount = order_json[\"makerAssetAmount\"]\n order.taker_asset_amount = order_json[\"takerAssetAmount\"]\n order.maker_asset_data = order_json[\"makerAssetData\"]\n order.taker_asset_data = order_json[\"takerAssetData\"]\n order.salt = order_json[\"salt\"]\n order.exchange_address = order_json[\"exchangeAddress\"]\n order.fee_recipient_address = order_json[\"feeRecipientAddress\"]\n order.expiration_time_secs = order_json[\"expirationTimeSeconds\"]\n if include_signature:\n order.signature = order_json[\"signature\"]\n order.update()\n return order\n","sub_path":"src/pydex_app/db_models.py","file_name":"db_models.py","file_ext":"py","file_size_in_byte":11014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"575377063","text":"# GIT utilities\nimport logging\nfrom contextlib import contextmanager\n\nfrom git import Repo\n\nlog = logging.getLogger(__name__)\n\n\ndef find_root():\n \"\"\"Based on the current directory, look for a .menhir_root.yaml file.\"\"\"\n from os.path import dirname\n from .fileutils import find_file_in_parents\n root = find_file_in_parents(\".git\")\n if root:\n return dirname(root)\n\n\ndef repo(base_dir=None):\n \"\"\"Return a repository object.\"\"\"\n base_dir = base_dir or find_root()\n return Repo(base_dir)\n\n\ndef commit(repo, commitish):\n \"\"\"Return a commit object.\"\"\"\n return repo.commit(commitish)\n\n\ndef commit_cached(repo, *args):\n \"\"\"Commit cached files.\"\"\"\n repo.git.commit(*args)\n\n\ndef head_commit(repo):\n \"\"\"Return a commit object.\"\"\"\n return repo.head.commit\n\n\ndef diff(start, end):\n \"\"\"Diff for the commit range.\"\"\"\n return diff_paths(start.diff(end))\n\n\ndef dirty_files(repo):\n return diff_paths(repo.index.diff(None))\n\n\ndef staged_files(repo):\n return diff_paths(repo.index.diff(\"HEAD\"))\n\n\ndef uncommited_files(repo):\n dirty = repo.index.diff(None)\n dirty.extend(repo.index.diff(\"HEAD\"))\n return diff_paths(dirty)\n\n\ndef unstaged_files(repo):\n dirty = repo.index.diff(None)\n dirty.extend(repo.index.diff(\"HEAD\"))\n return diff_paths(dirty)\n\n\ndef files_changed_since(repo, commitish):\n dirty = repo.index.diff(None)\n dirty.extend(repo.index.diff(commitish))\n return diff_paths(dirty)\n\n\ndef diff_paths(diff):\n rpaths = [p.a_path for p in diff.iter_change_type('R')]\n rpaths.extend([p.b_path for p in diff.iter_change_type('R')])\n\n diffs = {\n 'added': [p.b_path for p in diff.iter_change_type('A')],\n 'deleted': [p.a_path for p in diff.iter_change_type('D')],\n 'renamed': rpaths,\n 'modified': [p.b_path for p in diff.iter_change_type('M')],\n }\n all_paths = []\n for i in ['added', 'deleted', 'renamed', 'modified']:\n all_paths.extend(diffs[i])\n diffs['all'] = all_paths\n return diffs\n\n\ndef changed_files(start, end):\n from menhir import gitutils\n repo = gitutils.repo()\n start_commit = gitutils.commit(repo, start)\n end_commit = gitutils.commit(repo, end)\n changed_files = gitutils.diff(start_commit, end_commit)\n return changed_files\n\n\ndef sha(commit):\n \"\"\"Return the sha hex for a commit.\"\"\"\n return commit.hexsha\n\n\ndef branch(repo):\n \"\"\"Return the branch name.\"\"\"\n return repo.active_branch.name\n\n\n@contextmanager\ndef staged_as_committed(repo):\n staged_changes = staged_files(repo)\n log.debug('staged_changes %s', staged_changes)\n\n commit_changes = False\n if len(staged_changes['all']):\n commit_cached(repo, \"-m\", \"temp\", \"-n\")\n commit_changes = True\n\n try:\n yield\n finally:\n if commit_changes:\n repo.git.reset(\"HEAD^\", soft=True)\n\n\n@contextmanager\ndef stashed_changes(repo):\n uncommitted_changes = uncommited_files(repo)\n log.debug('uncommitted_changes %s', uncommitted_changes)\n stash_changes = False\n\n if len(uncommitted_changes['all']):\n stash_changes = True\n repo.git.stash('save', \"--quiet\", \"--include-untracked\")\n try:\n yield\n finally:\n if stash_changes:\n repo.git.stash('pop', \"--quiet\")\n","sub_path":"menhir/gitutils.py","file_name":"gitutils.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"451563226","text":"#!/usr/bin/env python3\n\n# Created by: Mr. Coxall\n# Created on: October 2019\n# This file is the B scene\n# for CircuitPython and uGame\n\nimport ugame\nimport stage\n\nimport menu_scene\n\ndef game_loop():\n # this function is a scene\n\n # an image bank for CircuitPython\n image_bank_1 = stage.Bank.from_bmp16(\"space_aliens.bmp\")\n\n # sets the background to image 0 in the bank\n # we will not change the background after initially drawing it\n background = stage.Grid(image_bank_1, 160, 120)\n\n # a list of sprites that will be updated every frame\n sprites = []\n\n # create a sprite\n # parameters (image_bank, image # in bank, x, y)\n #alien = stage.Sprite(image_bank_1, 9, 80-8, 60-8)\n #sprites.append(alien)\n\n # show text on screen\n text = stage.Text(width = 29, height = 1)\n text.move(30, 110)\n text.text(\"B\")\n\n # create a stage for the background to show up on\n # and set the frame rate to 30fps\n game = stage.Stage(ugame.display, 30)\n # set the layers, items show up in order\n game.layers = [text] + sprites + [background]\n # render the background and inital location of sprite list\n # most likely you will only render background once per scene\n game.render_block()\n\n # repeat forever, game loop\n while True:\n # get user input\n keys = ugame.buttons.get_pressed()\n\n # update game logic\n if keys & ugame.K_SELECT != 0: # Select button\n menu_scene.game_loop()\n\n\n # redraw sprite list\n game.render_sprites(sprites)\n game.tick() # wait until refresh rate finishes\n\n\nif __name__ == \"__main__\":\n game_loop()","sub_path":"b_scene.py","file_name":"b_scene.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"357503256","text":"from groundwork.patterns import GwDocumentsPattern, GwCommandsPattern\n\ncommands_content = \"\"\"\nCommands overview\n=================\n\nRegistered commands: {{app.commands.get()|count}}\n\nList of commands\n----------------\n\n {% for name, command in app.commands.get().items() %}\n * {{command.command-}}\n {% endfor %}\n\n{% for name, command in app.commands.get().items() %}\n{{command.command}}\n{{\"-\" * command.command|length}}\nName: {{command.command}}\nDescription: {{command.description}}\nPlugin: {{command.plugin.name}}\n{% endfor %}\n\n\"\"\"\n\n\nclass GwCommandsInfo(GwDocumentsPattern, GwCommandsPattern):\n \"\"\"\n Provides documents for giving an overview about registered commands.\n \"\"\"\n # GwCommandsPatterns is not really needed for this plugin as parent class, because we do not register any command.\n # However, if no plugin does inherit from GwCommandsPattern the needed argument app.commands would not exist.\n # So this is the way to make sure that command-functionality was set up when this plugins gets used.\n def __init__(self, *args, **kwargs):\n self.name = kwargs.get(\"name\", self.__class__.__name__)\n super(GwCommandsInfo, self).__init__(*args, **kwargs)\n\n def activate(self):\n self.documents.register(name=\"commands_overview\",\n content=commands_content,\n description=\"Gives an overview about all registered commands\")\n","sub_path":"groundwork/plugins/gw_commands_info.py","file_name":"gw_commands_info.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287334560","text":"\"\"\"For assessing Calder-Verwer metric, :math:`1-(P(Y=1|S=1)-P(Y=1|S!=1))`.\"\"\"\n\nfrom ethicml.common import implements\nfrom ethicml.utility import DataTuple, Prediction\n\nfrom .metric import Metric\nfrom .prob_pos import ProbPos\n\n\nclass CV(Metric):\n \"\"\"Calder-Verwer.\"\"\"\n\n _name: str = \"CV\"\n\n @implements(Metric)\n def score(self, prediction: Prediction, actual: DataTuple) -> float:\n # has to be imported on demand because otherwise we get circular imports\n from ethicml.evaluators.per_sensitive_attribute import (\n diff_per_sensitive_attribute,\n metric_per_sensitive_attribute,\n )\n\n per_sens = metric_per_sensitive_attribute(prediction, actual, ProbPos())\n diffs = diff_per_sensitive_attribute(per_sens)\n\n return 1 - list(diffs.values())[0]\n\n @property\n def apply_per_sensitive(self) -> bool:\n \"\"\"Can this metric be applied per sensitive attribute group?\"\"\"\n return False\n\n\nclass AbsCV(CV):\n \"\"\"Absolute value of Calder-Verwer.\n\n This metric is supposed to make it easier to compare results.\n \"\"\"\n\n _name: str = \"CV absolute\"\n\n @implements(Metric)\n def score(self, prediction: Prediction, actual: DataTuple) -> float:\n cv_score = super().score(prediction, actual)\n # the following is equivalent to 1 - abs(diff)\n if cv_score > 1:\n return 2 - cv_score\n return cv_score\n","sub_path":"ethicml/metrics/cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"427085591","text":"import FWCore.ParameterSet.Config as cms\nprocess = cms.Process(\"MergeHLT\")\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 50000\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\nXXX_INPUT_XXX\n )\n)\n\nprocess.HSCPHLTDuplicate = cms.EDFilter(\"HSCPHLTFilter\",\n RemoveDuplicates = cms.bool(True),\n TriggerProcess = cms.string(\"HLT\"),\n MuonTrigger1Mask = cms.int32(1), #Activated\n PFMetTriggerMask = cms.int32(1), #Activated\n)\n\nprocess.HSCPHLTFilterPFMET = cms.EDFilter(\"HSCPHLTFilter\",\n RemoveDuplicates = cms.bool(False),\n TriggerProcess = cms.string(\"HLT\"),\n MuonTrigger1Mask = cms.int32(0), #Activated\n PFMetTriggerMask = cms.int32(1), #Activated\n)\n\nprocess.HSCPHLTFilterSingleMU = cms.EDFilter(\"HSCPHLTFilter\",\n RemoveDuplicates = cms.bool(False),\n TriggerProcess = cms.string(\"HLT\"),\n MuonTrigger1Mask = cms.int32(1), #Activated\n PFMetTriggerMask = cms.int32(0), #Activated\n)\n\nprocess.Filter = cms.Path(process.HSCPHLTDuplicate )\nprocess.HscpPathPFMet = cms.Path(process.HSCPHLTFilterPFMET )\nprocess.HscpPathSingleMu = cms.Path(process.HSCPHLTFilterSingleMU )\n\n\nprocess.Out = cms.OutputModule(\"PoolOutputModule\",\n outputCommands = cms.untracked.vstring(\n \"drop *\",\n 'keep EventAux_*_*_*',\n 'keep LumiSummary_*_*_*',\n 'keep edmMergeableCounter_*_*_*',\n \"keep *_genParticles_*_*\",\n \"keep GenEventInfoProduct_generator_*_*\",\n \"keep *_offlinePrimaryVertices_*_*\",\n #\"keep *_cscSegments_*_*\",\n #\"keep *_rpcRecHits_*_*\",\n #\"keep *_dt4DSegments_*_*\",\n \"keep SiStripClusteredmNewDetSetVector_generalTracksSkim_*_*\",\n \"keep SiPixelClusteredmNewDetSetVector_generalTracksSkim_*_*\",\n #\"keep *_reducedHSCPhbhereco_*_*\", #\n #\"keep *_reducedHSCPEcalRecHitsEB_*_*\", #\n #\"keep *_reducedHSCPEcalRecHitsEE_*_*\", #\n \"keep *_TrackRefitter_*_*\",\n \"drop TrajectorysToOnerecoTracksAssociation_TrackRefitter__\",\n \"keep *_standAloneMuons_*_*\",\n #\"drop recoTracks_standAloneMuons__*\",\n \"keep *_globalMuons_*_*\", #\n \"keep *_muonsSkim_*_*\",\n \"keep edmTriggerResults_TriggerResults_*_*\",\n \"keep recoPFJets_ak5PFJets__*\", #\n \"keep recoPFMETs_pfMet__*\", #\n \"keep recoCaloJets_ak5CaloJets__*\",\n \"keep *_HSCParticleProducer_*_*\",\n \"keep *_HSCPIsolation01__*\",\n \"keep *_HSCPIsolation03__*\",\n \"keep *_HSCPIsolation05__*\",\n \"keep *_dedx*_*_HSCPAnalysis\",\n \"keep *_muontiming_*_HSCPAnalysis\",\n \"keep triggerTriggerEvent_hltTriggerSummaryAOD_*_*\",\n \"keep PileupSummaryInfos_addPileupInfo_*_*\"\n ),\n fileName = cms.untracked.string('XXX_OUTPUT_XXX.root'),\n)\n\nprocess.endPath = cms.EndPath(process.Out)\n\nprocess.schedule = cms.Schedule(process.Filter, process.HscpPathPFMet, process.HscpPathSingleMu, process.endPath)\n\n\n","sub_path":"SUSYBSMAnalysis/HSCP/test/BuildHSCParticles/MC/Merge_cfg.py","file_name":"Merge_cfg.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322286407","text":"import numpy as np\nnp.set_printoptions(precision=4,suppress=True)\nimport sys\nfrom functools import reduce,partial\nfrom hqca.tools import RDMFunctions as rdmf\nfrom hqca.tools import Chem as chem\nfrom hqca.tools import EnergyFunctions as enf\nfrom hqca.tools import EnergyDeterminant as end\nfrom hqca.tools import EnergyOrbital as eno\nfrom pyscf import gto,mcscf\nfrom pyscf import scf as pscf\n\n'''\n./tools/EnergyFunctions.py\n\nModule for optimizer or energy functions, i.e. for rotations, etc.\n\n'''\n\ndef find_function(\n run_type,\n spec,\n Store,\n QuantStore):\n if run_type=='noft':\n if spec=='qc':\n f = partial(\n end.energy_eval_nordm,\n **{\n 'Store':Store,\n 'QuantStore':QuantStore\n }\n )\n if spec=='orb':\n f = partial(\n eno.energy_eval_orbitals,\n **{\n 'Store':Store,\n 'QuantStore':QuantStore\n }\n )\n elif spec=='orb_grad':\n f = partial(\n #eno.orbital_energy_gradient_givens,\n eno.orbital_en_grad_numerical,\n **{\n 'Store':Store,\n 'QuantStore':QuantStore\n }\n )\n if spec=='noft_grad':\n f = partial(\n end.energy_eval_grad_noft_numerical,\n **{\n 'Store':Store,\n 'QuantStore':QuantStore\n }\n )\n elif run_type=='rdm':\n f = partial(\n end.energy_eval_rdm,\n **{'Store':Store,'QuantStore':QuantStore}\n )\n return f\n\nclass Storage:\n '''\n Class for storing energetic properties -\n Basically, will store certain properties of the best 2RDM and wavefunction\n without having to return it for every function call.\n\n Also, will initiate the chemical procedure\n\n Also stores some basic properties of the molecule. However, does not hold\n properties related to the quantum optimization. Need to generate a\n QuantumStorage object to do that.\n '''\n def __init__(self,\n mol,\n Ne_as='default',\n No_as='default',\n casci=False,\n **kwargs):\n self.S = mol.intor('int1e_ovlp')\n self.T_1e = mol.intor('int1e_kin')\n self.V_1e = mol.intor('int1e_nuc')\n self.ints_1e_ao = self.V_1e+self.T_1e\n self.ints_2e_ao = mol.intor('int2e')\n try:\n self.hf = pscf.RHF(mol)\n self.hf.kernel()\n self.mol = mol\n self.hf.analyze()\n self.C= self.hf.mo_coeff\n self.f = self.hf.get_fock()\n except Exception:\n self.hf = pscf.ROHF(mol)\n self.hf.kernel()\n self.mol = mol\n self.hf.analyze()\n self.C= self.hf.mo_coeff\n self.f = self.hf.get_fock()\n if Ne_as=='default':\n self.Ne_as = mol.nelec[0]+mol.nelec[1]\n else:\n self.Ne_as = int(Ne_as)\n self.Ne_tot = mol.nelec[0]+mol.nelec[1]\n self.Ne_alp = mol.nelec[0]\n self.Ne_bet = mol.nelec[1]\n if No_as=='default':\n self.No_as = self.C.shape[0]\n else:\n self.No_as = int(No_as)\n self.No_tot = self.C.shape[0]\n if casci:\n self.mc = mcscf.CASCI(\n self.hf,\n self.No_as,\n self.Ne_as)\n self.mc.kernel()\n self.e_casci = self.mc.e_tot\n self.mc_coeff = self.mc.mo_coeff\n else:\n self.mc = None\n print('Hartree-Fock Energy: {:.8f}'.format(float(self.hf.e_tot)))\n print('CASCI Energy: {:.8f}'.format(float(self.e_casci)))\n self.E_ne = self.mol.energy_nuc()\n self.energy_best = 0\n self.energy_wf = 0\n self.energy_int = 0\n self.wf = {}\n self.rdm2=None\n self.Ci = np.linalg.inv(self.C)\n self.ints_1e =None\n self.ints_2e = None\n self.T_alpha = self.C.copy()\n self.T_beta = self.C.copy()\n self.opt_T_alpha = None\n self.opt_T_beta = None\n self.opt_done = False\n self.error = False\n self.occ_energy_calls = 0\n self.orb_energy_calls = 0\n self.active_space_calc='FCI'\n self.F_alpha = 0\n self.F_beta = 0\n self.spin = self.mol.spin\n self.kw = kwargs\n\n def gip(self):\n '''\n 'Get Initial Parameters (GIP) function.\n '''\n try:\n if self.sp=='noft':\n self.parameters=[0,0]\n elif self.sp=='rdm':\n if self.kw['spin_mapping'] in ['default','alternating']:\n Na = 1\n Nb = 1\n elif self.kw['spin_mapping']=='spin-free':\n Na = 2\n Nb = 0\n elif self.kw['spin_mapping']=='spatial':\n Na = 1\n Nb = 0\n if self.kw['entangled_pairs']=='full':\n N = 0.5*((self.No_as*Na)**2-self.No_as*Na)\n N += 0.5*((self.No_as*Nb)**2-self.No_as*Nb)\n elif self.kw['entangled_pairs']=='sequential':\n N = self.No_as-1\n elif self.kw['entangled_pairs']=='specified':\n pass\n self.parameters = [0 for i in range(int(N))]\n except AttributeError:\n print('Not assigned.')\n\n def gsm(self):\n self._generate_spin2spac_mapping()\n\n def gas(self):\n self._generate_active_space(**self.kw)\n\n def _generate_active_space(self,\n spin_mapping='default',\n **kw\n ):\n '''\n Note, all orb references are in spatial orbitals. \n '''\n self.alpha_mo={\n 'inactive':[],\n 'active':[],\n 'virtual':[],\n 'qc':[]\n }\n self.beta_mo={\n 'inactive':[],\n 'active':[],\n 'virtual':[],\n 'qc':[]\n }\n self.Ne_ia = self.Ne_tot-self.Ne_as\n self.No_ia = self.Ne_ia//2\n self.spin = spin_mapping\n self.No_v = self.No_tot-self.No_ia-self.No_as\n if self.Ne_ia%2==1:\n raise(SpinError)\n if self.Ne_ia>0:\n self.active_space_calc='CASSCF'\n ind=0\n for i in range(0,self.No_ia):\n self.alpha_mo['inactive'].append(ind)\n ind+=1\n for i in range(0,self.No_as):\n self.alpha_mo['active'].append(ind)\n ind+=1\n for i in range(0,self.No_v):\n self.alpha_mo['virtual'].append(ind)\n ind+=1\n for i in range(0,self.No_ia):\n self.beta_mo['inactive'].append(ind)\n ind+=1\n for i in range(0,self.No_as):\n self.beta_mo['active'].append(ind)\n ind+=1\n for i in range(0,self.No_v):\n self.beta_mo['virtual'].append(ind)\n ind+=1\n\n def _generate_spin2spac_mapping(self):\n self.s2s = {}\n for i in range(0,self.No_tot):\n self.s2s[i]=i\n for i in range(self.No_tot,2*self.No_tot):\n self.s2s[i]=i-self.No_tot\n\n def opt_update_wf(self,energy,wf,para):\n if energy<self.energy_wf:\n if energy<self.energy_best:\n self.energy_best = energy\n self.energy_wf = energy\n self.parameters = para\n self.wf = wf\n\n def opt_update_rdm2(self,energy,rdm2,para):\n if energy<self.energy_wf:\n if energy<self.energy_best:\n self.energy_best = energy\n self.energy_wf = energy\n self.parameters = para\n self.rdm2 = fx.expand(rdm2)\n\n def update_rdm2(self):\n self.rdm2 = rdmf.build_2rdm(\n self.wf,\n self.alpha_mo,\n self.beta_mo,\n region='full')\n self.rdm1 = rdmf.check_2rdm(\n self.rdm2,self.Ne_tot)\n self.rdm2 = fx.contract(self.rdm2)\n\n def update_full_ints(self):\n try:\n self.T_alpha_old = self.T_alpha.copy()\n self.T_beta_old = self.T_beta.copy()\n self.T_alpha = self.opt_T_alpha.copy()\n self.T_beta = self.opt_T_beta.copy()\n except Exception as e:\n pass\n self.ints_1e = chem.gen_spin_1ei(\n self.ints_1e_ao.copy(),\n self.T_alpha.T,\n self.T_beta.T,\n self.alpha_mo,\n self.beta_mo,\n region='full',\n spin2spac=self.s2s\n )\n self.ints_2e = chem.gen_spin_2ei(\n self.ints_2e_ao.copy(),\n self.T_alpha.T,\n self.T_beta.T,\n self.alpha_mo,\n self.beta_mo,\n region='full',\n spin2spac=self.s2s\n )\n self.ints_2e = fx.contract(self.ints_2e)\n # now, determining trace fidelity\n self.F_alpha = abs((reduce(np.dot, (\n self.T_alpha_old.T,\n self.Ci.T,\n self.Ci,\n self.T_alpha\n )\n ).trace()))*(1/len(self.T_alpha))\n self.F_beta = abs((reduce(np.dot, (\n self.T_beta_old.T,\n self.Ci.T,\n self.Ci,\n self.T_beta\n )\n ).trace()))*(1/len(self.T_beta))\n if self.F_alpha-1>1e-8:\n print('Error in fidelity:')\n print(self.T_alpha_old.T)\n print(self.S)\n print(self.T_alpha)\n print(self.F_alpha)\n if self.F_beta>1:\n print('Error in fidelity:')\n print(self.T_beta_old)\n print(self.S)\n print(self.T_beta.T)\n print(reduce(np.dot,(\n self.T_beta_old.T,\n self.S,\n self.T_beta)))\n print(reduce(np.dot,(\n self.T_beta_old,\n self.S,\n self.T_beta.T)))\n print(self.F_beta)\n\n\n\n def opt_update_int(self,para,energy,U_a,U_b):\n '''\n Basically, always update the energy after finding the next best step in\n an orbital optimization.\n '''\n if energy<self.energy_int:\n if energy<self.energy_best:\n self.energy_best = energy\n self.energy_int = energy\n self.opt_T_alpha = U_a\n self.opt_T_beta = U_b\n self.opt_para = para\n\n def opt_analysis(self):\n print(' -- -- -- -- -- -- -- ')\n print('-- -- -- -- -- -- -- --')\n print('E, scf: {:.9f} H'.format(self.hf.e_tot))\n print('E, run: {:.9f} H'.format(self.energy_best))\n try:\n diff = 1000*( self.energy_best-self.e_casci)\n print('E, fci: {:.9f} H'.format(self.e_casci))\n print('Energy difference from FCI: {:.8f} mH'.format(diff))\n except KeyError:\n pass\n rdm1 = rdmf.check_2rdm(fx.expand(self.rdm2),self.Ne_tot)\n print('Occupations of the 1-RDM:')\n print(np.real(np.diag(rdm1)))\n print('Natural orbital wavefunction:')\n for k,v in self.wf.items():\n print(' |{}>: {}'.format(k,v))\n self.Ci = np.linalg.inv(self.C)\n self.Ti_a = np.linalg.inv(self.T_alpha)\n self.Ti_b = np.linalg.inv(self.T_beta)\n Ni_a = reduce(\n np.dot, (\n self.Ti_a,self.C)\n )\n Ni_b = reduce(\n np.dot, (\n self.Ti_b,self.C)\n )\n rdm2_mo = rdmf.rotate_2rdm(\n fx.expand(self.rdm2),\n Ni_a.T,\n Ni_b.T,\n self.alpha_mo,\n self.beta_mo,\n spin2spac=self.s2s,\n region='full'\n )\n rdm1_mo = rdmf.check_2rdm(\n rdm2_mo,\n self.Ne_tot)\n print('1-RDM in the molecular orbital basis.')\n print(np.real(rdm1_mo))\n print('NO coefficients (in terms of MO):')\n print('Alpha: ')\n print(np.real(Ni_a.T))\n print('Beta: ')\n print(np.real(Ni_b.T))\n print('NO coefficients (in terms of AO):')\n print('Alpha: ')\n print(np.real(self.T_alpha))\n print('Beta: ')\n print(np.real(self.T_beta))\n sz = rdmf.Sz(\n rdm1_mo,\n self.alpha_mo,\n self.beta_mo,\n s2s=self.s2s)\n s2 = rdmf.S2(\n rdm2_mo,\n rdm1_mo,\n self.alpha_mo,\n self.beta_mo,\n s2s=self.s2s)\n print('1-RDM in the Lowdin atomic orbital basis.')\n #print('MO coefficients: ')\n rdm1_mo_a = rdm1_mo[0:self.No_tot,0:self.No_tot]\n rdm1_mo_b = rdm1_mo[self.No_tot:,self.No_tot:]\n print('Alpha:')\n print(np.real(reduce(np.dot, (self.C,rdm1_mo_a,self.Ci))))\n print('Beta:')\n print(np.real(reduce(np.dot, (self.C,rdm1_mo_b,self.Ci))))\n print('Sz value: {:.6f}'.format(np.real(sz)))\n print('S2 value: {:.6f}'.format(np.real(s2)))\n print('-- -- -- -- -- -- -- --')\n print(' -- -- -- -- -- -- --')\n\n def check(self,crit,Occ,Orb,print_run=False):\n print('Checking orbital and occupation energies for convergence...')\n if print_run:\n print('Best Energy: {}'.format(self.energy_best))\n print('Best energy from wf: {}'.format(self.energy_wf))\n print('Best energy from orbitals: {}'.format(self.energy_int))\n print('Parameters: {}'.format(self.parameters))\n print('Wavefunction: {}'.format(self.wf))\n self.energy_best = min(self.energy_wf,self.energy_int)\n if Occ.error:\n self.opt_done=True\n self.error=True\n elif Orb.error:\n self.opt_done=True\n self.error=True\n elif abs(self.energy_int-self.energy_wf)<crit:\n self.opt_done=True\n else:\n diff = abs(self.energy_int-self.energy_wf)*1000\n print('Difference in orbital and occupation energies: {:8f} mH'.format(diff))\n self.energy_wf = 0\n self.energy_int = 0 \n\n def update_calls(self,orb,occ):\n self.occ_energy_calls += occ\n self.orb_energy_calls += orb\n\n def find_npara_orb(self):\n self.Np_orb = 0\n if self.active_space_calc=='FCI':\n if self.spin in ['default']: #unrestricted\n temp = len(self.alpha_mo['active'])\n self.Np_orb += int(temp*(temp-1)/2)\n temp = len(self.beta_mo['active'])\n self.Np_orb += int(temp*(temp-1)/2)\n elif self.spin=='spatial': #restricted\n temp = len(self.alpha_mo['active'])\n self.Np_orb += int(temp*(temp-1)/2)\n elif self.active_space_calc=='CASSCF':\n sys.exit('Orbital rotations not implemented fully for CASSCF.')\n\ndef rotation_parameter_generation(\n spin_mo, # class with inactive, active, and virtual orbitals\n region='active',\n output='matrix',\n para=None\n ):\n '''\n spin_mo - should be a alpha or beta spin dictionary, with active, inactive\n and virtual orbital arrays\n\n keywords:\n\n region - 'active', 'active_space', 'as', 'full','occupied'\n -active space rotations\n -every rotation, with the exception of the active space\n -no virtual mixing\n\n output - 'matrix', 'Npara'\n -outputs the rotation matrix (require para input)\n -otherwise, outputs array with zeros that is the proper length\n '''\n No_tot = len(spin_mo['virtual']+spin_mo['active']+spin_mo['inactive'])\n if output=='matrix':\n rot_mat = np.identity(No_tot)\n count = 0\n hold=[]\n N = No_tot\n if region in ['active','as','active_space']:\n for i in spin_mo['active']:\n for j in spin_mo['active']:\n if i<j:\n hold.append([i%N,j%N])\n elif region in ['full']:\n for i in spin_mo['inactive']:\n for j in spin_mo['active']:\n hold.append([i%N,j%N])\n for i in spin_mo['inactive']:\n for j in spin_mo['virtual']:\n hold.append([i%N,j%N])\n for i in spin_mo['active']:\n for j in spin_mo['virtual']:\n hold.append([i%N,j%N])\n elif region in ['occupied']:\n for i in spin_mo['inactive']:\n for j in spin_mo['active']:\n hold.append([i%N,j%N])\n else:\n sys.exit('Invalid active space selection.')\n for z in hold:\n if output=='matrix':\n if para[count]==0:\n continue\n temp=np.identity(No_tot)\n c = np.cos(((para[count])))\n s = np.sin(((para[count])))\n temp[z[0],z[0]] = c\n temp[z[1],z[1]] = c\n temp[z[0],z[1]] = -s\n temp[z[1],z[0]] = s\n rot_mat = reduce( np.dot, (rot_mat,temp))\n count+=1 \n if output=='matrix':\n #print(rot_mat)\n return rot_mat\n elif output=='Npara':\n return count\n\n\n\nclass NotAvailableError(Exception):\n '''\n Means what it says.\n '''\nclass SpinError(Exception):\n '''\n Wrong active space selection. OR at least, not supported.\n '''\n\n\n","sub_path":"hqca/old/Storage.py","file_name":"Storage.py","file_ext":"py","file_size_in_byte":17707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"539481679","text":"# Copyright ClusterHQ Inc. See LICENSE file for details.\n\n\"\"\"\nTests for the ``flocker-deploy`` command line tool.\n\"\"\"\n\nfrom copy import deepcopy\nfrom subprocess import check_call\n\nfrom twisted.internet import reactor\nfrom twisted.python.filepath import FilePath\nfrom yaml import safe_dump\n\nfrom ...common import loop_until\nfrom ...control._config import FlockerConfiguration\nfrom ...control.httpapi import container_configuration_response\n\nfrom ..testtools import require_flocker_cli, require_cluster\nfrom ...testtools import AsyncTestCase, random_name, flaky\n\n\nclass FlockerDeployTests(AsyncTestCase):\n \"\"\"\n Tests for ``flocker-deploy``.\n \"\"\"\n def flocker_deploy(self, cluster, deployment_config, application_config):\n \"\"\"\n Run ``flocker-deploy`` with given configuration files.\n\n :param cluster: The ``Cluster`` to which the supplied config should\n be applied.\n :param dict deployment_config: The desired deployment configuration.\n :param dict application_config: The desired application configuration.\n \"\"\"\n # Construct an expected deployment mapping of IP addresses\n # to a set of ``Application`` instances.\n applications_to_parse = deepcopy(application_config)\n expected_deployment = dict()\n applications_map = FlockerConfiguration(\n applications_to_parse).applications()\n for node in deployment_config['nodes']:\n node_applications = []\n for node_app in deployment_config['nodes'][node]:\n if node_app in applications_map:\n node_applications.append(applications_map[node_app])\n expected_deployment[node] = set(node_applications)\n temp = FilePath(self.mktemp())\n temp.makedirs()\n\n deployment = temp.child(b\"deployment.yml\")\n deployment.setContent(safe_dump(deployment_config))\n\n application = temp.child(b\"application.yml\")\n application.setContent(safe_dump(application_config))\n check_call([b\"flocker-deploy\",\n b\"--certificates-directory\",\n cluster.certificates_path.path,\n cluster.control_node.public_address,\n deployment.path, application.path])\n # Wait for the cluster state to match the new deployment.\n da = self.assert_expected_deployment(cluster, expected_deployment)\n return da\n\n def assert_expected_deployment(self, cluster, expected_deployment):\n \"\"\"\n Assert that the expected set of ``Application`` instances on a set of\n nodes is the same as the actual set of ``Application`` instance on\n those nodes.\n\n The tutorial looks at Docker output, but the acceptance tests are\n intended to test high-level external behaviors. Since this is looking\n at the output of the control service API it merely verifies what\n Flocker believes the system state is, not the actual state.\n The latter should be verified separately with additional tests\n for external side-effects (applications being available on ports,\n say).\n\n :param cluster: The ``Cluster`` to query for current configuration.\n :param dict expected_deployment: A mapping of IP addresses to set of\n ``Application`` instances expected on the nodes with those IP\n addresses.\n\n :return Deferred: Fires on end of assertion.\n \"\"\"\n ip_to_uuid = {\n node.reported_hostname: node.uuid for node in cluster.nodes\n }\n\n def got_results(existing_containers):\n expected = []\n for reported_hostname, apps in expected_deployment.items():\n node_uuid = ip_to_uuid[reported_hostname]\n expected += [container_configuration_response(app, node_uuid)\n for app in apps]\n for app in expected:\n app[u\"running\"] = True\n return sorted(existing_containers) == sorted(expected)\n\n def configuration_matches_state():\n d = cluster.current_containers()\n d.addCallback(got_results)\n return d\n\n return loop_until(reactor, configuration_matches_state)\n\n @flaky([u'FLOC-3528'])\n @require_flocker_cli\n @require_cluster(1, require_container_agent=True)\n def test_deploy(self, cluster):\n \"\"\"\n Deploying an application to one node and not another puts the\n application where expected.\n \"\"\"\n [node_1] = cluster.nodes\n name = random_name(self)\n\n minimal_deployment = {\n u\"version\": 1,\n u\"nodes\": {\n node_1.reported_hostname: [name],\n },\n }\n\n minimal_application = {\n u\"version\": 1,\n u\"applications\": {\n name: {\n # Our config format doesn't support command-lines, so\n # we can't use standard image and need to pick\n # something small that will not immediately exit.\n u\"image\": u\"openshift/busybox-http-app\",\n },\n },\n }\n\n d = self.flocker_deploy(\n cluster, minimal_deployment, minimal_application)\n d.addCallback(lambda _:\n self.addCleanup(cluster.remove_container, name))\n return d\n","sub_path":"flocker/acceptance/obsolete/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"124214689","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 7 14:37:02 2019\n\n@author: sergio\n\"\"\"\ni = 0\nresultado = 0\nv = []\n\nprint(\"Este programa calcula o vetor paralelo tal que vetor1*vetor2=k\")\nr = int(input(\"Digite a dimensao desejada: \"))\nprint(\"\\nDigite as coordenas separadas por virgurlas, ex: 1,3,4\")\nu1 = eval('[' + input(\"Digite as coordenadas do vetor 1: \") + ']')\nk = float(input(\"Digite uma constante k, tal que u*v=k : \"))\n#funçao para achar o produto escalar de u1\nwhile i < r:\n resultado += u1[i]*u1[i]\n i +=1\n\ni = 0\n#encontrar x\nx = k/resultado\n\n\"\"\"funçao para fazer u1*x para encontrar v.\nqueria fazer imprimir igual o exercio3a (o vetor v é: x,y,z)\nmas não consegui, essa função imprime os valores um embaixo do outro\nseguindo a ordem x,y,z... respectivamente\"\"\"\nwhile i < r:\n v = u1[i]*x \n print(\"\\nAs coordenadas do vetor v sao respectivamente:\",v)\n i +=1\n \n ","sub_path":"Geometria analitica/ga3b.py","file_name":"ga3b.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"242106087","text":"# Python defaults\nimport pickle\nimport argparse\nfrom typing import List, Tuple\nfrom pathlib import Path\n\n# Custom imports\nimport discrete_world.plotting as P\nimport discrete_world.design_obstacles as DO\nfrom discrete_world import GridWorld as G\nfrom discrete_world.agent import Agent\n\ndef readWorld(fp):\n \"\"\" Reads a grid-world from an .env file. \"\"\"\n with open(fp, \"rb\") as data_file:\n data = pickle.load(data_file)\n return data\n\n\ndef main(env_file: Path, fig_dir: Path, create_obstacles: bool = False):\n # Define the grid-world start and goal locations\n rows = 5\n cols = 5\n init_pos = (rows - 1, 0)\n goals = [(0, cols - 1), (rows - 1, cols - 1)]\n goals = []\n obstacles = [] # type: List[Tuple[int, int]]\n p_slip = 0.8\n\n g = G(rows, cols, init_pos, goals, obstacles, p_slip)\n\n # Design the obstacles and save it in the env_file\n if create_obstacles:\n DO.create_world_wrapper(g, env_file)\n\n # Read the saved env_file\n g = readWorld(env_file)\n # Show the grid-world\n # g.render()\n\n # Define an agent or robot for the grid-world\n robot = Agent(g)\n\n # ----- This is where you define your RL agent. I just chose a random policy ----\n robot.gen_policy()\n\n # Show the plots of the grid-world and its reward\n # Image available in the fig_dir under parent.\n P.gen_plots(robot, fig_dir, env_file)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Grid-World setup\")\n parser.add_argument(\n \"env_file\", type=lambda p: Path(p).absolute(), help=\"Path to environment file\",\n )\n parser.add_argument(\n \"fig_dir\",\n type=lambda p: Path(p).absolute(),\n default=Path(__file__).absolute().parent / \"figs\",\n help=\"Path to directory where figures should be stored\",\n )\n parser.add_argument(\n \"-d\", \"--design\", action=\"store_true\", help=\"design obstacles in PyGame\"\n )\n args = parser.parse_args()\n\n fig_dir = args.fig_dir\n if not fig_dir.is_dir():\n fig_dir.mkdir(parents=True, exists_ok=True)\n\n create_obstacles = args.design\n\n env_file = args.env_file\n if not env_file.is_file() and not create_obstacles:\n raise ValueError(\"The given file {} does not exist\".format(env_file))\n\n main(env_file, fig_dir, create_obstacles)\n","sub_path":"discrete_world/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436184398","text":"import concurrent.futures\n\n\ndef function_x(item):\n return item * item\n\n\na_list = range(10)\n\nif __name__ == '__main__':\n\n with concurrent.futures.ThreadPoolExecutor(10) as tp:\n\n future_to_function_x = {\n tp.submit(function_x, item): item\n for item in a_list\n }\n\n results = {}\n\n for future in concurrent.futures.as_completed(future_to_function_x):\n\n item = future_to_function_x[future]\n\n try:\n res = future.result()\n except Exception as e:\n print('Exception when processing item \"%s\": %s' % (item, e))\n else:\n results[item] = res\n print(results)\n","sub_path":"multiprocess/concur.py","file_name":"concur.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"603328376","text":"import os\n\nif __name__ == \"__main__\":\n fileNameString = []\n result = []\n for i in range(16):\n result[i] = (i, i, i)\n for (root,dirs,files) in os.walk(r'E:\\Learning700\\2021-08-30', topdown=True):\n for file in files:\n fileNameString.append(r'{}\\{}'.format(root,file))\n for file in fileNameString:\n print(file)\n","sub_path":"ListDirFiles.py","file_name":"ListDirFiles.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"74925906","text":"import numpy as np\nfrom numpy import asarray, uint8\n\n\nclass ImageReader:\n def transfromImage(self, image, boxCount):\n boxCount = min(boxCount, min(image.size[0], image.size[1]))\n self.img = image\n self.data = asarray(image, dtype=uint8)\n boxWidth = image.size[0] // boxCount\n boxHeight = image.size[1] // boxCount\n squares = np.zeros(shape=(boxCount, boxCount, 3))\n for gY in range(boxCount):\n if gY == 0 or gY == boxCount - 1:\n for gX in range(boxCount):\n squares[gY][gX] = self.calcSqaure((gX * boxWidth, gY * boxHeight), (boxWidth, boxHeight))\n else:\n squares[gY][0] = self.calcSqaure((0, gY * boxHeight), (boxWidth, boxHeight))\n squares[gY][(boxCount - 1)] = self.calcSqaure(((boxCount - 1) * boxWidth, gY * boxHeight),\n (boxWidth, boxHeight))\n return squares\n\n def calcSqaure(self, point, box):\n colors = np.zeros(shape=3)\n for x in range(box[0]):\n for y in range(box[1]):\n colors += self.data[point[1] + y][point[0] + x]\n return colors / (box[0] * box[1])\n","sub_path":"imageReader.py","file_name":"imageReader.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"331067537","text":"import csv\nimport cgi\nimport requests\nfrom multiprocessing import Process\nfrom PIL import Image\nfrom StringIO import StringIO\nfrom django.core.files import File\nfrom django.conf import settings\nfrom rest_framework import serializers\nfrom rest_framework.reverse import reverse\nfrom api.exceptions import ImageURLException, ImageException\nfrom core.models import Item, TITLE_MAX_LENGTH, DESCRIPTION_MAX_LENGTH\nfrom itsdangerous import URLSafeTimedSerializer\n\n\nTHUMB_SIZE = 128, 128\nELLIPSIS = \"...\"\nFIELDNAMES = ['title', 'description', 'image']\n\n\ndef task(data):\n item_ser = ItemSerializer(data=data)\n if item_ser.is_valid():\n item_ser.save()\n # skip if not possible to create\n\n\nclass URLSerializer(serializers.Serializer):\n url = serializers.URLField(\n max_length=200, min_length=None, allow_blank=False\n )\n\n\nclass ImportSerializer(URLSerializer):\n\n @staticmethod\n def escape_and_truncate(value, length):\n # quote=True default in html.escape in python 3\n value = cgi.escape(value, quote=True)\n if len(value) > length:\n value = \"%s%s\" % (value[:length-len(ELLIPSIS)], ELLIPSIS)\n return value\n\n @staticmethod\n def get_csv_reader(url):\n try:\n resp = requests.get(url, stream=True, timeout=1, verify=True)\n except (\n requests.exceptions.ConnectionError,\n requests.exceptions.Timeout,\n requests.exceptions.TooManyRedirects\n ) as ex:\n raise serializers.ValidationError(\n dict(url=[ex.message])\n )\n except requests.exceptions.RequestException as ex:\n raise serializers.ValidationError(\n dict(url=['Unable to fetch CSV data form URL.'])\n )\n\n if resp.status_code == 404:\n raise serializers.ValidationError(\n dict(url=['The URL is not a valid CSV source.'])\n )\n\n # when using google docs URL, chunk is '' on next line. Bug?\n chunk = resp.iter_content(chunk_size=1024).next()\n\n sniffer = csv.Sniffer()\n try:\n if not chunk:\n chunk = resp.content[:1024]\n dialect = sniffer.sniff(chunk)\n except Exception:\n # Could not determine dialect\n # must investigate if we can conclude \"CSV not valid\"\n raise serializers.ValidationError(\n dict(url=['The URL is not a valid CSV source.'])\n )\n reader = csv.DictReader(\n resp.iter_lines(), dialect=dialect, fieldnames=FIELDNAMES\n )\n if sniffer.has_header(chunk):\n # skip header manually because it can be different than FIELDNAMES\n # and it wouldn't be skipped by the *reader* when iterating\n reader.next()\n return reader\n\n def create(self, validated_data):\n reader = self.get_csv_reader(validated_data['url'])\n items = []\n for row in reader:\n if row == dict(zip(FIELDNAMES, FIELDNAMES)):\n # header row was not detected by sniffer\n continue;\n else:\n # it migth happen that the sniffer would not detect a header\n # and the undetected header could be different than *fieldnames*\n # see api/tests.py::test_import_from_csv_with_unconventional_undetected_header\n\n # i don't think there's anything we could do about this here\n # since the bad header would look like a valid item row\n pass\n\n data = dict(\n user=self.context['user'].id,\n title=self.escape_and_truncate(\n row['title'] or \"N/A\", TITLE_MAX_LENGTH),\n description=self.escape_and_truncate(\n row['description'], DESCRIPTION_MAX_LENGTH),\n image=row['image'] or ''\n )\n if settings.ASYNC_IMPORT:\n Process(target=task, args=(data,)).start()\n else:\n task(data)\n return []\n\n\nclass ImageFromURLField(serializers.ImageField):\n\n def fetch(self, url):\n ser = URLSerializer(data=dict(url=url))\n\n if not ser.is_valid():\n raise ImageURLException\n\n try:\n resp = requests.get(\n ser.validated_data['url'], stream=True, timeout=1, verify=True\n )\n except requests.exceptions.RequestException:\n raise ImageURLException\n\n return resp\n\n def thumbnail(self, data):\n resp = self.fetch(data)\n try:\n im = Image.open(StringIO(resp.content))\n except IOError:\n raise ImageException\n\n im.thumbnail(THUMB_SIZE, Image.ANTIALIAS)\n out_image_data = StringIO()\n im.save(out_image_data, format=\"PNG\")\n out_image_data.seek(0)\n\n return File(out_image_data, name=\"thumbnail.png\")\n\n def to_internal_value(self, data):\n try:\n thumbnail = self.thumbnail(data)\n except (ImageURLException, ImageException):\n return None\n return super(serializers.ImageField, self).to_internal_value(thumbnail)\n\n def to_representation(self, value):\n if not value:\n return None\n serializer = URLSafeTimedSerializer(\n settings.SECRET_KEY, salt=settings.TOKEN_HASH_AUTH_SALT\n )\n auth_hash = serializer.dumps(\n self.context['request'].user.auth_token.key\n )\n return reverse(\n 'image-detail', [value.instance.id, auth_hash],\n request=self.context['request']\n )\n\nclass ItemSerializer(serializers.ModelSerializer):\n image = ImageFromURLField(required=False)\n resource_uri = serializers.HyperlinkedIdentityField(\n view_name='item-detail')\n class Meta:\n model = Item\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"333703578","text":"from datetime import datetime\nfrom flask import render_template, session, redirect, current_app, url_for, request , make_response, flash, session\nfrom . import main\nfrom .forms import BindingForm\nfrom .. import db\nfrom ..models import db, User, School\nfrom ..school import getOpener, USTB\nfrom ..wxmsgr import wxinit, todict, toxml, getwxid\n# import json\n# import urllib.request\n# from app.database import db_session\n\n@main.before_app_first_request\ndef before_first_request(): \n current_app.USTB=School('USTB')\n current_app.code=''\n\n\n# @main.teardown_request\n# def shutdown_session(exception=None):\n# db_session.remove()\n\n@main.route('/' )\ndef hello_world():\n return render_template('test.html')\n\n@main.route('/wx', methods = ['GET', 'POST'] )\ndef init_auth():\n if request.method == 'GET':\n signature = request.args[\"signature\"]\n timestamp = request.args[\"timestamp\"]\n nonce = request.args[\"nonce\"]\n echostr = request.args[\"echostr\"]\n return wxinit(signature, timestamp, nonce, echostr)\n else:\n print(request.data)\n dict = todict(request.data)\n if dict['MsgType'] == 'event' and dict['Event'] == 'CLICK' and dict[\"EventKey\"] == \"cx\":\n # url = 'http://ustbonline.coding.io' + url_for('main.grade', opid = dict['FromUserName'])\n url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3bd2eedb7bee8069&redirect_uri=http://ustbol.herokuapp.com'+ url_for('main.grade') +'&response_type=code&scope=snsapi_base#wechat_redirect' \n return toxml(dict, url)\n else:\n return 'Bad request'\n\n\n@main.route('/bd', methods = ['GET', 'POST'] )\ndef oauth():\n # session['opid']=getwxid(request.args.get(\"code\"))\n# return redirect(url_for('main.binding'))\n\n# @main.route('/binding', methods = ['GET', 'POST'])\n# def binding():\n state = None\n form = BindingForm()\n if session.get('opid'):\n opid=session['opid']\n print('session中有opid',session['opid'])\n else:\n opid=getwxid(request.args.get(\"code\"))\n session['opid'] = opid\n print('通过函数获得opid', opid)\n if form.validate_on_submit():\n ustb=USTB(form.stuid.data, form.pswd.data)\n opener = ustb.login()\n if opid and opener :\n user=User.query.filter_by(wxid=opid).first()\n if user:\n state='已重新绑定'\n else:\n user = User(opid, form.stuid.data, form.pswd.data, current_app.USTB)\n db.session.add(user)\n flash('恭喜:), 绑定成功!')\n state = '已绑定'\n else:\n flash('绑定失败:(, 请请使用微信登录,并检查学号密码是否正确')\n form.stuid.data = ''\n return render_template('binding.html', form=form, state=state)\n\n\n@main.route('/grade', methods = ['GET', 'POST'] )\ndef grade():\n if session.get('opid'):\n opid=session['opid']\n print('session中有opid',session['opid'])\n else:\n opid=getwxid(request.args.get(\"code\"))\n print('通过函数获得opid', opid)\n user = User.query.filter_by(wxid=opid).first()\n if user:\n ustb=USTB(user.stuid, user.pswd)\n opener = ustb.login()\n grade=ustb.getgrade(opener)\n return render_template('grade.html', grade=grade, lenth = len(grade))\n else:\n flash('请先绑定')\n return render_template('404.html'), 404\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"415034829","text":"\nfrom DealPackageDevKit import CompositeAttributeDefinition, CalcVal, ParseFloat\n\nclass SetCallbacksToClass(object):\n def __init__(self, inherited, base):\n self._inherited = inherited\n self._base = base\n def __enter__(self):\n self._name = self._inherited.get_name()\n self._inherited.set_name(self._base.get_name())\n def __exit__(self, type, value, traceback):\n self._inherited.set_name(self._name)\n\n\nclass OneVolVolatility(CompositeAttributeDefinition):\n def OnInit(self, quoteTradeName, callVolObjectsName, putVolObjectsName):\n self._quoteTradeName = quoteTradeName\n self._callVolObjectsName = callVolObjectsName\n self._putVolObjectsName = putVolObjectsName\n \n def Attributes(self):\n return {'volatility': CalcVal(label = 'Vol %',\n calcMapping=self.QuoteTradeName() + ':FDealSheet:Portfolio One Volatility',\n onChanged='@SimulateVolatility',\n transform='@TransformVolatility',\n solverParameter='@VolatilityParam'),\n \n 'callVolatility': CalcVal(label='@CallVolatilityLabel',\n calcMapping=self.CallVolObjectsNameName() + ':FDealSheet:Portfolio Volatility FXOStrat',\n onChanged='@ValueSimulated|UnsimulateOneVolatility',\n transform='@TransformVolatility',\n solverParameter='@VolatilityParam'),\n\n 'putVolatility': CalcVal(label='@PutVolatilityLabel',\n calcMapping=self.PutVolObjectsNameName() + ':FDealSheet:Portfolio Volatility FXOStrat',\n onChanged='@ValueSimulated|UnsimulateOneVolatility',\n transform='@TransformVolatility',\n solverParameter='@VolatilityParam')\n } if self.CallVolObjectsNameName() else {}\n '''*******************************************************\n * 1Vol get methods\n *******************************************************''' \n def QuoteTradeName(self):\n return self._quoteTradeName\n\n def CallVolObjectsNameName(self):\n return self._callVolObjectsName\n\n def PutVolObjectsNameName(self):\n return self._putVolObjectsName\n\n\nclass OneVolatility(OneVolVolatility):\n def OnInit(self, quoteTradeName, saveTradeName, altQuoteTradeName = None, saveTradeFlippedName = None, callVolObjectsName = None, putVolObjectsName = None):\n OneVolVolatility.OnInit(self, quoteTradeName, callVolObjectsName, putVolObjectsName)\n self._altQuoteTradeName = altQuoteTradeName\n self._saveTradeName = saveTradeName\n self._flippedSide = None\n if saveTradeFlippedName:\n self._flippedSide = OneVolatility( 'Flipped%s' % quoteTradeName,\n saveTradeFlippedName,\n 'Flipped%s' % altQuoteTradeName if altQuoteTradeName else '')\n self._flippedSide.set_name('flipped')\n \n def DeltaAttributes(self, callBackName, suffix = ''):\n return {'deltaBS%s'%suffix: CalcVal(label='Delta BS (1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=callBackName + ':FDealSheet:Instrument Delta One Vol FXOStrat',\n transform=self.UniqueCallback('@SolveOneVolDelta'),\n solverTopValue=True),\n\n 'deltaBS%sCall'%suffix: CalcVal(label='Delta BS Call(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=callBackName + ':FDealSheet:Instrument Delta Call One Vol FXOStrat',\n solverTopValue='solverStrike2DomPerFor'),\n\n 'deltaBS%sPut'%suffix: CalcVal(label='Delta BS Call(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=callBackName + ':FDealSheet:Instrument Delta Put One Vol FXOStrat',\n solverTopValue='solverStrikeDomPerFor')\n } if callBackName else {}\n\n def FwdDeltaAttributes(self):\n return {'fwdDeltaBS': CalcVal(label='Fwd Delta BS(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=self.SaveTradeName() + ':FDealSheet:Instrument Forward Delta One Vol FXOStrat',\n transform=self.UniqueCallback('@SolveOneVolDelta'),\n solverTopValue=True),\n\n 'fwdDeltaBSCall': CalcVal(label='Fwd Delta BS Call(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=self.SaveTradeName() + ':FDealSheet:Instrument Forward Delta Call One Vol FXOStrat',\n solverTopValue='solverStrike2DomPerFor'),\n\n 'fwdDeltaBSPut': CalcVal(label='Fwd Delta BS Put(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=self.SaveTradeName() + ':FDealSheet:Instrument Forward Delta Put One Vol FXOStrat',\n solverTopValue='solverStrikeDomPerFor')\n }\n \n def FlippedAttributes(self):\n attrs = {}\n if self._flippedSide:\n with SetCallbacksToClass(self._flippedSide, self):\n flippedAttributes = self._flippedSide.Attributes()\n for attr, trait in flippedAttributes.items():\n attrs[self._flippedSide.PrefixedName(attr)] = trait\n return attrs\n \n def Attributes(self): \n attrs = OneVolVolatility.Attributes(self)\n attrs.update(self.DeltaAttributes(self.QuoteTradeName()))\n attrs.update(self.DeltaAttributes(self.AltQuoteTradeName(), 'Alt'))\n attrs.update(self.FwdDeltaAttributes())\n attrs.update(self.FlippedAttributes())\n return attrs\n \n \n '''*******************************************************\n * 1Vol get methods\n *******************************************************''' \n def AltQuoteTradeName(self):\n return self._altQuoteTradeName\n \n def SaveTradeName(self):\n return self._saveTradeName\n\n def SolveOneVolDelta(self, attrName, value):\n # slow solver, first creating one copy and then each solver in the loop will create an own copy of that copy\n # code should be optimized to do all solving operations in the same deal package copy\n precision = 0.0001\n maxIterations = 5\n dpCopy = self.Owner().DealPackage().Copy()\n dpCopy.SetAttribute('bidAskMode', False)\n dpCopy.Refresh()\n \n callAttr = attrName + 'Call'\n putAttr = attrName + 'Put'\n \n callSolverParam = self.Owner().GetAttributeMetaData(callAttr, 'solverTopValue')()\n putSolverParam = self.Owner().GetAttributeMetaData(putAttr, 'solverTopValue')()\n \n callValue = ParseFloat(value, formatter=dpCopy.GetAttribute(callAttr))\n \n if (dpCopy.GetAttribute(callAttr).Value().Number() > 0) != (callValue > 0):\n callValue = -callValue\n putValue = -callValue\n \n for i in range(maxIterations):\n dpCopy.SetAttribute('solverParameter', callSolverParam)\n dpCopy.SetAttribute(callAttr, callValue)\n dpCopy.SetAttribute('solverParameter', putSolverParam)\n dpCopy.SetAttribute(putAttr, putValue)\n \n if abs(dpCopy.GetAttribute(callAttr).Value().Number() - callValue) <= precision:\n break\n else:\n print (callAttr, dpCopy.GetAttribute(callAttr).Value(), putAttr, dpCopy.GetAttribute(putAttr).Value())\n raise DealPackageException(\"No solution found for '%s' that gives expected '%s' of %s. \"\n \"(Using boundary conditions precision = %f, max iterations = %d).\"\n %('strikes', attrName, value, precision, maxIterations))\n \n for attribute in ('strikeDomesticPerForeign', 'strike2DomesticPerForeign'):\n self.Owner().SetAttribute(attribute, dpCopy.GetAttribute(attribute))\n return self.Owner().GetValueToStore(attrName, dpCopy.GetAttribute(attrName).Value())\n \n","sub_path":"Extensions/PairOptionsPricerDealPackage/FPythonCode/PairOptionsOneVolatility.py","file_name":"PairOptionsOneVolatility.py","file_ext":"py","file_size_in_byte":9461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"128636144","text":"def power():\n numbers = []\n for a in range(1, 100):\n for b in range(1, 100):\n n = a ** b\n numbers.append(n)\n return numbers\n\n\ndef solve():\n summ = 0\n results = []\n for i in power():\n for j in str(i):\n summ += int(j)\n results.append(summ)\n summ = 0\n return max(results)\n\n\nprint(solve())\n","sub_path":"Problem 056.py","file_name":"Problem 056.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131339076","text":"from django import forms\nfrom apps.administrador import models\nfrom apps.send_email import models as model_email\nfrom django.contrib.auth.models import User \nfrom django.urls import reverse_lazy\nfrom Seguimiento import settings\nfrom django.contrib.auth.hashers import make_password\nfrom django.utils.translation import ugettext_lazy as _\n\n\n#from django.db.models import Q\n#from bootstrap_datepicker.widgets import DatePicker\n#from bootstrap_datepicker_plus import DatePickerInput\n#from datetimewidget.widgets import DateTimeWidget\n\t\nclass UserForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.User\n\n\t\tfields = [\n\t\t\t'id',\n\t\t\t'password',\n\t\t\t'username',\n\t\t\t'first_name',\n\t\t\t'last_name',\n\t\t\t'email',\n\t\t\t'is_active',\n\t\t\t'carrera',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id': 'Código', \n\t\t\t'password': 'Constraseña',\n\t\t\t'username': 'Cédula',\n\t\t\t'first_name': 'Nombre',\n\t\t\t'last_name': 'Apellido',\n\t\t\t'email': 'Correo',\n\t\t\t'is_active': 'Estado',\n\t\t\t'carrera': 'Carrera',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id': forms.TextInput(attrs={'class':'form-control'}),\n\t\t\t'password': forms.PasswordInput(render_value = True, \n\t\t\t\tattrs={'class':'form-control',\n\t\t\t\t }),\n\t\t\t'username': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese la cédula',\n\t\t\t\t'id' : 'username',\n 'onkeypress' : 'return soloNumeros(event);',\n 'autocomplete' : 'off',\n 'required' : 'true', \n }),\n\t\t\t'first_name': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el nombre',\n\t\t\t\t'id' : 'first_name',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n }), \n\t\t\t'last_name': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el apellido',\n\t\t\t\t'id' : 'last_name',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n }), \n\t\t\t'email': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el correo',\n\t\t\t\t'id' : 'email',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}), \n\t\t\t'is_active': forms.CheckboxInput(attrs={'class':'onoffswitch'}), \n\t\t\t'carrera': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(UserForm, self).__init__(*args, **kwargs)\n\t\tself.fields['email'].help_text = 'Correo institucional de la UTMACH'\n\t\tself.fields['is_active'].help_text = 'Conceder permiso para acceder al sistema'\n\t\tself.fields['password'].initial = make_password('syllabus')\n\t\tself.fields['is_active'].initial = True\n\n\tdef clean_email(self):\n\t\t#self: instancia de la clase\n\t\temail = self.cleaned_data.get(\"email\")\n\t\tif str(email) == '':\n\t\t\traise forms.ValidationError('Ingrese el correo electrónico')\n\t\telse:\n\t\t\tif not \"@\" in email:\n\t\t\t\traise forms.ValidationError('Utilice un email como: ejemplo_est@utmachala.edu.ec')\n\t\t\telse:\n\t\t\t\temail_base, extension = email.split(\"@\")\n\t\t\t\tif not \"utmachala.edu.ec\" == extension:\n\t\t\t\t\traise forms.ValidationError('Utilice un email con la extensión utmachala.edu.ec')\n\t\t\t\treturn email\n\n\tdef verificar(self, nro):\n\t\ttotal = 0\n\t\tbase = 10\n\t\td_ver = int(nro[9])# digito verificador\n\t\tmultip = (2, 1, 2, 1, 2, 1, 2, 1, 2)\n\n\t\tfor i in range(0,len(multip)):\n\t\t\tp = int(nro[i]) * multip[i]\n\t\t\tif p >= 10:\n\t\t\t\tp=p-9\n\t\t\t\ttotal+=p\n\t\t\telse:\n\t\t\t\ttotal+=p \n\t \n\t\tmod = total % base\n\t\tnuevo=total\n\t\twhile mod != 0:\n\t\t\tnuevo=nuevo+1\n\t\t\tmod = nuevo % base\n\t\td_ver= nuevo-total\n\t\treturn d_ver\n\n\tdef clean_username(self):\n\t\tusername = self.cleaned_data.get(\"username\")\n\t\tl = len(username)\n\t\tif l == 10: # verificar la longitud correcta\n\t\t\tcp = int(username[0:2])\n\t\t\tif cp >= 1 and cp <= 24: # verificar codigo de provincia de 1 a 24\n\t\t\t\ttercer_dig = int(username[2])\n\t\t\t\tif tercer_dig >= 0 and tercer_dig < 6 : # numeros entre 0 y 6\n\t\t\t\t\tif l == 10:\n\t\t\t\t\t\tif int(username[9]) == int(self.verificar(username)):\n\t\t\t\t\t\t\tif(username == '2222222222'):\n\t\t\t\t\t\t\t\traise forms.ValidationError('Cédula de identidad incorrecta')\n\t\t\t\t\t\t\t\t#print(\"Incorrecto\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\treturn username\n\t\t\t\t\t\t\t\t#print(\"Cedula correcta\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise forms.ValidationError('Cédula de identidad incorrecta')\n\t\t\t\t\t\t\t#print(\"Cedula erronea\")\n\t\t\t\telse:\n\t\t\t\t\traise forms.ValidationError('Tercer digito invalido')\n\t\t\t\t\t#print('Tercer digito invalido')\n\t\t\telse:\n\t\t\t\traise forms.ValidationError('Cédula de provincia incorrecto')\n\t\t\t\t#print('Codigo de provincia incorrecto') \n\t\telse:\n\t\t\traise forms.ValidationError('Cédula de identidad incorrecta, debe tener 10 dígitos')\n\t\t\t#print('Longitud incorrecta del numero ingresado')\n\n\t# def clean_password(self):\n\t# \tclave = self.cleaned_data.get('password')\n\t# \tprint(clave)\n\t# \tclave = make_password(clave)\n\t# \tprint(clave)\n\t# \treturn clave\n\nclass EstudianteForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.User\n\n\t\tfields = [\n\t\t\t'username',\n\t\t\t'first_name',\n\t\t\t'last_name',\n\t\t\t'email',\n\t\t\t'carrera',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'username': 'Cédula',\n\t\t\t'first_name': 'Nombre',\n\t\t\t'last_name': 'Apellido',\n\t\t\t'email': 'Correo',\n\t\t\t'carrera': 'Carrera',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'username': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese la cédula' }),\n\t\t\t'first_name': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el nombre',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}), # muestra la lista de carreras\n\t\t\t'last_name': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el apellido',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}), \n\t\t\t'email': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el correo'}), \n\t\t\t'carrera': forms.HiddenInput(attrs={'class':'form-control'}),\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(EstudianteForm, self).__init__(*args, **kwargs)\n\t\tself.fields['email'].help_text = 'Correo institucional de la UTMACH'\n\t\tself.fields['username'].required = True\n\t\tself.fields['first_name'].required = True\n\t\tself.fields['last_name'].required = True\n\t\tself.fields['email'].required = True\n\t\tself.fields['carrera'].required = False\n\n\tdef clean_email(self):\n\t\t#self: instancia de la clase\n\t\temail = self.cleaned_data.get(\"email\")\n\t\tif str(email) == '':\n\t\t\traise forms.ValidationError('Ingrese el correo electrónico')\n\t\telse:\n\t\t\tif not \"@\" in email:\n\t\t\t\traise forms.ValidationError('Utilice un email como: ejemplo_est@utmachala.edu.ec')\n\t\t\telse:\n\t\t\t\temail_base, extension = email.split(\"@\")\n\t\t\t\tif not \"utmachala.edu.ec\" == extension:\n\t\t\t\t\traise forms.ValidationError('Utilice un email con la extensión utmachala.edu.ec')\n\t\t\t\treturn email\n\nclass CarreraForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Carrera\n\n\t\tfields = [\n\t\t\t'id_carrera',\n\t\t\t'nombre_carrera',\n\t\t]\n\t\tlabels = {\n\t\t\t'id_carrera': 'Código' ,\n\t\t\t'nombre_carrera': 'Carrera',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_carrera': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_carrera',\n }),\n\t\t\t'nombre_carrera': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese la carrera',\n\t\t\t\t'id' : 'nombre_carrera',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n }),\n\t\t}\n\nclass EnviarCorreoForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = model_email.Mensajes\n\n\t\tfields = [\n\t\t\t'id_mensaje',\n\t\t\t'asunto',\n\t\t\t'mensaje',\n\t\t\t'remitente',\n\t\t\t'destinatario',\n\t\t]\n\t\tlabels = {\n\t\t\t'id_mensaje': 'Código',\n\t\t\t'asunto': 'Asunto',\n\t\t\t'mensaje': 'Mensaje',\n\t\t\t'remitente': 'Remitente',\n\t\t\t'destinatario': 'Destinatario',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_mensaje': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_mensaje',\n }),\n\t\t\t'asunto': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el asunto',\n\t\t\t\t'id': 'asunto',\n 'autocomplete': 'off',\n 'required': 'true',\n }),\n\t\t\t'mensaje': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el mensaje',\n\t\t\t\t'id': 'mensaje',\n 'autocomplete': 'off',\n 'required': 'true',\n }),\n\t\t\t'remitente': forms.Select(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el correo',\n\t\t\t\t'id': 'remitente',\n 'autocomplete': 'off',\n }),\n\t\t\t'destinatario': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el destinatario',\n\t\t\t\t'id': 'destinatario',\n 'autocomplete': 'off',\n 'required': 'true',\n }),\n\t\t}\n\nclass PeriodosForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Periodo\t\n\n\t\tfields = [\n\t\t\t'id_periodo',\n\t\t\t'estado_periodo',\n\t\t\t'fecha_inicio',\n\t\t\t'fecha_fin',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_periodo': 'Periodo' ,\n\t\t\t'estado_periodo': 'Estado',\n\t\t\t'fecha_inicio': 'Fecha de inicio',\n\t\t\t'fecha_fin': 'Fecha fin',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_periodo': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_periodo',\n\t\t\t\t'onkeypress': 'return eliminarEspaciosVacios(event);', \n 'autocomplete' : 'off',\n 'required' : 'true',\n }),\n\t\t\t'estado_periodo': forms.CheckboxInput(),\n\t\t\t'fecha_inicio': forms.DateInput(format = '%Y-%m-%d',attrs={'type': 'date', 'class': 'form-control'}),\n\t\t\t'fecha_fin': forms.DateInput(format = '%Y-%m-%d',attrs={'type': 'date', 'class': 'form-control'}),\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(PeriodosForm, self).__init__(*args,**kwargs)\n\t\tself.fields['estado_periodo'].initial = True\n\n\t#usar el metodo clean para otro tipo de validaciones\n\tdef clean(self):\n\t\tfecha_inicio = self.cleaned_data.get('fecha_inicio')\n\t\tfecha_fin = self.cleaned_data.get('fecha_fin')\n\t\tperiodo = self.cleaned_data.get('id_periodo')\n\n\t\tfecha_inicio_valida = False\n\t\tfecha_fin_valida = False\n\n\t\tif fecha_inicio is not None:\n\t\t\tfecha_inicio_valida = True\t\t\t\n\n\t\tif fecha_fin is not None:\n\t\t\tfecha_fin_valida = True\n\n\t\tif fecha_inicio_valida == False and fecha_fin_valida == False:\n\t\t\traise forms.ValidationError('Ingrese la fecha de inicio y fin del periodo')\n\t\telse:\n\t\t\tif fecha_inicio_valida == False:\n\t\t\t\traise forms.ValidationError('Ingrese una fecha de inicio')\n\t\t\telif fecha_fin_valida == False:\n\t\t\t\traise forms.ValidationError('Ingrese una fecha de cierre')\t\n\t\t\telse:\n\t\t\t\tfecha_inicio = str(fecha_inicio)\n\t\t\t\tfecha_fin = str(fecha_fin)\n\n\t\t\t\tanio_inicio, mes_inicio, dia_inicio = str(fecha_inicio).split(\"-\")\n\t\t\t\tanio_fin, mes_fin, dia_fin = str(fecha_fin).split(\"-\")\n\n\t\t\t\tdia_inicio = int(dia_inicio)\n\t\t\t\tmes_inicio = int (mes_inicio)\n\t\t\t\tanio_inicio = int(anio_inicio)\n\n\t\t\t\tdia_fin = int(dia_fin)\n\t\t\t\tmes_fin = int(mes_fin)\n\t\t\t\tanio_fin = int(anio_fin)\n\n\t\t\t\tif anio_inicio < anio_fin:\n\t\t\t\t\t#fechas_validadas = True\n\t\t\t\t\treturn super(PeriodosForm,self).clean()\n\t\t\t\telif anio_inicio == anio_fin:\n\t\t\t\t\tif mes_inicio < mes_fin:\n\t\t\t\t\t\t#fechas_validadas = True\n\t\t\t\t\t\treturn super(PeriodosForm,self).clean()\n\t\t\t\t\telif mes_inicio == mes_fin:\n\t\t\t\t\t\tif dia_inicio <= dia_fin:\n\t\t\t\t\t\t\t#fechas_validadas = True\n\t\t\t\t\t\t\treturn super(PeriodosForm,self).clean()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise forms.ValidationError('Fecha de inicio mayor a fecha de cierre')\n\t\t\t\t\telse:\n\t\t\t\t\t\traise forms.ValidationError('Fecha de inicio mayor a fecha de cierre')\t\n\t\t\t\telse:\n\t\t\t\t\traise forms.ValidationError('Fecha de inicio mayor a fecha de cierre')\n\n\n\t#validacion estado \n\tdef clean_estado_periodo(self):\n\t\t#self: instancia de la clase\n\t\testado = self.cleaned_data.get('estado_periodo')\n\t\tcodigo_periodo = self.cleaned_data.get('id_periodo')\n\n\t\tnumero_periodos_activos = len(models.Periodo.objects.filter(estado_periodo =True))\n\t\t#print('numero de periodos activos '+str(numero_periodos_activos))\n\n\t\tif estado == False:\n\t\t\treturn estado\n\t\telse: #estado activo\n\t\t\tif numero_periodos_activos > 0:\n\t\t\t\tfilas = len(models.Periodo.objects.filter(id_periodo = codigo_periodo, estado_periodo = True))\n\t\t\t\tif str(filas) == '1': \n\t\t\t\t\treturn estado\n\t\t\t\telse:\n\t\t\t\t\t#Si estoy agregando un periodo con estado activo, y hay ya un periodo activo, no se debe guardar ese registro\n\t\t\t\t\traise forms.ValidationError('Desactive el periodo que se encuentra activo')\t\t\t\n\t\t\telif numero_periodos_activos == 0:\n\t\t\t\t#Si estoy agregando un periodo con estado activo, y no hay ningun periodo activo, se debe guardar ese registro\n\t\t\t\treturn estado\n\t\t\treturn estado\n\nclass CursoNuevoForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Curso\n\n\t\tfields = [\n\t\t\t'id_curso',\n\t\t\t'nombre_curso',\n\t\t\t'carrera',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_curso': 'Código' ,\n\t\t\t'nombre_curso': 'Curso',\n\t\t\t'carrera': 'Carrera',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_curso': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_curso',\n\t\t\t\t}),\n\t\t\t'nombre_curso': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el curso',\n\t\t\t\t'id' : 'nombre_curso',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}), \n\t\t\t'carrera': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t}\n\n\n\tdef __init__(self, *args, **kwargs):\n\t\tcarrera = kwargs.pop('carrera')\n\t\tsuper(CursoNuevoForm, self).__init__(*args,**kwargs)\n\t\tself.fields['carrera'].initial = carrera\n\n\nclass CursoEditarForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Curso\n\n\t\tfields = [\n\t\t\t'id_curso',\n\t\t\t'nombre_curso',\n\t\t\t'carrera',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_curso': 'Código' ,\n\t\t\t'nombre_curso': 'Curso',\n\t\t\t'carrera': 'Carrera',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_curso': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'nombre_curso': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el curso',\n\t\t\t\t'id' : 'nombre_curso',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}), \n\t\t\t'carrera': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t}\n\n\nclass CursoParaleloForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Cursos_Paralelo\n\n\t\tfields = [\n\t\t\t'id_curso_paralelo',\n\t\t\t'curso',\n\t\t\t'paralelo',\n\t\t\t'estudiante',\n\t\t\t'periodo',\n\t\t\t'estado_curso_paralelo',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_curso_paralelo': 'Código' ,\n\t\t\t'curso': 'Curso',\n\t\t\t'paralelo': 'Paralelo',\n\t\t\t'estudiante': 'Estudiante',\n\t\t\t'periodo': 'Periodo',\n\t\t\t'estado_curso_paralelo': 'Estado',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_curso_paralelo': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t'curso': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'id' : 'curso',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), # muestra la lista de cursos\n\t\t\t'paralelo': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el paralelo',\n\t\t\t\t'id' : 'paralelo',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t}), # muestra la lista de paralelos \n\t\t\t'estudiante': forms.HiddenInput(attrs={'class':'form-control'}),\n\t\t\t'periodo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'id' : 'periodo',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'estado_curso_paralelo': forms.CheckboxInput(attrs={'class':'onoffswitch'}),\n\t\t}\n\t\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(CursoParaleloForm, self).__init__(*args,**kwargs)\n\t\tperiodo_actual = models.Periodo.objects.get(estado_periodo = True)\n\t\tself.fields['estudiante'].required = False\n\t\tself.fields['periodo'].initial = periodo_actual\n\t\tself.fields['estado_curso_paralelo'].initial = True \n\t\tself.fields['curso'].queryset = models.Curso.objects.all().order_by('carrera', 'id_curso') \n\n\t#validacion de los campos de CursoParalelo \n\tdef clean(self):\n\t\tcurso = self.cleaned_data.get('curso')\n\t\tparalelo = self.cleaned_data.get('paralelo')\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\testado = self.cleaned_data.get('estado_curso_paralelo')\n\n\t\tcantidad_curso_paralelo = len(models.Cursos_Paralelo.objects.filter(curso = curso, paralelo = paralelo, periodo = periodo))\n\t\tif cantidad_curso_paralelo == 0:\n\t\t\treturn super(CursoParaleloForm,self).clean()\n\t\telse:\n\t\t\traise forms.ValidationError(str(curso) + ' ' + str(paralelo) + ' ya ha sido creado en el periodo ' + str(periodo) )\n\n\nclass CursoParaleloFormEdit(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Cursos_Paralelo\n\n\t\tfields = [\n\t\t\t'id_curso_paralelo',\n\t\t\t'curso',\n\t\t\t'paralelo',\n\t\t\t'estudiante',\n\t\t\t'periodo',\n\t\t\t'estado_curso_paralelo',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_curso_paralelo': 'Código' ,\n\t\t\t'curso': 'Curso',\n\t\t\t'paralelo': 'Paralelo',\n\t\t\t'estudiante': 'Estudiante',\n\t\t\t'periodo': 'Periodo',\n\t\t\t'estado_curso_paralelo': 'Estado', \n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_curso_paralelo': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t'curso': forms.HiddenInput(attrs={'class':'form-control'}), # muestra la lista de cursos\n\t\t\t'paralelo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el paralelo',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}), # muestra la lista de paralelos \n\t\t\t'estudiante': forms.Select(attrs={'class':'form-control'}),\n\t\t\t'periodo': forms.HiddenInput(attrs={'class':'form-control'}),\n\t\t\t'estado_curso_paralelo': forms.CheckboxInput(attrs={'class':'onoffswitch'}),\n\t\t}\n\t\n\tdef __init__(self, *args, **kwargs):\n\t\tcarrera = kwargs.pop('carrera')\n\t\tsuper(CursoParaleloFormEdit, self).__init__(*args,**kwargs)\n\t\tperiodo = models.Periodo.objects.get(estado_periodo = True)\n\t\tself.fields['estado_curso_paralelo'].help_text = 'Marque esta opción si aún el estudiante está a cargo de este curso'\n\t\tself.fields['estudiante'].queryset = models.User.objects.filter(is_superuser=False, is_active = True, carrera = carrera)\n\t\tself.fields['estudiante'].required = True\n\t\tself.fields['curso'].required = True\n\t\tself.fields['periodo'].required = True\n\t\tself.fields['paralelo'].required = False\n\t\tself.fields['periodo'].initial = periodo\n\n\t#validacion de los campos de CursoParalelo \n\tdef clean(self):\n\t\tcurso = self.cleaned_data.get('curso')\n\t\tparalelo = self.cleaned_data.get('paralelo')\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\testudiante = self.cleaned_data.get('estudiante')\n\t\testado = self.cleaned_data.get('estado_curso_paralelo')\n\n\t\tif (estado == False):\n\t\t\treturn super(CursoParaleloFormEdit,self).clean()\n\t\telse:\n\t\t\tcantidad_curso_paralelo = len(models.Cursos_Paralelo.objects.filter(estudiante = estudiante, estado_curso_paralelo = True, periodo = periodo, curso=curso, paralelo=paralelo))\n\n\t\t\tif cantidad_curso_paralelo == 0:\n\t\t\t\tcantidad_curso_paralelo = len(models.Cursos_Paralelo.objects.filter(estudiante = estudiante, estado_curso_paralelo = True, periodo = periodo))\n\t\t\t\tif cantidad_curso_paralelo == 0:\n\t\t\t\t\treturn super(CursoParaleloFormEdit,self).clean()\n\t\t\t\telse:\t\t\t\t\t\n\t\t\t\t\traise forms.ValidationError(str(estudiante) + \" ya tiene asignado un curso en el periodo \" +str(periodo))\n\t\t\telse:\n\t\t\t\traise forms.ValidationError(str(estudiante) + \" ya tiene asignado un curso en el periodo \" +str(periodo))\n\n\nclass DocenteForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Docente\n\n\t\tfields = [\n\t\t\t'id_docente',\n\t\t\t'nombre_docente',\n\t\t\t'apellido_docente',\n\t\t\t'estado_docente',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_docente': 'Cédula',\n\t\t\t'nombre_docente': 'Nombre',\n\t\t\t'apellido_docente': 'Apellido',\n\t\t\t'correo_docente': 'Correo',\n\t\t\t'estado_docente': 'Estado',\n\t\t\t'telefono_docente': 'Telefono',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_docente': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n }),\n\t\t\t'nombre_docente': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el nombre',\n\t\t\t\t'id' : 'nombre_docente',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',}),\n\t\t\t'apellido_docente': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el apellido',\n\t\t\t\t'id' : 'apellido_docente',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}),\n\t\t\t'estado_docente': forms.CheckboxInput(),\n\t\t}\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(DocenteForm, self).__init__(*args, **kwargs)\n\t\tself.fields['estado_docente'].initial = True\n\t\t#self.fields['nombre_docente'].error_messages = {'required': 'First Name is Required'}\n\n\nclass AsignaturaForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Asignatura\n\n\t\tfields = [\n\t\t\t'id_asignatura',\n\t\t\t'nombre_asignatura',\n\t\t\t'nro_creditos',\n\t\t\t'carrera',\n\t\t\t'curso',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_asignatura': 'Código',\n\t\t\t'nombre_asignatura': 'Asignatura',\n\t\t\t'nro_creditos': 'Número de créditos',\n\t\t\t'carrera': 'Carrera',\n\t\t\t'curso': 'Curso',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_asignatura': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_asignatura',\n\t\t\t\t'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}),\n\t\t\t'nombre_asignatura': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el nombre de la asignatura',\n\t\t\t\t'id' : 'nombre_asignatura',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}),\n\t\t\t'nro_creditos': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el número de créditos',\n\t\t\t\t'id' : 'nro_creditos',\n 'onkeypress' : 'return soloNumeros(event);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\n\t\t\t'carrera': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), # muestra la lista de carreras\n\t\t\t'curso': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t'id' : 'id_curso',\n\t\t\t\t}), # muestra la lista de cursos\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tcurso = kwargs.pop('curso')\n\t\tsuper(AsignaturaForm, self).__init__(*args,**kwargs)\n\t\tself.fields['curso'].initial = curso\n\t\tcurso = models.Curso.objects.filter(id_curso=curso)\n\t\tcarrera = 0\n\t\tfor row in curso:\n\t\t\tcarrera = int(row.carrera_id)\n\n\t\tself.fields['carrera'].initial = carrera\n\n\tdef clean(self):\n\t\tmateria = self.cleaned_data.get(\"nombre_asignatura\")\n\t\tcurso = self.cleaned_data.get(\"curso\")\n\t\tcarrera = self.cleaned_data.get(\"carrera\")\n\t\tcantidad_filas = len(models.Asignatura.objects.filter(nombre_asignatura = materia, curso = curso, carrera = carrera))\n\n\t\tnro_creditos = self.cleaned_data.get(\"nro_creditos\")\n\t\tif nro_creditos <= 0:\n\t\t\traise forms.ValidationError('El número de créditos debe ser mayor a cero')\n\t\telse:\n\t\t\tif cantidad_filas == 0:\n\t\t\t\treturn super(AsignaturaForm,self).clean()\n\t\t\telse:\n\t\t\t\traise forms.ValidationError(\"Ya se ha registrado \" + str(materia) + \" en \" + str(curso) )\n\n\nclass AsignaturaEditForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Asignatura\n\n\t\tfields = [\n\t\t\t'id_asignatura',\n\t\t\t'nombre_asignatura',\n\t\t\t'nro_creditos',\n\t\t\t'carrera',\n\t\t\t'curso',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_asignatura': 'Código',\n\t\t\t'nombre_asignatura': 'Asignatura',\n\t\t\t'nro_creditos': 'Número de créditos',\n\t\t\t'carrera': 'Carrera',\n\t\t\t'curso': 'Curso',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_asignatura': forms.HiddenInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t'nombre_asignatura': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el nombre de la asignatura',\n\t\t\t\t'onkeypress' : 'return soloLetras(event);',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}),\n\t\t\t'nro_creditos': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el número de créditos',\n\t\t\t\t'onkeypress' : 'return soloNumeros(event);',\n\t\t\t\t'type':'number',\n\t\t\t\t}),\n\t\t\t'carrera': forms.HiddenInput(attrs={'class':'form-control'}), # muestra la lista de carreras\n\t\t\t'curso': forms.HiddenInput(attrs={'class':'form-control'}), # muestra la lista de cursos\n\t\t}\n\n\tdef clean(self):\n\t\tnro_creditos = self.cleaned_data.get(\"nro_creditos\")\n\t\tif nro_creditos <= 0:\n\t\t\traise forms.ValidationError('El número de créditos debe ser mayor a cero')\n\t\telse:\n\t\t\treturn super(AsignaturaEditForm,self).clean()\n\nclass AsignaturaDocenteForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Docentes_Asignatura\n\n\t\tfields = [\n\t\t\t'id_docente_asignatura',\n\t\t\t'curso',\n\t\t\t'asignatura',\n\t\t\t'paralelo',\n\t\t\t'docente',\n\t\t\t'periodo',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_docente_asignatura': 'Código',\n\t\t\t'curso': 'Curso',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'paralelo': 'Paralelo',\n\t\t\t'docente': 'Docente',\n\t\t\t'periodo': 'Periodo',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_docente_asignatura': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_docente_asignatura',\n\t\t\t\t}),\n\t\t\t'curso': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t}),\n\t\t\t'asignatura': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), \n\t\t\t'paralelo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el paralelo',\n\t\t\t\t}),\n\t\t\t'periodo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t}),\n\t\t\t'docente': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t'id' : 'docente',\n\t\t\t\t}),\t\t\t\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tparalelo = kwargs.pop('paralelo')\n\t\tcurso = kwargs.pop('curso')\n\t\tperiodo = kwargs.pop('periodo')\n\t\tsuper(AsignaturaDocenteForm, self).__init__(*args, **kwargs)\n\t\tself.fields['docente'].queryset = models.Docente.objects.filter(estado_docente = True).order_by('apellido_docente')\n\t\tself.fields['asignatura'].queryset = models.Asignatura.objects.filter(curso = curso)\n\t\tself.fields['periodo'].initial = periodo\n\t\tself.fields['paralelo'].initial = paralelo\n\t\tself.fields['curso'].initial = curso\n\n\t#validacion de los campos de Asignaturas Docentes \n\tdef clean(self): #self: instancia de la clase\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\tdocente = self.cleaned_data.get('docente')\n\t\tasignatura = self.cleaned_data.get('asignatura')\n\t\tcurso = self.cleaned_data.get('curso')\n\t\tparalelo = self.cleaned_data.get('paralelo')\n\n\t\tif docente == None or asignatura == None or paralelo == '' or curso == None:\n\t\t\traise forms.ValidationError(\"Completa todos los campos\")\n\n\n\t\tcantidad_estudiantes = len(models.Docentes_Asignatura.objects.filter(periodo = periodo, asignatura = asignatura, curso = curso, docente = docente, paralelo = paralelo))\n\t\tif cantidad_estudiantes == 0:\n\t\t\tcantidad_estudiantes = len(models.Docentes_Asignatura.objects.filter(periodo = periodo, asignatura = asignatura, curso = curso, paralelo = paralelo))\n\t\t\tif cantidad_estudiantes == 0:\n\t\t\t\treturn super(AsignaturaDocenteForm,self).clean()\n\t\t\telse:\n\t\t\t\traise forms.ValidationError(\"Ya existe un docente asignado a dictar clases de \" + str(asignatura) + \" en \" + str(curso) + str(paralelo) + \" durante el periodo \" + str(periodo))\n\t\telse:\t\n\t\t\traise forms.ValidationError( str(docente) + \" ya tiene asignado \" + str(curso) + \" \" + str(paralelo) + \" y la asignatura de \" + str(asignatura) + \" en el periodo \" +str(periodo))\n\n\nclass AsignaturaDocenteEditForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Docentes_Asignatura\n\t\tfields = [\n\t\t\t'id_docente_asignatura',\n\t\t\t'curso',\n\t\t\t'asignatura',\n\t\t\t'paralelo',\n\t\t\t'docente',\n\t\t\t'periodo',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_docente_asignatura': 'Código',\n\t\t\t'curso': 'Curso',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'paralelo': 'Paralelo',\n\t\t\t'docente': 'Docente',\n\t\t\t'periodo': 'Periodo',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_docente_asignatura': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t'curso': forms.Select(attrs={'class':'form-control'}),\n\t\t\t'asignatura': forms.Select(attrs={'class':'form-control'}), \n\t\t\t'paralelo': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el paralelo',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}),\n\t\t\t'periodo': forms.TextInput(attrs={'class':'form-control'}),\n\t\t\t'docente': forms.Select(attrs={'class':'form-control'}),\t\t\t\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tasignatura_docente = kwargs.pop('asignatura_docente')\n\t\tasignatura_docente = models.Docentes_Asignatura.objects.get(id_docente_asignatura = asignatura_docente)\n\n\t\tsuper(AsignaturaDocenteEditForm, self).__init__(*args, **kwargs)\n\t\tself.fields['docente'].queryset = models.Docente.objects.filter(estado_docente = True)\n\t\tself.fields['periodo'].initial = asignatura_docente.periodo\n\t\tself.fields['curso'].initial = asignatura_docente.curso\n\t\tself.fields['paralelo'].initial = asignatura_docente.paralelo\n\t\tself.fields['asignatura'].initial = asignatura_docente.asignatura\n\n\t#validacion de los campos de Asignaturas Docentes \n\tdef clean(self):\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\tdocente = self.cleaned_data.get('docente')\n\t\tasignatura = self.cleaned_data.get('asignatura')\n\t\tcurso = self.cleaned_data.get('curso')\n\t\tparalelo = self.cleaned_data.get('paralelo')\n\n\t\tif docente == None or asignatura == None:\n\t\t\tif docente == None and asignatura == None:\n\t\t\t\traise forms.ValidationError(\"Completa los campos de docente, asignatura y paralelo\")\n\t\t\telse:\n\t\t\t\tif docente == None:\n\t\t\t\t\traise forms.ValidationError(\"Completa el campo de docente\")\n\t\t\t\telse:\n\t\t\t\t\tif asignatura==None:\n\t\t\t\t\t\traise forms.ValidationError(\"Completa el campo de asignatura\")\t\t\t\n\n\t\tcantidad_docentes_asignaturas = len(models.Docentes_Asignatura.objects.filter(periodo = periodo, asignatura = asignatura, curso = curso, docente = docente, paralelo = paralelo))\n\t\tif cantidad_docentes_asignaturas == 0:\n\t\t\treturn super(AsignaturaDocenteEditForm,self).clean()\n\t\telse:\t\n\t\t\t#return super(AsignaturaDocenteEditForm,self).clean()\n\t\t\traise forms.ValidationError(str(docente) + \" ya tiene a cargo \" + str(asignatura) + \" en el periodo \" +str(periodo))\n\nclass HorarioForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Horario\t\n\t\tfields = [\n\t\t\t'id_horario',\n\t\t\t'curso_paralelo',\n\t\t\t'asignatura',\n\t\t\t'dia',\n\t\t\t'hora',\t\t\n\t\t\t'periodo',\t\n\t\t]\n\t\tlabels = {\n\t\t\t'id_horario': 'Horario' ,\n\t\t\t'curso_paralelo': 'Curso - Paralelo',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'dia': 'Día',\n\t\t\t'hora': 'Número de horas',\n\t\t\t'periodo': 'Periodo',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_horario': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_horario',\n\t\t\t\t}),\n\t\t\t'curso_paralelo': forms.HiddenInput(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'asignatura': forms.Select(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'dia': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'id' : 'dia',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), \n\t\t\t'hora': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el número de horas',\n\t\t\t\t'id' : 'hora',\n 'onkeypress' : 'return soloNumeros(event);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\t\t\n\t\t\t'periodo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\t\t\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tcurso_paralelo = kwargs.pop('curso_paralelo')\n\t\tcurso = kwargs.pop('curso')\n\t\tperiodo = kwargs.pop('periodo')\n\t\tsuper(HorarioForm, self).__init__(*args,**kwargs)\n\t\tself.fields['curso_paralelo'].initial = curso_paralelo\n\t\tself.fields['periodo'].initial = periodo\n\t\tself.fields['asignatura'].queryset = models.Asignatura.objects.filter(curso = curso)\n\n\nclass HorarioEditForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Horario\t\n\t\tfields = [\n\t\t\t'id_horario',\n\t\t\t'curso_paralelo',\n\t\t\t'asignatura',\n\t\t\t'dia',\n\t\t\t'hora',\t\t\n\t\t\t'periodo',\t\n\t\t]\n\t\tlabels = {\n\t\t\t'id_horario': 'Horario' ,\n\t\t\t'curso_paralelo': 'Curso - Paralelo',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'dia': 'Día',\n\t\t\t'hora': 'Número de horas',\n\t\t\t'periodo': 'Periodo',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_horario': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_horario',\n\t\t\t\t}),\n\t\t\t'curso_paralelo': forms.TextInput(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'asignatura': forms.Select(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'dia': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'id' : 'dia',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), \n\t\t\t'hora': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el número de horas',\n\t\t\t\t'id' : 'hora',\n 'onkeypress' : 'return soloNumeros(event);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\t\t\n\t\t\t'periodo': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\t\t\n\t\t}\n\n\tdef clean(self):\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\thora = self.cleaned_data.get('hora')\n\t\tdia = self.cleaned_data.get('dia')\n\t\tasignatura = self.cleaned_data.get('asignatura')\n\t\tcurso_paralelo = self.cleaned_data.get('curso_paralelo')\n\t\tcantidad_horario = len(models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, hora = hora, dia = dia))\n\t\tcreditos = models.Asignatura.objects.get(id_asignatura = asignatura.id_asignatura).nro_creditos\n\n\t\tif hora <= 0:\n\t\t\traise forms.ValidationError('Indique una hora mayor a cero')\n\t\telse:\n\t\t\tif cantidad_horario == 1:\n\t\t\t\traise forms.ValidationError('Ya se ha establecido ' + str(hora) + ' hora(s) el día ' + str(dia) + ' para ' + str(asignatura))\t\n\t\t\telse:\n\t\t\t\tcantidad_horario = len(models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, hora = hora)) #cambiar dia\n\t\t\t\thorario = models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, hora = hora)\n\t\t\t\tif cantidad_horario >= 1:\n\t\t\t\t\thorario = models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo).exclude(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, hora = hora)\n\t\t\t\t\tif str(dia) == str(horario.dia):\n\t\t\t\t\t\traise forms.ValidationError('Ya se ha establecido el día ' + str(dia) + ' para ' + str(asignatura))\t\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn super(HorarioEditForm,self).clean()\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tcantidad_horario = len(models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, dia = dia)) #cambiar hora\n\t\t\t\t\tif cantidad_horario >= 1:\n\t\t\t\t\t\thorario = models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo).exclude(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, dia = dia)\n\t\t\t\t\t\tif (hora + horario.hora) == creditos:\n\t\t\t\t\t\t\treturn super(HorarioEditForm,self).clean()\n\t\t\t\t\traise forms.ValidationError('Cambie el día o la hora, uno a la vez')\t\n\t\t\t\t\t\t\n\t\t\nclass SeguimientoForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Seguimiento\t\n\t\tfields = [\n\t\t\t'id_seguimiento',\n\t\t\t'fecha',\n\t\t\t'porcentaje_real',\n\t\t\t'porcentaje_ideal',\n\t\t\t'estudiante',\n\t\t\t'observacion',\n\t\t\t'asignatura',\n\t\t\t'semana',\n\t\t\t'periodo',\t\t\n\t\t\t'estado_seguimiento',\t\n\t\t]\n\t\tlabels = {\n\t\t\t'id_seguimiento': 'Código',\n\t\t\t'fecha': 'Fecha',\n\t\t\t'porcentaje_real': 'Valor real',\n\t\t\t'porcentaje_ideal': 'Valor ideal',\n\t\t\t'estudiante': 'Estudiante',\n\t\t\t'observacion': 'Observación',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'semana': 'Semana',\n\t\t\t'periodo': 'Periodo',\n\t\t\t'estado_seguimiento': 'Estado',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_seguimiento': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t#'fecha': forms.DateInput(attrs={'class': 'vDateField'}),\n\t\t\t'fecha': forms.DateInput(format = '%Y-%m-%d',attrs={'type': 'date', 'class': 'form-control'}),\n\t\t\t'porcentaje_real': forms.TextInput(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'onkeypress' : 'return soloNumerosYDecimales(this, event);',\n\t\t\t\t'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\n\t\t\t'porcentaje_ideal': forms.TextInput(attrs={'class': 'form-control'}),\n\t\t\t'estudiante': forms.HiddenInput(attrs={'class':'form-control'}),\t\t\n\t\t\t'observacion': forms.Textarea(attrs={\n\t\t\t\t'rows': 2, \n\t\t\t\t'cols': 40, \n\t\t\t\t'style': 'height: auto;' 'width: calc(100% - 0px);',\n\t\t\t\t'placeholder': 'Observaciones ...'}),\n\t\t\t'asignatura': forms.Select(attrs={'class':'form-control', 'placeholder': 'Ingrese la Asignatura'}),\n\t\t\t'semana': forms.HiddenInput(attrs={'class':'form-control'}),\n\t\t\t'periodo': forms.HiddenInput(attrs={'class': 'form-control'}),\n\t\t\t'estado_seguimiento': forms.HiddenInput(attrs={'class': 'form-control'}),\t\t\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tcurso = kwargs.pop('curso')\n\t\tcarrera = kwargs.pop('carrera')\n\t\tperiodo = kwargs.pop('periodo')\n\t\talumno = kwargs.pop('alumno')\n\t\tsemana = kwargs.pop('semana')\n\n\t\tsuper(SeguimientoForm, self).__init__(*args, **kwargs)\n\t\tself.fields['asignatura'].queryset = models.Asignatura.objects.filter(curso = curso, carrera = carrera)\n\t\tself.fields['periodo'].initial = periodo\n\t\tself.fields['estudiante'].initial = alumno\n\t\tself.fields['semana'].initial = semana\n\t\tself.fields['estado_seguimiento'].initial = True\n\t\tself.fields['observacion'].required = False\n\t\tself.fields['porcentaje_real'].required = True\n\t\tself.fields['porcentaje_ideal'].required = True\n\t\tself.fields['fecha'].required = True\n\t\tself.fields['asignatura'].required = True\n\n\tdef clean(self):\n\t\tporcentaje_real = self.cleaned_data.get(\"porcentaje_real\")\n\t\tif porcentaje_real <= 0:\n\t\t\traise forms.ValidationError('No puede ingresar porcentajes menores a cero')\n\t\telse:\n\t\t\treturn super(SeguimientoForm,self).clean()\n\n\nclass SeguimientoEditForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Seguimiento\t\n\t\tfields = [\n\t\t\t'id_seguimiento',\n\t\t\t'fecha',\n\t\t\t'porcentaje_real',\n\t\t\t'porcentaje_ideal',\n\t\t\t'estudiante',\n\t\t\t'observacion',\n\t\t\t'asignatura',\n\t\t\t'semana',\n\t\t\t'periodo',\t\n\t\t\t'docente',\t\t\n\t\t\t'curso_paralelo',\t\t\t\n\t\t]\n\t\tlabels = {\n\t\t\t'id_seguimiento': 'Código',\n\t\t\t'fecha': 'Fecha',\n\t\t\t'porcentaje_real': 'Valor real',\n\t\t\t'porcentaje_ideal': 'Valor ideal',\n\t\t\t'estudiante': 'Estudiante',\n\t\t\t'observacion': 'Observación',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'semana': 'Semana',\n\t\t\t'periodo': 'Periodo',\n\t\t\t'docente': 'Docente',\n\t\t\t'curso_paralelo': 'Curso',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_seguimiento': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t#'fecha': forms.DateInput(attrs={'class': 'vDateField'}),\n\t\t\t'fecha': forms.DateInput(format = '%Y-%m-%d',attrs={'type': 'date', 'class': 'form-control'}),\n\t\t\t'porcentaje_real': forms.TextInput(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'onkeypress' : 'return soloNumerosYDecimales(this, event);',\n\t\t\t\t'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\n\t\t\t'porcentaje_ideal': forms.HiddenInput(attrs={'class': 'form-control'}),\n\t\t\t'estudiante': forms.TextInput(attrs={'class':'form-control'}),\t\t\n\t\t\t'observacion': forms.Textarea(attrs={\n\t\t\t\t'rows': 2, \n\t\t\t\t'cols': 40, \n\t\t\t\t'style': 'height: auto;' 'width: calc(100% - 0px);',\n\t\t\t\t'placeholder': 'Observaciones ...'}),\n\t\t\t'asignatura': forms.Select(attrs={'class':'form-control', 'placeholder': 'Ingrese la Asignatura'}),\n\t\t\t'semana': forms.TextInput(attrs={'class':'form-control'}),\n\t\t\t'periodo': forms.TextInput(attrs={'class': 'form-control'}),\n\t\t\t'docente': forms.TextInput(attrs={'class': 'form-control'}),\t\t\n\t\t\t'curso_paralelo': forms.TextInput(attrs={'class': 'form-control'}),\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(SeguimientoEditForm, self).__init__(*args, **kwargs)\n\t\tself.fields['observacion'].required = False\n\t\tself.fields['porcentaje_real'].required = True\n\t\tself.fields['fecha'].required = True\n\t\tself.fields['asignatura'].required = True\n\n\tdef clean(self):\n\t\tperiodo = self.cleaned_data.get(\"periodo\")\n\t\tfecha_inicio = periodo.fecha_inicio\n\t\tfecha_fin = periodo.fecha_fin\n\t\tfecha_seguimiento = self.cleaned_data.get(\"fecha\")\n\t\tporcentaje_real = self.cleaned_data.get(\"porcentaje_real\")\n\t\tporcentaje_ideal = self.cleaned_data.get(\"porcentaje_ideal\")\n\t\tobservacion = self.cleaned_data.get(\"observacion\")\n\t\tsemana = self.cleaned_data.get(\"semana\")\n\t\tmateria = self.cleaned_data.get(\"asignatura\")\n\t\talumno = self.cleaned_data.get(\"estudiante\")\n\t\tcurso_paralelo = self.cleaned_data.get(\"curso_paralelo\")\n\t\tseguimiento = models.Seguimiento.objects.get(periodo = periodo, asignatura = materia, curso_paralelo = curso_paralelo, estudiante=alumno, semana = semana, fecha = fecha_seguimiento)\n\t\t\n\t\tif porcentaje_real <= 0:\n\t\t\traise forms.ValidationError('No puede ingresar porcentajes menores a cero')\n\t\telse:\n\t\t\tif fecha_inicio <= fecha_seguimiento and fecha_seguimiento <= fecha_fin:\n\t\t\t\tif (float(porcentaje_real) > float(porcentaje_ideal) and observacion == ''):\n\t\t\t\t\traise forms.ValidationError('El porcentaje real supera al ideal. Especifique alguna observación' )\n\t\t\t\telif (float(porcentaje_real) < float(porcentaje_ideal) and observacion == ''):\n\t\t\t\t\traise forms.ValidationError('El porcentaje real es inferior al ideal. Especifique alguna observación' )\n\t\t\t\telse:\n\t\t\t\t\tif float(porcentaje_ideal) > 100:\n\t\t\t\t\t\traise forms.ValidationError('El porcentaje ideal semanal no puede superar el 100% ' )\n\t\t\t\t\telse:\n\t\t\t\t\t\tporcentajes_sin_incluir_valor_real_actual = models.Seguimiento.objects.filter(periodo = periodo, asignatura = materia, curso_paralelo = curso_paralelo).exclude(id_seguimiento = seguimiento.id_seguimiento)\n\t\t\t\t\t\tvalor_real_total = 0\n\t\t\t\t\t\tvalor_ideal_total = porcentaje_ideal\n\t\t\t\t\t\tfor row in porcentajes_sin_incluir_valor_real_actual: #recorrer valores por semana\n\t\t\t\t\t\t\tvalor_real_total = valor_real_total + row.porcentaje_real\n\t\t\t\t\t\t\tvalor_ideal_total = valor_ideal_total + row.porcentaje_ideal\n\n\t\t\t\t\t\tif valor_ideal_total >= (valor_real_total+porcentaje_real):\n\t\t\t\t\t\t\treturn super(SeguimientoEditForm,self).clean()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise forms.ValidationError('La sumatoria del porcentaje real no puede superar la sumatoria del porcentaje ideal ' )\t\n\t\t\telse:\n\t\t\t\traise forms.ValidationError('La fecha ingresada: ' + str(fecha_seguimiento) + ' no es válida. Dicha fecha debe estar entre el rango: ' + str(fecha_inicio) + ' - ' + str(fecha_fin) )\n","sub_path":"SISTEMA_SEGUIMIENTO_SYLLABUS/apps/administrador/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":43238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"549499603","text":"from __future__ import division\n#from builtins import str\nfrom builtins import range\nfrom past.utils import old_div\nfrom builtins import object\nimport uuid\nimport copy\nimport os\nimport time\n\nimport vodka.app\nimport vodka.data\nimport vodka.data.renderers\nimport vodka.config\nimport vodka.plugins\nimport vodka.plugins.zeromq\n\nimport graphsrv.group\n\n#FIXME: these need to be abstracted in wsgi plugin\nfrom flask import request\n\nclass GraphSourcePlugin(vodka.plugins.TimedPlugin):\n \"\"\"\n Graph data source plugin\n \"\"\"\n\n @property\n def type_name(self):\n return self.get_config(\"type\")\n\n def push(self, plots, ts=None):\n \n if not ts:\n ts = time.time()\n\n vodka.data.handle(\n self.type_name,\n {\n \"data\": plots,\n \"ts\" : ts\n },\n data_id=self.name,\n caller=self\n )\n\n\n\n\nclass Graph(object):\n \n class Configuration(vodka.config.Handler):\n\n format_y = vodka.config.Attribute(\n str,\n default=\"ms\",\n #FIXME: should be dynamic\n choices=[\"ms\"],\n help_text=\"formatter for y axis labels\"\n )\n\n precision_y = vodka.config.Attribute(\n int,\n default=2,\n help_text=\"float precision\"\n )\n\n size_y = vodka.config.Attribute(\n float,\n default=0.25,\n help_text=\"tick size on the y axis\"\n )\n\n sizes_x = vodka.config.Attribute(\n list,\n default=[3000],\n help_text=\"valid sizes for the x axis - this should be a list of intervals you want to support for viewing. (ms)\"\n )\n\n type = vodka.config.Attribute(\n str,\n #FIXME: should be dynamic\n choices=[\"multitarget\", \"smokestack\"],\n help_text=\"graph type\"\n )\n\n plot_y = vodka.config.Attribute(\n str,\n help_text=\"plot this value on the y axis (data field name)\"\n )\n\n id_field = vodka.config.Attribute(\n str,\n help_text=\"the field by which a record in the data set is uniquely identified\"\n )\n\n\n\n@vodka.app.register('graphsrv')\nclass GraphServ(vodka.app.WebApplication):\n # configuration\n\n class Configuration(vodka.app.WebApplication.Configuration):\n \n layout_config_file = vodka.config.Attribute(\n vodka.config.validators.path,\n default=lambda x,i: i.resource(\"etc/layouts.yaml\"),\n help_text=\"location of your layout configuration file\"\n )\n\n graphs = vodka.config.Attribute(\n dict,\n default={},\n help_text=\"graph configuration\",\n handler=lambda k,v: Graph\n )\n\n groups = vodka.config.Attribute(\n dict,\n default={},\n help_text=\"data groups\"\n )\n\n # application methods\n\n def setup(self):\n super(GraphServ, self).setup()\n self.layout_last_sync = 0\n graphsrv.group.add_all(self.get_config(\"groups\"))\n\n def data(self, source):\n data, _ = graphsrv.group.get_from_path(source)\n return data\n\n def data_type(self, source):\n return source\n\n def overview_read_file(self):\n return \"\"\n\n def sync_layout_config(self):\n path = self.get_config(\"layout_config_file\")\n mtime = os.path.getmtime(path)\n\n\n if not self.layout_last_sync or self.layout_last_sync != mtime:\n self.log.debug(\"%s has changed, reloading layout config...\"%path)\n self.layouts= vodka.config.Config()\n self.layouts.read(config_file=path)\n self.layout_last_sync = mtime\n\n return self.layouts\n \n\n def overview_view(self):\n \"\"\"\n Renders the overview which can hold several graphs\n and is built via config\n \"\"\"\n self.sync_layout_config()\n \n layouts = self.layouts.get(\"layouts\")\n graphs = self.config.get(\"graphs\")\n\n if \"layout\" in request.args:\n _layout = layouts.get(request.args[\"layout\"])\n else:\n _layout = list(layouts.values())[0]\n\n layout = copy.deepcopy(_layout)\n \n source = layout.get(\"source\", request.args.get(\"source\"))\n\n if source:\n title = layout.get(\"title\", source)\n else:\n title = layout.get(\"title\", \"overview\")\n\n sources = [source]\n\n ids = 1\n\n if layout.get(\"type\") == \"index\":\n # index layout, auto generate grid\n\n grid = [int(x) for x in layout.get(\"grid\", \"3x3\").split(\"x\")]\n\n sources = layout.get(\"sources\", graphsrv.group.get_paths())\n\n layout[\"layout\"] = [\n {\n \"cols\" : [\n {\n \"graph\" : copy.deepcopy(layout.get(\"graph\")),\n \"width\" : int(old_div(12,grid[0]))\n } for _ in range(0, grid[0])\n ],\n \"height\" : float(old_div(100.00,float(grid[1])))\n } for _ in range(0, grid[1])\n ]\n \n\n for row in layout.get(\"layout\"):\n for col in row.get(\"cols\",[]):\n if \"graph\" in col:\n cfg = graphs.get(col[\"graph\"].get(\"config\"))\n if \"targets\" not in cfg:\n cfg[\"targets\"] = [{\"target\":\"all\"}]\n\n col[\"graph\"][\"config_dict\"] =cfg\n if layout.get(\"type\") == \"index\":\n if sources:\n col[\"graph\"][\"source\"] = sources.pop(0)\n if not col[\"graph\"].get(\"id\"):\n col[\"graph\"][\"id\"] = \"auto-%s\" % ids\n ids +=1 \n else:\n col[\"graph\"][\"source\"] = sources[0]\n\n return self.render(\n \"overview.html\", \n self.wsgi_plugin.request_env(layout=layout, source=source, title=title)\n )\n \n def graph_view(self):\n \"\"\"\n Renders graph.js\n \"\"\"\n\n source = request.args.get(\"source\")\n \n if not source:\n raise ValueError(\"No source specified\")\n\n data_type = self.data_type(source)\n\n graphs = self.config.get(\"graphs\")\n\n source_config = graphsrv.group.get_config_from_path(source)\n\n if \"config\" in request.args:\n graph_config = graphs.get(request.args.get(\"config\"))\n else:\n graph_config = {}\n\n valid_tick_sizes = graph_config.get(\"sizes_x\", [3000])\n tick_size = int(request.args.get(\"size\", valid_tick_sizes[0]))\n\n if tick_size not in valid_tick_sizes:\n tick_size = valid_tick_sizes[0]\n \n graph_types = []\n for _, g in list(graphs.items()):\n if g.get(\"type\") not in graph_types:\n graph_types.append(g.get(\"type\"))\n\n\n variables = {\n \"type\" : request.args.get(\"type\", \"multitarget\"),\n \"source\" : source,\n \"graph_types\" : graph_types,\n \"graphConfig\" : graph_config,\n \"maxTicks\" : int(self.config.get(\"max_ticks\", 500)),\n \"dataType\" : data_type,\n \"tickSize\" : tick_size,\n \"targets\" : request.args.get(\"targets\", \"\"),\n \"fit\" : request.args.get(\"fit\", \"no\"),\n \"id\" : request.args.get(\"id\", str(uuid.uuid4()))\n } \n\n # for detail charts we only allow one target\n if variables[\"type\"] in [\"detail\"]:\n variables[\"targets\"] = variables[\"targets\"].split(\",\")[0]\n\n self.sync_layout_config()\n\n variables[\"graphConfig\"][\"targets\"] = graphsrv.group.get_config_from_path(source).get(\"targets\")\n\n return self.render(\"graph.js\", self.wsgi_plugin.request_env(**variables))\n\n def collect_targets(self, data, source):\n for row in self.data(source):\n for target in list(row[\"data\"].keys()):\n if target not in data and target[0] != \"_\":\n data.append(target)\n\n\n @vodka.data.renderers.RPC(errors=True)\n def targets(self, data, *args, **kwargs):\n \"\"\"\n Returns a json response containing all available\n targets (that have been collected from incoming\n data)\n \"\"\"\n source = request.values.get(\"source\")\n \n if not source:\n raise ValueError(\"No source specified\")\n\n self.collect_targets(data, source)\n\n\n def collect_graph_data(self, data, targets, source, ts=0.0):\n\n \"\"\"\n collect graph data from specified source\n\n data <list> - collect into this container\n targets <list> - list of target ids, only collect those targets\n source <str> - storage data id\n ts <float> - if specified only collect targets that were updated past this timestamp (seconds)\n \"\"\"\n\n \n cdata = self.data(source)\n\n for row in cdata:\n if ts and ts >= row[\"ts\"]:\n continue\n\n rdata = row[\"data\"]\n \n rv_row = {\"ts\" : row[\"ts\"], \"data\":{}}\n\n if \"all\" in targets:\n for target,bars in list(rdata.items()):\n rv_row[\"data\"][target] = bars\n else:\n for target in targets:\n if target in rdata:\n rv_row[\"data\"][target] = rdata.get(target)\n \n data.append(rv_row)\n \n\n\n @vodka.data.renderers.RPC(errors=True)\n def graph_data(self, data, *args, **kwargs):\n \"\"\"\n Returns a json response containing graph data\n \"\"\"\n\n targets = request.values.get(\"targets\",\"\").split(\",\")\n ts = float(request.values.get(\"ts\",0))\n source = request.values.get(\"source\")\n\n if not source:\n raise ValueError(\"No source specified\")\n\n if not len(targets):\n raise ValueError(\"Target targets missing\")\n\n self.collect_graph_data(data, targets, source, ts=ts)\n \n \n \n","sub_path":"graphsrv/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":10137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"343162846","text":"import pypcd\nimport os\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\nfrom sklearn import mixture\nfrom itertools import cycle\n\n\n# Input file\nsrc_file = \"~/Research/jresearch/2016-06-23-textiles-ironing/hoodie2/colored_mesh_1.ply-output.pcd\"\nsrc_file = os.path.abspath(os.path.expanduser(src_file))\n\nif __name__ == \"__main__\":\n # Load point cloud\n point_cloud = pypcd.PointCloud.from_path(src_file)\n\n # center the point cloud (xy)\n point_cloud.pc_data['x'] -= point_cloud.pc_data['x'].mean()\n point_cloud.pc_data['y'] -= point_cloud.pc_data['y'].mean()\n\n data = point_cloud.pc_data\n X = np.array([ [i, j, k] for (i, j, k) in zip(data['x'], data['y'], data['z'])])\n\n fig = plt.figure()\n #ax = fig.add_subplot(111, projection='3d')\n #ax.scatter(data[:,0], data[:,1], data[:,2], c='r', marker='o')\n plt.scatter(X[:,0], X[:,1], c='r', marker='.')\n plt.show()\n\n lowest_bic = np.infty\n bic = []\n n_components_range = range(1, 27)\n cv_types = ['spherical', 'tied', 'diag', 'full']\n for cv_type in cv_types:\n for n_components in n_components_range:\n # Fit a mixture of Gaussians with EM\n gmm = mixture.GMM(n_components=n_components, covariance_type=cv_type)\n gmm.fit(X)\n bic.append(gmm.bic(X))\n if bic[-1] < lowest_bic:\n lowest_bic = bic[-1]\n best_gmm = gmm\n\n bic = np.array(bic)\n color_iter = cycle(['k', 'r', 'g', 'b', 'c', 'm', 'y'])\n clf = best_gmm\n bars = []\n\n # Plot the BIC scores\n spl = plt.subplot(2, 1, 1)\n for i, (cv_type, color) in enumerate(zip(cv_types, color_iter)):\n xpos = np.array(n_components_range) + .2 * (i - 2)\n bars.append(plt.bar(xpos, bic[i * len(n_components_range):\n (i + 1) * len(n_components_range)],\n width=.2, color=color))\n plt.xticks(n_components_range)\n plt.ylim([bic.min() * 1.01 - .01 * bic.max(), bic.max()])\n plt.title('BIC score per model')\n xpos = np.mod(bic.argmin(), len(n_components_range)) + .65 +\\\n .2 * np.floor(bic.argmin() / len(n_components_range))\n plt.text(xpos, bic.min() * 0.97 + .03 * bic.max(), '*', fontsize=14)\n spl.set_xlabel('Number of components')\n spl.legend([b[0] for b in bars], cv_types)\n\n plt.show()","sub_path":"ironing/perception/wrinkle_detector.py","file_name":"wrinkle_detector.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"362438747","text":"# -*- encoding: utf-8 -*-\n'''\n@Filename : settings.py\n@Datetime : 2020/08/31 16:18:07\n@Author : Joe-Bu\n@version : 1.0\n'''\n\n\"\"\" 评价配置文件 \"\"\"\n\nfrom datetime import datetime\n\n\n''' Normal Prams '''\nstart = datetime(2020, 7, 10, 0, 0)\n# start = datetime(2020, 7, 31, 0, 0)\nend = datetime(2020, 8, 1, 0, 0)\n\nTZONE = 30\nINDEX = 'CODMn'\nFREQ = 4\nSCALE = 42\nEVALUATE_SCALE = 42\n\n# ------------------------\n\n''' Path Params '''\n\npaths = dict(\n in_path = r'../../output',\n out_path = r'../../output/',\n out_eval = r'../../output/evaluate/{0}/{1}/'.format(INDEX, EVALUATE_SCALE),\n model_path = r'../../model'\n)\n# filename = u'沿江渡4h验证原始数据-线性扩展.xls'\nfilename = u'洛宁长水4h验证原始数据-线性扩展.xls'\n","sub_path":"src/DataEvaluate/.ipynb_checkpoints/settings-checkpoint.py","file_name":"settings-checkpoint.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"40269899","text":"my = __import__(\"0071_custom_singly_linked_list\")\r\n\r\ndef sumList(llA, llB):\r\n n1 = llA.head\r\n n2 = llB.head\r\n carry = 0\r\n ll = my.LinkedList()\r\n while n1 or n2:\r\n result = carry\r\n if n1:\r\n result += n1.value\r\n n1 = n1.next\r\n if n2:\r\n result += n2.value\r\n n2 = n2.next\r\n ll.add(int(result % 10))\r\n carry = result / 10\r\n if int(carry) != 0:\r\n ll.add(int(carry))\r\n return ll\r\n\r\nllA = my.LinkedList()\r\nllA.add(2)\r\nllA.add(0)\r\nllA.add(5)\r\n\r\nllB = my.LinkedList()\r\nllB.add(9)\r\nllB.add(6)\r\nllB.add(5)\r\n\r\nprint(llA)\r\nprint(llB)\r\n\r\nprint(sumList(llA, llB))\r\n","sub_path":"zzz_dsa/python_dsa_2/0075_sum_of_2_nos_reversed_in_2_linked_lists.py","file_name":"0075_sum_of_2_nos_reversed_in_2_linked_lists.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"574352777","text":"import datetime\nimport pytest\nfrom dateutil.tz import tzutc\nimport accloudtant.aws.instance\nfrom conftest import MockEC2Instance\n\n\ndef test_instance():\n az = 'us-east-1b'\n region = 'us-east-1'\n instance_data = {\n 'id': 'i-1840273e',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'app1',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': az,\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'RHEL Linux', },\n }\n\n\n ec2_instance = MockEC2Instance(instance_data)\n instance = accloudtant.aws.instance.Instance(ec2_instance)\n\n assert(instance.id == ec2_instance.id)\n assert(instance.reserved == 'No')\n assert(instance.name == ec2_instance.tags[0]['Value'])\n assert(instance.size == ec2_instance.instance_type)\n assert(instance.availability_zone == az)\n assert(instance.region == region)\n assert(instance.operating_system == 'Red Hat Enterprise Linux')\n assert(instance.key == 'rhel')\n assert(instance.state == ec2_instance.state['Name'])\n assert(instance.current == 0.0)\n assert(instance.best == 0.0)\n\n with pytest.raises(ValueError):\n instance.reserved = 'Maybe'\n\n instance.current = 0.392\n instance.best = 0.293\n\n assert(instance.current == 0.392)\n assert(instance.best == 0.293)\n\n\ndef test_guess_os():\n instance_data_win = {\n 'id': 'i-912a4392',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'web1',\n }, ],\n 'instance_type': 'c3.8xlarge',\n 'placement': {\n 'AvailabilityZone': 'us-east-1c',\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc(),\n ),\n 'console_output': {'Output': 'Windows', },\n }\n instance_data_rhel = {\n 'id': 'i-1840273e',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'app1',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': 'us-east-1b',\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'RHEL Linux', },\n }\n instance_data_sles = {\n 'id': 'i-9840273d',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'app2',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': 'us-east-1c',\n },\n 'state': {\n 'Name': 'stopped',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'SUSE Linux', },\n }\n instance_data_linux = {\n 'id': 'i-1840273c',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'database2',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': 'us-east-1c',\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'Linux', },\n }\n\n ec2_instance_win = MockEC2Instance(instance_data_win)\n ec2_instance_rhel = MockEC2Instance(instance_data_rhel)\n ec2_instance_sles = MockEC2Instance(instance_data_sles)\n ec2_instance_linux = MockEC2Instance(instance_data_linux)\n instance_win = accloudtant.aws.instance.Instance(ec2_instance_win)\n instance_rhel = accloudtant.aws.instance.Instance(ec2_instance_rhel)\n instance_sles = accloudtant.aws.instance.Instance(ec2_instance_sles)\n instance_linux = accloudtant.aws.instance.Instance(ec2_instance_linux)\n\n assert(instance_win.operating_system == 'Windows')\n assert(instance_rhel.operating_system == 'Red Hat Enterprise Linux')\n assert(instance_sles.operating_system == 'SUSE Linux')\n assert(instance_linux.operating_system == 'Linux/UNIX')\n\n\ndef test_match_reserved_instance():\n az = 'us-east-1b'\n instance_data = {\n 'id': 'i-1840273e',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'app1',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': az,\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'RHEL Linux', },\n }\n reserved_instance = {\n 'ProductDescription': 'Red Hat Enterprise Linux',\n 'InstanceTenancy': 'default',\n 'InstanceCount': 1,\n 'InstanceType': 'r2.8xlarge',\n 'Start': datetime.datetime(\n 2011,\n 6,\n 5,\n 6,\n 20,\n 10,\n 494000,\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n 'End': datetime.datetime(\n 2011,\n 6,\n 5,\n 6,\n 20,\n 10,\n tzinfo=tzutc()\n ),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233321',\n 'FixedPrice': 910.0,\n 'AvailabilityZone': 'us-east-1b',\n 'UsagePrice': 0.12,\n 'Duration': 31536000,\n 'State': 'active',\n }\n\n ec2_instance = MockEC2Instance(instance_data)\n instance = accloudtant.aws.instance.Instance(ec2_instance)\n reserved_instance['InstancesLeft'] = reserved_instance['InstanceCount']\n\n assert(instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['State'] = 'pending'\n\n assert(not instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['State'] = 'active'\n reserved_instance['InstancesLeft'] = 0\n\n assert(not instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['InstacesLeft'] = 1\n reserved_instance['ProductDescription'] = 'Windows'\n\n assert(not instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['ProductionDescription'] = 'Red Hat Enterprise Linux'\n reserved_instance['InstaceType'] = 't1.micro'\n\n assert(not instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['InstaceType'] = 'r2.8xlarge'\n reserved_instance['AvailabilityZone'] = 'us-east-1c'\n\n assert(not instance.match_reserved_instance(reserved_instance))\n","sub_path":"tests/aws/test_instance.py","file_name":"test_instance.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"225855224","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 7 14:53:43 2019\r\n\r\n@author: vr_lab\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pdb\r\nimport random\r\nimport vtk\r\n\r\ndef select_points(filename):\r\n reader = vtk.vtkSTLReader()\r\n reader.SetFileName(filename)\r\n reader.Update()\r\n data = reader.GetOutput() \r\n n_points = data.GetNumberOfPoints()\r\n mesh_points = np.zeros([n_points, 3])\r\n for i in range(n_points):\r\n mesh_points[i][0], mesh_points[i][1], mesh_points[i][\t2] = data.GetPoint(i)\r\n point_indices = []\r\n for i in range(0,20):\r\n point_index = random.randint(1, n_points)\r\n point_indices.append(mesh_points[point_index, :]) \r\n return point_indices\r\n\r\ndef write_to_file(filename, points):\r\n output_file = open(filename, 'w')\r\n for index, point in enumerate(points):\r\n output_file.write(str(index) + ' ' + str(point[0]) + ' ' + str(point[1]) + \r\n ' ' + str(point[2]) + '\\n')\r\n output_file.close()\r\n \r\nif __name__ == '__main__':\r\n input_file = 'FGlandular.stl'\r\n output_file = \"Fat_Solid_32837pointspoints.a.node\"\r\n points = select_points(input_file)\r\n write_to_file(output_file, points)","sub_path":"ChangeAbaqusInput/random_select_point_from_organ.py","file_name":"random_select_point_from_organ.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"262431134","text":"from itertools import starmap\nfrom typing import Dict, List, Tuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch_scatter as scatter\n\nfrom transformers.configuration_bert import BertConfig\nfrom transformers.modeling_bert import BertForSequenceClassification as OrigBertForSequenceClassification\nfrom transformers.modeling_bert import BertModel, BertPreTrainedModel\n\n\nclass SimpleConcatAvgMaxTokensPooler(nn.Module):\n def __init__(self, config):\n super(SimpleConcatAvgMaxTokensPooler, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool1d(1)\n self.max_pool = nn.AdaptiveMaxPool1d(1)\n\n def forward(self, tokens_embs: torch.Tensor, *args) -> torch.Tensor: # type: ignore\n return torch.cat([self.avg_pool(tokens_embs).squeeze(), self.max_pool(tokens_embs).squeeze()], dim=0).squeeze()\n\n\nclass SimpleAvgOrMaxTokensPoolerWithMask(nn.Module):\n def __init__(self, config):\n super(SimpleAvgOrMaxTokensPoolerWithMask, self).__init__()\n word_tokens_pooling_method = getattr(config, \"word_tokens_pooling_method\", \"\").lower().capitalize()\n self.pooler = getattr(nn, f\"Adaptive{word_tokens_pooling_method}Pool1d\")(1)\n\n def forward(self, tensor: torch.Tensor) -> torch.Tensor:\n return self.pooler(tensor).squeeze()\n\n\nclass CustomBertForNer(BertPreTrainedModel):\n def __init__(self, config):\n super(CustomBertForNer, self).__init__(config)\n word_tokens_pooling_method = getattr(config, \"word_tokens_pooling_method\", \"\").lower()\n linear_hidden_size_mult = 1\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n if word_tokens_pooling_method in [\"avg\", \"max\"]:\n self.tokens_pooler = SimpleAvgOrMaxTokensPoolerWithMask(config)\n elif word_tokens_pooling_method == \"concatavgmax\":\n self.tokens_pooler = SimpleConcatAvgMaxTokensPooler(config)\n linear_hidden_size_mult = 2\n\n self.classifier = nn.Linear(config.hidden_size * linear_hidden_size_mult, config.num_labels)\n\n self.init_weights()\n\n def _convert_bert_outputs_to_map(self, outputs: Tuple[torch.Tensor, ...]) -> Dict[str, torch.Tensor]:\n outputs_map = dict(last_hidden_state=outputs[0], pooler_output=outputs[1])\n\n if len(outputs) > 2:\n outputs_map[\"hidden_states\"] = outputs[2]\n if len(outputs) > 3:\n outputs_map[\"attentions\"] = outputs[3]\n\n return outputs_map\n\n def forward(\n self,\n input_ids,\n word_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n labels=None,\n ):\n outputs = self.bert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n )\n outputs = self._convert_bert_outputs_to_map(outputs)\n sequence_output = outputs[\"last_hidden_state\"]\n\n if word_ids is not None and hasattr(self, \"tokens_pooler\"):\n\n word_ids[word_ids == -100] = -1\n\n _word_ids = word_ids.unsqueeze(-1) + 1\n _mean = scatter.scatter_mean(sequence_output, _word_ids, dim=1).type(sequence_output.dtype)\n _mean[:, 0, :] = sequence_output[:, 0, :]\n _max = scatter.scatter_max(sequence_output, _word_ids, dim=1, fill_value=0)[0].type(sequence_output.dtype)\n _max[:, 0, :] = sequence_output[:, 0, :]\n sequence_output = torch.cat([_mean, _max], dim=-1)\n\n word_ids[word_ids == -1] = -100\n\n if labels is not None:\n\n def transform_ids(word_ids: torch.Tensor, labels: torch.Tensor, pad_id: int = -100) -> torch.Tensor:\n word_labels = labels[\n word_ids[word_ids != pad_id].unique_consecutive(return_counts=True)[1].cumsum(dim=0) - 1\n ]\n tensor = F.pad(\n word_labels, (0, sequence_output.shape[1] - 1 - word_labels.shape[0]), value=pad_id,\n )\n return tensor\n\n labels = torch.stack(list(starmap(transform_ids, zip(word_ids[:, 1:], labels[:, 1:]))), dim=0)\n labels = torch.cat((torch.tensor(-100).repeat(labels.shape[0], 1).to(labels.device), labels), dim=1)\n attention_mask = torch.zeros_like(labels)\n attention_mask[labels != -100] = 1\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n if labels is not None:\n loss_fct = nn.CrossEntropyLoss()\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1).type(torch.bool)\n active_logits = logits.view(-1, self.config.num_labels)[active_loss]\n active_labels = labels.view(-1)[active_loss]\n loss = loss_fct(active_logits, active_labels)\n else:\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n outputs[\"loss\"] = loss\n\n outputs[\"attention_mask\"] = attention_mask\n outputs[\"logits\"] = logits\n\n if labels is not None:\n outputs[\"labels\"] = labels\n\n return outputs # (loss), scores, (hidden_states), (attentions)\n\n\nclass CustomBertForQuestionAnswering(BertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config)\n self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n def forward(\n self,\n input_ids,\n attention_mask=None,\n num_question_tokens=None,\n position_ids=None,\n head_mask=None,\n start_positions=None,\n end_positions=None,\n ):\n batch_size, seq_len = input_ids.shape\n windowed_mode = False\n\n if seq_len > self.config.max_position_embeddings:\n assert batch_size == 1, \"sliding window mode is not currently supported for batch_size > 1\"\n assert position_ids is None\n assert isinstance(num_question_tokens, int)\n\n windowed_mode = True\n\n input_ids = torch.squeeze(input_ids, dim=0)\n question_ids, paragraph_ids = torch.split(input_ids, [num_question_tokens, seq_len - num_question_tokens])\n windowed_paragraph_ids, paragraph_position_ids = self._apply_sliding_window_to_single_batch(\n paragraph_ids, self.config.max_position_embeddings - num_question_tokens\n )\n\n batch_size = windowed_paragraph_ids.shape[0]\n seq_len = self.config.max_position_embeddings\n\n input_ids = torch.cat(\n (question_ids.unsqueeze(0).expand(batch_size, num_question_tokens), windowed_paragraph_ids,), dim=-1,\n )\n\n if num_question_tokens is None:\n num_question_tokens = seq_len\n\n if isinstance(num_question_tokens, int):\n token_type_ids = (\n self._create_type_tokens_for_single_batch(num_question_tokens, seq_len)\n .unsqueeze(0)\n .expand(batch_size, seq_len)\n )\n else:\n token_type_ids = torch.stack(\n [\n self._create_type_tokens_for_single_batch(num_in_batch, seq_len)\n for num_in_batch in num_question_tokens\n ]\n )\n\n token_type_ids = token_type_ids.to(input_ids.device)\n\n outputs = self.bert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n )\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n if windowed_mode:\n question_logits, paragraph_logits = torch.split(\n logits, [num_question_tokens, seq_len - num_question_tokens], dim=1\n )\n\n question_logits = question_logits.min(dim=0, keepdim=True)[0]\n paragraph_logits = self._compress_sliding_window(paragraph_logits, paragraph_position_ids)\n\n logits = torch.cat((question_logits, paragraph_logits), dim=1)\n\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n\n outputs = (start_logits, end_logits) + outputs[2:]\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions.clamp_(0, ignored_index)\n end_positions.clamp_(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n outputs = (total_loss,) + outputs\n\n return outputs # (loss), start_logits, end_logits, (hidden_states), (attentions)\n\n def _create_type_tokens_for_single_batch(self, num_question_tokens, seq_len):\n return torch.cat([torch.zeros(num_question_tokens), torch.ones(seq_len - num_question_tokens)]).long()\n\n def _apply_sliding_window_to_single_batch(self, tokens, window_size=512, window_stride=None):\n if window_stride is None:\n window_stride = window_size // 2\n\n result_batch = []\n result_positions = []\n\n start = end = 0\n while end < len(tokens):\n end = min(start + window_size, len(tokens))\n start = end - window_size # this allows to avoid shorter last window\n\n result_batch.append(tokens[start:end])\n result_positions.append(torch.arange(start, end))\n\n start += window_stride\n\n return torch.stack(result_batch), torch.stack(result_positions)\n\n def _compress_sliding_window(self, windowed_tokens, positions):\n num_tokens = positions.max() + 1\n window_size = windowed_tokens.shape[1]\n\n middle_positions = positions[:, window_size // 2]\n tokens_best_window_idxs = (\n (torch.unsqueeze(middle_positions, 0) - torch.arange(num_tokens).unsqueeze(-1)).abs().argmin(dim=1)\n )\n token_mask = torch.stack(\n [\n tokens_best_window_idxs[token_idxs_in_window] == window_idx\n for window_idx, token_idxs_in_window in enumerate(positions)\n ]\n )\n\n return windowed_tokens[token_mask].unsqueeze(0)\n\n\nclass BertForSequenceClassification(OrigBertForSequenceClassification):\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n model = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n pooler_name = kwargs.get(\"pooler\", None)\n if pooler_name and pooler_name.lower().startswith(\"concat\"):\n model.classifier = nn.Linear(model.config.hidden_size * 2, model.config.num_labels)\n return model\n","sub_path":"src/transformers/customs/modeling_bert.py","file_name":"modeling_bert.py","file_ext":"py","file_size_in_byte":11620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"255779250","text":"import cv2 as cv\r\nimport numpy as np\r\nimport tensorflow.contrib.slim as slim\r\nimport os\r\nimport tensorflow as tf\r\nimport random\r\nimport glob\r\nfrom tensorflow.python.framework import graph_util\r\nfrom tensorflow.python.platform import gfile \r\nimport shutil\r\n\r\ndata_test_dir = 'ucf_101_img_mul12_NECK'\r\ndata_train_dirs = ['ucf_101_img_centre_NECK','ucf_101_img_mul12_NECK','ucf_101_img_centre_top8_F_NECK']\r\nCLASS_NUM = 101\r\nBATCH_SIZE = 50\r\nlearning_rate = 0.0001\r\nITEMS = 3000\r\ndrop_rate = 0.9\r\nSPLIT_PATH = 'ucfTrainTestlist/testlist02.txt'\r\nLABEL_PATH = 'ucfTrainTestlist/classInd.txt'\r\nMODEL_DIR = 'models/'\r\nMODEL_FILE = 'SA_v1_0.759.pb'\r\nGPU = '0'\r\nTOP_DIR = 'ucf_101_img_mul12_top8'\r\nMID_DIR = 'ucf_101_img_mul12_mid35'\r\nNECK_DIR = 'ucf_101_img_mul12_NECK'\r\nOUT_DIR = 'ucf_101_img_mul12_NECK_OUT'\r\n# pb_file_path = 'full_ucfs1.pb'\r\ntest_dir = {'neck':NECK_DIR, 'top':TOP_DIR, 'pre_out':OUT_DIR, 'mid':MID_DIR}\r\ntarget_dir = {'neck':NECK_DIR+'_max2', 'top':TOP_DIR+'_max2', 'pre_out':OUT_DIR+'_max2', 'mid':MID_DIR+'_max2'}\r\n# 'neck', 'pre_out', 'top', 'if_train'\r\nshape = {'neck':(2048),'top':(8,8,1280),'mid':(35,35,288),'pre_out':(101)}\r\nmax_file = 'UCF_101_s2_SA_max.txt'\r\n\r\n\r\nclass convert_max():\r\n def __init__(self, test_dir, target_dir, max_file):\r\n self.sourse_dir = test_dir\r\n self.target_dir = target_dir\r\n self.max_file = max_file\r\n self.read_max_list()\r\n print(\"has read\")\r\n for kk in test_dir.keys():\r\n self.copy2target(self.sourse_dir[kk], self.target_dir[kk])\r\n def initial(self,dic):\r\n keys = dic.keys()\r\n for key in keys:\r\n dic[key] = []\r\n def copy2target(self, sourse_dir, target_dir):\r\n for path, index, class_name in self.max_info:\r\n glob_path = os.path.join(sourse_dir,class_name,path)+\"*\"\r\n glob_list = sorted(glob.glob(glob_path))\r\n target_path = os.path.join(target_dir,class_name,path)+'.txt'\r\n if not os.path.exists(os.path.dirname(target_path)):\r\n os.makedirs(os.path.dirname(target_path))\r\n print(os.path.dirname(target_path))\r\n shutil.copyfile(glob_list[index], target_path)\r\n def read_max_list(self):\r\n self.max_info = []\r\n with open(self.max_file) as f:\r\n line = f.readline()\r\n while len(line) > 0:\r\n lines = line.split(',')\r\n index = int(lines[1])\r\n path = os.path.basename(lines[0])\r\n class_name = os.path.basename(os.path.dirname(lines[0]))\r\n self.max_info.append((path, index, class_name))\r\n line = f.readline()\r\n\r\nconvert_max(test_dir, target_dir, max_file)\r\n\r\n\r\n # acc_list = []\r\n # index_list = []\r\n\r\n # input_tensor = tf.placeholder(dtype=tf.float32, shape=[None,192], name='input_tensor')\r\n # label_index = tf.placeholder(dtype=tf.int64, shape=[None], name='label_index')\r\n # label = tf.one_hot(label_index, CLASS_NUM)\r\n # logits = graph_def(input_tensor)\r\n # cross_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=label,logits=logits))\r\n # slim.losses.add_loss(cross_loss)\r\n # total_loss = slim.losses.get_total_loss()\r\n # train_op = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)\r\n # pre_out = tf.nn.softmax(logits, name='output')\r\n # predict_label = tf.argmax(logits,1)\r\n # correct_prediction = tf.equal(tf.argmax(label,1), tf.argmax(logits,1))\r\n # accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n\r\n # with tf.Session(config=cuda_set(gpu='1')) as sess:\r\n # sess.run( tf.global_variables_initializer())\r\n # print(data_test_dir)\r\n # for i in range(ITEMS):\r\n # train_batch, label_batch = get_train_batch(train_path_list, train_label_list, test_set)\r\n # if (i+1)%100 == 0 :\r\n # _, loss, acc = sess.run([train_op, total_loss, accuracy],\r\n # feed_dict={input_tensor:train_batch, label_index:label_batch})\r\n # test_acc, test_loss = sess.run([accuracy, total_loss], feed_dict={input_tensor:test_batch, label_index:test_label_batch})\r\n # print(test_acc)\r\n # print(\"step %6d loss=%f acc=%f TEST_acc : %f Test_loss=%f\"%(i+1, loss, acc, test_acc, test_loss))\r\n # with open('ucf-101-img-combine-record.txt','a') as f:\r\n # acc_str = 'Step %05d TEST_acc : %f '%(i, test_acc)+'\\n'\r\n # f.write(acc_str)\r\n # else:\r\n # sess.run([train_op], feed_dict={input_tensor:train_batch, label_index:label_batch})\r\n # # _, test_acc[0] = sess.run([train_op, accuracy], feed_dict={input_tensor:test_batch, label_index:test_label_batch})\r\n # # print('TEST_acc : %f '%(test_acc[0]) )\r\n # # with open('ucf-101-img-combine-record.txt','a') as f:\r\n # # acc_str = 'TEST_acc : %f '%(test_acc[0])\r\n # # f.write(acc_str)\r\n # constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, [\"output\"])\r\n # with tf.gfile.FastGFile(pb_file_path, mode='wb') as f:\r\n # f.write(constant_graph.SerializeToString())\r\n\r\n\r\n# if __name__ == '__main__' :\r\n# # get_center_frame(data_path)\r\n# main()\r\n","sub_path":"SA_101_save_max_mid.py","file_name":"SA_101_save_max_mid.py","file_ext":"py","file_size_in_byte":5302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"402532229","text":"from tkinter import *\nimport tkinter as tk\nimport PIL\nfrom PIL import ImageTk, Image\nimport glob\nimport os\n\n# --- functions ---\n\ni = 0\nimg=0\nimagelist=[]\nimagelistname=[]\npath = 'injest/*'\nequipnumberentry = \"\"\nimagelableentry = \"\" \nimageorderentry = \"\"\nyup=\"\"\n\n\ndef text_mod():\n global i, btn2, imagelist, image, imagelistname, yup # btn can be omitted but not sure if should be\n btn2['text'] = imagelistname[i] # the global object that is modified\n yup = imagelistname[i]\n photo = load_images()\n i = (i + 1) % len(imagelistname) # another global object that gets modified\n item4 = canvas.create_image(209, 164, image=photo)\n root.mainloop()\n\ndef load_images():\n global i, btn2, imagelist, image,imagelistname, yup\n image = Image.open(yup)\n basewidth = 900\n #wpercent = (basewidth / float(image.size[0]))\n #hsize = int((float(image.size[1]) * float(wpercent)))\n image = image.resize((418,328), PIL.Image.ANTIALIAS)\n photo = ImageTk.PhotoImage(image)\n image.close()\n return photo\n\ndef resize_Image(simage):\n im = Image.open(simage)\n if im.width != 318 and im.height != 228:\n resized_im = im.resize((318,228))\n resized_im.save(simage)\n im.close()\n\ndef injest_image():\n global imagelableentry, imageorderentry, imagelistname, equipnumberentry, yup\n im = Image.open(yup)\n if im.width != 318 and im.height != 228:\n im = im.resize((318,228))\n s1=str(equipnumberentry.get())\n s2=str(imagelableentry.get())\n s3=str(imageorderentry.get())\n if not os.path.exists(\"images/\"+s1):\n os.makedirs(\"images/\"+s1)\n\n im.save(\"images/\"+s1+\"/\"+s2+\" \"+str(s3)+\".jpg\")\n im.close()\n os.remove(yup)\n imagelistname.remove(yup)\ndef image_reload():\n global imagelist, imagelistname\n imagelistname=[]\n imagelist=[]\n for filename in glob.glob(path+'/*.jpg'): #assuming gif\n im=Image.open(filename)\n imagelist.append(im)\n imagelistname.append(filename)\n im.close()\nroot=Tk()\n\n\nfor filename in glob.glob(path+'/*.jpg'): #assuming gif\n im=Image.open(filename)\n imagelist.append(im)\n imagelistname.append(filename)\n im.close()\n\ncanvas=Canvas(root, height=330, width=1000)\n\neqnlable = tk.Label(root, text='Equipment Number:')\neqnlable.config(font=('helvetica', 10))\ncanvas.create_window(550, 140, window=eqnlable)\nequipnumberentry = tk.Entry (root) \ncanvas.create_window(680, 140, window=equipnumberentry)\n\nimglable = tk.Label(root, text='Image lable:')\nimglable.config(font=('helvetica', 10))\ncanvas.create_window(550, 160, window=imglable)\nimagelableentry = tk.Entry (root) \ncanvas.create_window(680, 160, window=imagelableentry)\n\nimgorder = tk.Label(root, text='Image order ( 1-6 ):')\nimgorder.config(font=('helvetica', 10))\ncanvas.create_window(550, 180, window=imgorder)\nimageorderentry = tk.Entry (root) \ncanvas.create_window(680, 180, window=imageorderentry)\n\nbtn = tk.Button(root, text=\"Reload Image List\", height=2)\nbtn['command'] = image_reload\n\nbtn = tk.Button(root, text=\"Injest Image\", height=2, width = 20)\nbtn['command'] = injest_image\n\nbtn2 = tk.Button(root, text=\"Cycle Images\",height=2)\nbtn2['command'] = text_mod\n\nbtn.pack(fill='both', expand=True)\nbtn.place(x=600, y=300)\nbtn2.pack(fill='both', expand=True)\ncanvas.pack(side = TOP, expand=True, fill=BOTH)\nroot.mainloop()\n","sub_path":"ImageInjest.py","file_name":"ImageInjest.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"69484259","text":"\nfrom dNode import Node\n\nclass Dlist:\n def __init__(self):\n self.head= None\n\n def is_empty(self):\n return self.head ==None #if none, empty is true\n\n def add(self,item): #add at the start of list\n if self.head == None: #if the list is empty\n self.head = Node(item) #set the head's inference to the new item\n else:\n temp = Node(item)\n temp.set_next(self.head) #set the next of the item to the head\n self.head.set_previous(temp) #set the head's inference previous to temp\n self.head = temp #make the temp head\n\n def append(self,item): #add item at last\n if self.head == None: #when the list is empty, append at head\n self.head = Node(item)\n else: #when not empty list\n current = self.head\n while current.get_next() != None: #while loop until current's next is none: when node is the last node\n current = current.get_next()\n #outside while loop; current's next item is none\n temp = Node(item)\n current.set_next(temp)\n temp.set_previous(current)\n\n def insert_after(self, item, x): #insert new item after x\n if self.head == None: #when empty list there is no x\n print('List is empty!')\n\n else:\n current = self.head\n found = False\n while current != None and not found:\n if current.get_item() == x: #when we found the item we want to insert after\n found = True\n else:\n current = current.get_next()\n\n if found == False: #when x is not found : not in the list\n print('Item is not in the list')\n else:\n #change the inference of temp\n temp = Node(item)\n temp.set_next(current.get_next())\n temp.set_previous(current)\n\n if current.get_next() != None: #current is not the last item of the list\n current.get_next().set_previous(temp)\n #when current is the last item, no need to set the previous to temp since it is none\n\n current.set_next(temp) #set the current's next to temp\n\n\n def insert_before(self,item,x):\n if self.head == None:\n print('List is empty')\n else:\n current= self.head\n found = False\n while current != None and not found : #while until the current object is none(last item) or found\n if current.get_item() == x:\n found = True\n else:\n current = current.get_next()\n\n if found == False:\n print('Item is not in the list')\n\n else: #when the item is in the list\n temp = Node(item)\n temp.set_next(current)\n temp.set_previous(current.get_previous())\n #set the temp's previous and next according to the current item\n\n if current.get_previous() != None: #when the current item is not the first item in list\n current.get_previous().set_next(temp)\n\n else: #when the previous item is None (current is the first item of the list)\n self.head = temp\n current.set_previous(temp)\n def pop_first(self):\n if self.head == None:\n print('List is empty.')\n else:\n if self.head.get_next() ==None: #when there is only one item\n self.head =None #set head to None\n else:\n self.head= self.head.get_next() #make the next item of the head to the head\n self.head.set_previous(None) #make the new head's previous to None ; making it the head\n\n\n def pop_last(self):\n if self.head == None:\n print('List is empty.')\n else:\n if self.head.get_next() == None: #when the list has only one item\n self.head = None #delete that only one item\n else:\n current = self.head\n while current.get_next() != None: #until current's next item is none(last item's get next is none)\n current = current.get_next()\n\n current.get_previous().set_next(None) #set the current's previous to None\n\n def delete(self, item):\n if self.head.get_item() == item: #when the first item is the item we are looking for\n self.head = self.head.get_next()\n self.head.set_previous(None) #make the next item of head to the head and delete the previous inference\n else:\n current =self.head\n found = False\n while not found: #always found is the prerequisite\n if current.get_item() == item:\n found = True\n else:\n current = current.get_next()\n if current.get_next() != None: #when not last item\n current.get_previous().set_next(current.get_next())\n current.get_next().set_previous(current.get_previous())\n else: #when last item\n current.get_previous().set_next(None)\n\n def search(self,item):\n current = self.head\n found = False\n while current != None and not found:\n if current.get_item() == item:\n found = True\n else:\n current = current.get_next()\n return found\n\n def size(self):\n current = self.head\n count = 0\n while current != None: #while not last item\n count += 1\n current = current.get_next()\n return count\n\n\n\n\nd = Dlist()\nprint('is the list empty..? '+str(d.is_empty()))\nd.add(30)\nd.add(20)\nd.add(50)\nd.add(12)\nd.append(22)\nd.append(90)\nprint('the size of the list d is..'+ str(d.size()))\nd.pop_last()\nd.pop_first()\nd.delete(20)\nprint('the size of the list d is..'+ str(d.size()))\nprint('Is the value 22 in the list..? ' +str(d.search(22)))\nd.insert_after(99,30)\nprint('the size of the list d is..'+ str(d.size()))\nd.insert_before(100,30)\nprint('the size of the list d is..'+ str(d.size()))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2020-Data-Structure-Algorithms/dlist.py","file_name":"dlist.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"323952299","text":"from .Tex import Tex\nfrom .constants import QUOTE_FONT_SIZE\n\nclass Quote(Tex):\n \"\"\"\n class that represents a quote\n \"\"\"\n def __init__(self, quote, author='', font_size=QUOTE_FONT_SIZE):\n self.quote = quote\n self.author = author\n self.format = self._format()\n super().__init__(self.format)\n\n def _format(self):\n quote_size = QUOTE_FONT_SIZE\n quote_spacing = QUOTE_FONT_SIZE * 1.2\n\n res = ''\n res += r'\\noindent\\fontsize'\n res += f'{{{quote_size}}}{{{round(quote_spacing)}}}'\n res += rf'\\selectfont \"{self.quote}\"\\\\'\n res += rf'\\rightline{{-{self.author}}}'\n return res\n","sub_path":"objects/typesetting/Quote.py","file_name":"Quote.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551790411","text":"# 4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...Количество элементов (n) вводится с\n# клавиатуры.\n\nSUMS = 0\n\n\n# ---Цикл---\ndef sum_nums(n):\n sums = 0\n num = 1\n for i in range(n):\n sums += num\n num = -(num/2)\n print(f'Сумма {n} элементов ряда: \"1 -0.5 0.25 -0.125 ...\" равна: {sums}')\n\n\n# ---Рекурсия---\ndef sum_nums_2(n, num): # num - элемент последовательности\n global SUMS\n if n == 0:\n return print(f'Сумма элементов ряда: \"1 -0.5 0.25 -0.125 ...\" равна: {SUMS}')\n SUMS += num\n return sum_nums_2(n-1, -(num/2))\n\n\nif __name__ == '__main__':\n N = int(input('Введите кол-во элементов ряда:\\n'))\n sum_nums(N)\n sum_nums_2(N, 1)\n","sub_path":"lesson_2/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"562239536","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nfrom data_utils import (\n load_dialog_task, vectorize_data, load_candidates, vectorize_candidates, tokenize,\n generate_profile_encoding, IdenticalWordIdx\n)\nfrom sklearn import metrics\nfrom memn2n import MemN2NDialog\nfrom itertools import chain\nfrom six.moves import range, reduce\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pickle\nimport pprint\nimport glob\n\ntf.flags.DEFINE_float(\"learning_rate\", 0.001, \"Learning rate for Adam Optimizer.\")\ntf.flags.DEFINE_float(\"epsilon\", 1e-8, \"Epsilon value for Adam Optimizer.\")\ntf.flags.DEFINE_float(\"max_grad_norm\", 40.0, \"Clip gradients to this norm.\")\ntf.flags.DEFINE_integer(\"evaluation_interval\", 10, \"Evaluate and print results every x epochs\")\ntf.flags.DEFINE_integer(\"batch_size\", 32, \"Batch size for training.\")\ntf.flags.DEFINE_integer(\"hops\", 3, \"Number of hops in the Memory Network.\")\ntf.flags.DEFINE_integer(\"epochs\", 200, \"Number of epochs to train for.\")\ntf.flags.DEFINE_integer(\"embedding_size\", 20, \"Embedding size for embedding matrices.\")\ntf.flags.DEFINE_integer(\"memory_size\", 250, \"Maximum size of memory.\")\ntf.flags.DEFINE_integer(\"task_id\", 1, \"task id, 1 <= id <= 5\")\ntf.flags.DEFINE_integer(\"random_state\", None, \"Random state.\")\ntf.flags.DEFINE_string(\"data_dir\", \"../data/personalized-dialog-dataset/full\", \"Directory containing bAbI tasks\")\ntf.flags.DEFINE_string(\"model_dir\", \"model/\", \"Directory containing memn2n model checkpoints\")\ntf.flags.DEFINE_boolean('train', True, 'if True, begin to train')\ntf.flags.DEFINE_boolean('interactive', False, 'if True, interactive')\ntf.flags.DEFINE_boolean('OOV', False, 'if True, use OOV test set')\ntf.flags.DEFINE_boolean('save_vocab', False, 'if True, saves vocabulary')\ntf.flags.DEFINE_boolean('load_vocab', False, 'if True, loads vocabulary instead of building it')\ntf.flags.DEFINE_boolean('verbose', False, \"if True, print different debugging messages\")\ntf.flags.DEFINE_float('alpha', .5, \"Value of the alpha parameter, used to prefer one part of the model\")\ntf.flags.DEFINE_string('experiment', None, \"Choose if any experiment to do\")\nFLAGS = tf.flags.FLAGS\nprint(\"Started Task:\", FLAGS.task_id)\n\n\nclass ChatBot(object):\n \"\"\"\n Handle a chatbot session in sense of data, training and testing. Can be seen as a\n helper class for the main function.\n \"\"\"\n def __init__(self,\n data_dir,\n model_dir,\n task_id,\n isInteractive=True,\n OOV=False,\n memory_size=250,\n random_state=None,\n batch_size=32,\n learning_rate=0.001,\n epsilon=1e-8,\n max_grad_norm=40.0,\n evaluation_interval=10,\n hops=3,\n epochs=200,\n embedding_size=20,\n alpha=.5,\n save_vocab=None,\n load_vocab=None,\n verbose=False,\n load_profiles=None,\n save_profiles=None):\n\n self.data_dir=data_dir\n self.task_id=task_id\n self.model_dir=model_dir\n # self.isTrain=isTrain\n self.isInteractive=isInteractive\n self.OOV=OOV\n self.memory_size=memory_size\n self.random_state=random_state\n self.batch_size=batch_size\n self.learning_rate=learning_rate\n self.epsilon=epsilon\n self.max_grad_norm=max_grad_norm\n self.evaluation_interval=evaluation_interval\n self.hops=hops\n self.epochs=epochs\n self.embedding_size=embedding_size\n self.save_vocab=save_vocab\n self.load_vocab=load_vocab\n self.verbose = verbose\n self.alpha = alpha\n\n # Loading possible answers\n self.candidates, self.candid2indx = load_candidates(self.data_dir, self.task_id)\n self.n_cand = len(self.candidates)\n print(\"Candidate Size\", self.n_cand)\n self.indx2candid= dict((self.candid2indx[key],key) for key in self.candid2indx)\n\n # task data\n self.trainData, self.testData, self.valData = load_dialog_task(self.data_dir, self.task_id, self.candid2indx, self.OOV)\n data = self.trainData + self.testData + self.valData\n\n # Find profiles types\n if load_profiles:\n with open(load_profiles, 'rb') as f:\n self._profiles_mapping = pickle.load(f)\n else:\n self._profiles_mapping = generate_profile_encoding(self.trainData)\n if save_profiles:\n with open(save_profiles, 'wb') as f:\n pickle.dump(self._profiles_mapping, f)\n\n profiles_idx_set = set(self._profiles_mapping.values())\n\n print(\"Profiles:\", self._profiles_mapping)\n\n # Vocabulary\n self.build_vocab(data,self.candidates,self.save_vocab,self.load_vocab)\n # self.candidates_vec=vectorize_candidates_sparse(self.candidates,self.word_idx)\n self.candidates_vec=vectorize_candidates(self.candidates,self.word_idx,self.candidate_sentence_size)\n\n # Model initialisation\n optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate, epsilon=self.epsilon)\n self.sess=tf.Session()\n self.model = MemN2NDialog(self.batch_size,\n self.vocab_size,\n self.n_cand,\n self.sentence_size,\n self.embedding_size,\n self.candidates_vec,\n profiles_idx_set,\n session=self.sess,\n hops=self.hops,\n max_grad_norm=self.max_grad_norm,\n alpha=alpha,\n optimizer=optimizer,\n task_id=task_id,\n verbose=verbose)\n self.saver = tf.train.Saver(max_to_keep=50)\n \n # self.summary_writer = tf.train.SummaryWriter(self.model.root_dir, self.model.graph_output.graph)\n self.summary_writer = tf.summary.FileWriter(self.model.root_dir, self.model.graph_output.graph)\n \n def build_vocab(self,data,candidates,save=False,load_file=None):\n \"\"\"\n Construction of a vocabulary based on all possible words in `data`. A side-effect only method.\n :param data: Typically, the concatenation of the training, testing, and validation dataset\n :param candidates: Possible bot's answers\n :param save: Name of the file to construct (or anything evaluated to `False` would not trigger the saving)\n :param load_file: Name of the file to load (or `False` if force the construction of the vocabulary\n \"\"\"\n if load_file:\n with open(load_file, 'rb') as vocab_file:\n vocab = pickle.load(vocab_file)\n else:\n vocab = reduce(lambda x, y: x | y, (set(list(chain.from_iterable(s)) + q) for s, q, a in data))\n vocab |= reduce(lambda x,y: x|y, (set(candidate) for candidate in candidates) )\n vocab=sorted(vocab)\n\n self.vocabulary = vocab\n self.word_idx = dict((c, i + 1) for i, c in enumerate(vocab))\n max_story_size = max(map(len, (s for s, _, _ in data)))\n mean_story_size = int(np.mean([ len(s) for s, _, _ in data ]))\n self.sentence_size = max(map(len, chain.from_iterable(s for s, _, _ in data)))\n self.candidate_sentence_size = max(map(len,candidates))\n query_size = max(map(len, (q for _, q, _ in data)))\n self.memory_size = min(self.memory_size, max_story_size)\n self.vocab_size = len(self.word_idx) + 1 # +1 for nil word\n self.sentence_size = max(query_size, self.sentence_size) # for the position\n\n # params\n print(\"vocab size:\",self.vocab_size)\n print(\"Longest sentence length\", self.sentence_size)\n print(\"Longest candidate sentence length\", self.candidate_sentence_size)\n print(\"Longest story length\", max_story_size)\n print(\"Average story length\", mean_story_size)\n\n if save:\n with open(save, 'wb') as vocab_file:\n pickle.dump(vocab, vocab_file)\n \n def train(self):\n \"\"\"\n Training method for the chatbot. It is based on `self.trainData`, on side-effect values\n from `build_vocab`, and potentially other class' attributes.\n\n An epoch corresponds to one training on the whole dataset. If the current epoch's number\n is divisible by `self.evaluation_interval` (or that we're at the last epoch), the training\n and validating accuracies are computed, printed/stored. Furthermore, if the validation\n accuracy is the best in comparison to the previous values, the model is serialized.\n \"\"\"\n trainP, trainS, trainQ, trainA = vectorize_data(self.trainData, self.word_idx, self.sentence_size, self.batch_size, self.n_cand, self.memory_size, self._profiles_mapping)\n valP, valS, valQ, valA = vectorize_data(self.valData, self.word_idx, self.sentence_size, self.batch_size, self.n_cand, self.memory_size, self._profiles_mapping)\n n_train = len(trainS)\n n_val = len(valS)\n print(\"Training Size\",n_train)\n print(\"Validation Size\", n_val)\n tf.set_random_seed(self.random_state)\n batches = zip(range(0, n_train-self.batch_size, self.batch_size), range(self.batch_size, n_train, self.batch_size))\n batches = [(start, end) for start, end in batches]\n best_validation_accuracy=0\n\n print('Number of epochs:', self.epochs)\n for t in range(1, self.epochs+1):\n print('Epoch', t)\n np.random.shuffle(batches)\n total_cost = 0.0\n for start, end in batches:\n p = trainP[start:end]\n s = trainS[start:end]\n q = trainQ[start:end]\n a = trainA[start:end]\n cost_t = self.model.batch_fit(p, s, q, a)\n total_cost += cost_t\n if t % self.evaluation_interval == 0 or t == self.epochs:\n print('validation')\n print('predicting training full dataset...')\n train_preds=self.model.batch_predict(trainP, trainS, trainQ)\n print('predicting validation full dataset...')\n val_preds=self.model.batch_predict(valP, valS,valQ)\n print('finished predictions.')\n train_acc = metrics.accuracy_score(np.array(train_preds), trainA)\n val_acc = metrics.accuracy_score(val_preds, valA)\n print('-----------------------')\n print('Epoch', t)\n print('Total Cost:', total_cost)\n print('Training Accuracy:', train_acc)\n print('Validation Accuracy:', val_acc)\n print('-----------------------')\n\n # write summary\n # train_acc_summary = tf.scalar_summary('task_' + str(self.task_id) + '/' + 'train_acc', tf.constant((train_acc), dtype=tf.float32))\n # val_acc_summary = tf.scalar_summary('task_' + str(self.task_id) + '/' + 'val_acc', tf.constant((val_acc), dtype=tf.float32))\n # merged_summary = tf.merge_summary([train_acc_summary, val_acc_summary])\n train_acc_summary = tf.summary.scalar('task_' + str(self.task_id) + '/' + 'train_acc', tf.constant((train_acc), dtype=tf.float32))\n val_acc_summary = tf.summary.scalar('task_' + str(self.task_id) + '/' + 'val_acc', tf.constant((val_acc), dtype=tf.float32))\n merged_summary = tf.summary.merge([train_acc_summary, val_acc_summary])\n summary_str = self.sess.run(merged_summary)\n self.summary_writer.add_summary(summary_str, t)\n self.summary_writer.flush()\n \n if val_acc > best_validation_accuracy:\n best_validation_accuracy=val_acc\n self.saver.save(self.sess, os.path.join(self.model_dir, \"model.ckpt\"),global_step=t)\n\n @classmethod\n def restore_model(cls, **kwargs):\n \"\"\"\n Helper class method which tries to construct a chatbot instance and restore\n the tensorflow's session. It can be used to recover a model from a previous\n training session.\n\n :param kwargs: Same arguments as `Chatbot.__init__`\n :return: The successfully restored model (if not successful, a `ValueError` is raised)\n \"\"\"\n ckpt = tf.train.get_checkpoint_state(kwargs['model_dir'])\n\n if ckpt and ckpt.model_checkpoint_path:\n created_cb = cls(**kwargs)\n created_cb.saver.restore(created_cb.sess, ckpt.model_checkpoint_path)\n else:\n raise ValueError(\"`model_dir` does not exist or was not created correctly\")\n\n return created_cb\n\n def test(self):\n \"\"\"\n Load a model from a previous training session and prints the accuracy for\n the testing dataset.\n \"\"\"\n ckpt = tf.train.get_checkpoint_state(self.model_dir)\n if ckpt and ckpt.model_checkpoint_path:\n self.saver.restore(self.sess, ckpt.model_checkpoint_path)\n else:\n print(\"...no checkpoint found...\")\n if self.isInteractive:\n self.interactive()\n else:\n testP, testS, testQ, testA = vectorize_data(self.testData, self.word_idx, self.sentence_size, self.batch_size, self.n_cand, self.memory_size, self._profiles_mapping)\n n_test = len(testS)\n print(\"Testing Size\", n_test)\n test_preds=self.model.batch_predict(testP, testS,testQ)\n test_acc = metrics.accuracy_score(test_preds, testA)\n print(\"Testing Accuracy:\", test_acc)\n \n # print(testA)\n # for pred in test_preds:\n # print(pred, self.indx2candid[pred])\n\n def test_accuracy(self, test_data_dir):\n \"\"\"\n Compute and return the testing accuracy for the data directory given in argument.\n It is a more general method than `Chatbot.test` as it can be used on different\n datasets than the one given at initialisation.\n\n :param test_data_dir: Directory's path where to find the testing dataset\n :return: The accuracy score for the testing file\n \"\"\"\n _, testData, _ = load_dialog_task(test_data_dir, self.task_id, self.candid2indx, self.OOV)\n testP, testS, testQ, testA = vectorize_data(testData, self.word_idx, self.sentence_size, self.batch_size, self.n_cand, self.memory_size, self._profiles_mapping)\n test_preds = self.model.batch_predict(testP, testS, testQ)\n test_acc = metrics.accuracy_score(test_preds, testA)\n\n return test_acc\n\n def close_session(self):\n \"\"\"Helper function to close the owned attributes (i.e. the tensorflow's session)\"\"\"\n self.sess.close()\n\n\ndef run_experiment(experiment_path, test_dirs, **kwargs):\n \"\"\"\n Helper function for running experiment. The main purpose is to document\n the experiment and to ensure that the information is clearly established.\n\n\n Args:\n - experiment_path: directory for the experiment (created if not exist)\n - test_dirs: list of directories for to take the testing data from, and evaluating it\n - kwargs can also contains any other argument that will be given to ChatBot.\n \"\"\"\n os.makedirs(experiment_path, exist_ok=True)\n\n model_dir = experiment_path\n vocabulary = os.path.join(experiment_path, 'vocabulary.obj')\n profiles = os.path.join(experiment_path, 'profiles.obj')\n\n kwargs['model_dir'] = model_dir\n\n kwargs_load = kwargs.copy()\n kwargs_load['load_vocab'] = vocabulary\n kwargs_load['load_profiles'] = profiles\n\n kwargs_save = kwargs.copy()\n kwargs_save['save_vocab'] = vocabulary\n kwargs_save['save_profiles'] = profiles\n\n try:\n chatbot = ChatBot.restore_model(**kwargs_load)\n except Exception as err:\n print('Did not load, generate:', err)\n\n with open(os.path.join(experiment_path, 'attributes.log'), 'w') as f:\n pprint.pprint(kwargs, stream=f, indent=4)\n\n tf.reset_default_graph()\n chatbot = ChatBot(**kwargs_save)\n chatbot.train()\n\n for test_dir in test_dirs:\n acc = chatbot.test_accuracy(test_dir)\n print('Accuracy for {}: {:.5%}'.format(test_dir, acc))\n\n chatbot.close_session()\n\n\nif __name__ =='__main__':\n model_dir=\"tmp/task\"+str(FLAGS.task_id)+\"_\"+FLAGS.model_dir\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n\n\n if FLAGS.interactive:\n test_dirs = glob.glob('../data/personalized-dialog-dataset/split-by-profile/*')\n test_dirs = list(test_dirs)\n small_train_dataset = '../data/personalized-dialog-dataset/small'\n\n from IPython import embed\n pp = pprint.PrettyPrinter(indent=4)\n embed()\n\n else:\n # chatbot.run()\n if FLAGS.experiment == \"test\":\n run_experiment('experiments/test',\n ['../data/personalized-dialog-dataset/split-by-profile/female_elderly'],\n data_dir='../data/personalized-dialog-dataset/small',\n task_id=5,\n epochs=3)\n elif FLAGS.experiment == \"full_profile\":\n test_dirs = glob.glob('../data/personalized-dialog-dataset/split-by-profile/*')\n test_dirs = list(test_dirs)\n\n run_experiment('experiments/full_profile',\n test_dirs,\n data_dir='../data/personalized-dialog-dataset/small',\n task_id=5,\n epochs=200)\n\n elif FLAGS.experiment == 'split-by-profile':\n test_dirs = glob.glob('../data/personalized-dialog-dataset/split-by-profile/*')\n test_dirs = [f for f in test_dirs if os.path.isdir(f)]\n\n run_experiment('experiments/split_by_profile',\n test_dirs,\n data_dir='../data/personalized-dialog-dataset/merged-from-split-by-profile',\n task_id=5,\n epochs=200)\n\n else:\n chatbot=ChatBot(FLAGS.data_dir,\n model_dir,\n FLAGS.task_id,\n OOV=FLAGS.OOV,\n isInteractive=FLAGS.interactive,\n batch_size=FLAGS.batch_size,\n memory_size=FLAGS.memory_size,\n save_vocab=FLAGS.save_vocab,\n load_vocab=FLAGS.load_vocab,\n epochs=FLAGS.epochs,\n evaluation_interval=FLAGS.evaluation_interval,\n verbose=FLAGS.verbose,\n alpha=FLAGS.alpha)\n\n if FLAGS.train:\n chatbot.train()\n else:\n chatbot.test()\n\n chatbot.close_session()\n","sub_path":"MemN2N-mtl-more-softmax/single_dialog.py","file_name":"single_dialog.py","file_ext":"py","file_size_in_byte":19178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"267730778","text":"import csv\nimport math\nimport numpy as np\nimport random\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib import style\nx=[]\ny=[]\nfreq1=[20,210,30,0,-1,1,1]\nfreq2=[20,0,1.9,25,58,7]\nfreq3=[1,2,3,4,5]\nfreq4=[600,1000,3,4]\ncost1=[3000,5000,6000,2500,1500,2000,1000,1500]\ncost2=[3000,1500,4000,7000,5000,4600]\ncost3=[1700,2500,1300,3400,1500]\ncost4=[7100,4200,3700,4000]\nlis1=[]\nlis2=[]\ncar={}\nhead=['T1','T2','T3','T4','T5','T6','T7','T8','T9','T10','CAR_ID','ATTRIBUTE']\ncl=['Car1','Car2','Car3','Car4','Car5','Car6','Car7','Car8','Car9','Car10','Car11','Car12','Car13','Car14','Car15']\n\ndef immediate(dataset):\n\tdataset = csv.reader(open(dataset, newline=''), delimiter= \" \", quotechar=\"|\")\n\ti=0\n\tprob=' '\n\ts=0\n\t#wq=0\n\tk=0\n\ttot=0\n\trow=['0','0','0','0','0','0','0','0','0','0','0']\n\tprev=[' ',' ',' ',' ',' ',' ',' ']\n\t#inp=input(\"attribute\")\n\tfor row in dataset:\n\n\t\ts=s+1\n\t\tif(i<=0):\n\t\t\theader=row[0].split(',')\n\t\t\theader.append(' ')\n\t\t\theader.append(' ')\n\t\t\ti=i+1\n\t\t\ts=0\n\t\telse:\n\t\t\trow=row[0].split(',')\n\t\t\tnow=[row[1],row[1],row[1],row[1],row[1],row[1],row[1]]\n\n\t\t\t\t\t\t#0 to 3 years\n\t\t\t#engine oil checking\n\t\t\tif(header[3]=='ENGINE_OIL' and int(row[3])<=freq1[0] and (now[0]==' ' or now[0]!=prev[0])):\n\t\t\t\tprob= header[3]+', '\n\t\t\t\ttot=tot+cost1[0]\n\t\t\t\tprev[0]=row[1]\n\n\t\t\t#coolant checking\n\t\t\tif(header[4]=='COOLANT' and int(row[4])>=freq1[1] and (now[1]==' ' or now[1]!=prev[1])):\n\t\t\t\tprob= prob + ' ' + header[4]\n\t\t\t\ttot=tot+cost1[1]\n\t\t\t\tprev[1]=row[1]\n\n\t\t\tif(header[5]=='BATTERY' ):\n\t\t\t\tif(k<120):\n\t\t\t\t\tx.append(int(row[5]))\n\t\t\t\t\tk=k+1\n\n\t\t\t#battery checking\n\t\t\tif(header[5]=='BATTERY' and int(row[5])<=freq1[2] and (now[2]==' ' or now[2]!=prev[2])):\n\t\t\t\tprob= prob + ' ' + header[5]\n\t\t\t\ttot=tot+cost1[2]\n\t\t\t\tprev[2]=row[1]\n\n\t\t\t#lights checking\n\t\t\tif(header[6]=='LIGHTS' and int(row[6])<=freq1[3] and (now[3]==' ' or now[3]!=prev[3])):\n\t\t\t\tprob=prob +' ' + header[6]\n\t\t\t\ttot=tot+cost1[3]\n\t\t\t\tprev[3]=row[1]\n\n\t\t\t#left wheel alignment checking\n\t\t\tif(header[7]=='WHEEL_ALIGNMENT' and int(row[7])<=freq1[4] and (now[4]==' ' or now[4]!=prev[4])):\n\t\t\t\tprob=prob +' left-' + header[7]\n\t\t\t\ttot=tot+cost1[4]\n\t\t\t\tprev[4]=row[1]\n\n\t\t\t#right wheel alignment checking\n\t\t\tif(header[7]=='WHEEL_ALIGNMENT' and int(row[7])>=freq1[5] and (now[4]==' ' or now[4]!=prev[4])):\n\t\t\t\tprob=prob + ' right-' + header[7]\n\t\t\t\ttot=tot+cost1[4]\n\t\t\t\tprev[4]=row[1]\n\n\t\t\t#cleaning\n\t\t\tif(header[8]=='CLEANING' and int(row[8])>=freq1[6] and (now[5]==' ' or now[5]!=prev[5])):\n\t\t\t\tprob=prob + ' '+ header[8]\n\t\t\t\ttot=tot+cost1[5]\n\t\t\t\tprev[5]=row[1]\n\n\t\t\t#oil filter checking\n\t\t\tif(header[9]=='OIL_FILTER' and row[9]=='yes' and (now[6]==' ' or now[6]!=prev[6])):\n\t\t\t\tprob=prob+ ' ' + header[9]\n\t\t\t\ttot=tot+cost1[6]\n\t\t\t\tprev[6]=row[1]\n\n\t\t\t\t\t\t\t#3 to 6 years\n\t\t\t#rad check\n\t\t\tif(header[3]=='RAD_CHECK' and int(row[3])<freq2[0] and (now[0]==' ' or now[0]!=prev[0])):\n\t\t\t\tprob=prob + ' '+ header[3]\n\t\t\t\ttot=tot+cost2[0]\n\t\t\t\tprev[0]=row[1]\n\n\t\t\t#wiper blades\n\t\t\tif(header[4]=='WIPER_BLADES' and int(row[4])<=freq2[1] and (now[1]==' ' or now[1]!=prev[1])):\n\t\t\t\tprob=prob + ' '+ header[4]\n\t\t\t\ttot=tot+cost2[1]\n\t\t\t\tprev[1]=row[1]\n\n\t\t\t#suspension\n\t\t\tif(header[5]=='SUSPENSION' and float(row[5])<=freq2[2] and (now[2]==' ' or now[2]!=prev[2])):\n\t\t\t\tprob=prob + ' '+ header[5]\n\t\t\t\ttot=tot+cost2[2]\n\t\t\t\tprev[2]=row[1]\n\n\t\t\t#steer gear box check\n\t\t\tif(header[6]=='STEER_GEAR_BOX' and int(row[6])<=freq2[3] and (now[3]==' ' or now[3]!=prev[3])):\n\t\t\t\tprob=prob + ' '+ header[6]\n\t\t\t\ttot=tot+cost2[3]\n\t\t\t\tprev[3]=row[1]\n\n\t\t\t#fuel filters\n\t\t\tif(header[7]=='FUEL_FILTER' and float(row[7])<=freq2[4] and (now[4]==' ' or now[4]!=prev[4])):\n\t\t\t\tprob=prob + ' '+ header[7]\n\t\t\t\ttot=tot+cost2[4]\n\t\t\t\tprev[4]=row[1]\n\n\t\t\t#brake pads check\n\t\t\tif(header[8]=='BRAKE_PADS' and int(row[8])<=freq2[5] and (now[5]==' ' or now[5]!=prev[5])):\n\t\t\t\tprob=prob + ' '+ header[8]\n\t\t\t\ttot=tot+cost2[5]\n\t\t\t\tprev[5]=row[1]\n\n\t\t\t\t\t\t\t#6 to 9 years\n\t\t\t#Ignition checking\n\t\t\tif(header[3]=='IGNITION_TIMING' and int(row[3])>=freq3[0] and (now[0]==' ' or now[0]!=prev[0])):\n\t\t\t\tprob=prob+ ' ' + header[3]\n\t\t\t\ttot=tot+cost3[0]\n\t\t\t\tprev[0]=row[1]\n\n\t\t\t#fuel ejectors checking\n\t\t\tif(header[4]=='FUEL_EJECTORS' and int(row[4])>=freq3[1] and (now[1]==' ' or now[1]!=prev[1])):\n prob=prob+ ' ' + header[4]\n tot=tot+cost3[1]\n prev[1]=row[1]\n\n\t\t\t#power steering check\n\t\t\tif(header[5]=='POWER_STEERING_FUEL' and int(row[5])>=freq3[2] and (now[2]==' ' or now[2]!=prev[2])):\n prob=prob+ ' ' + header[5]\n tot=tot+cost3[2]\n prev[2]=row[1]\n\n\t\t\t#pcv valve check\n\t\t\tif(header[6]=='PCV_VALVE' and int(row[6])>=freq3[3] and (now[3]==' ' or now[3]!=prev[3])):\n prob=prob+ ' ' + header[6]\n tot=tot+cost3[3]\n prev[3]=row[1]\n\n\t\t\t#transmission checking\n\t\t\tif(header[7]=='TRANSMISSION' and int(row[7])>=freq3[4] and (now[4]==' ' or now[4]!=prev[4])):\n prob=prob+ ' ' + header[7]\n tot=tot+cost3[4]\n prev[4]=row[1]\n\n\t\t\t\t\t\t\t#9 to 15 years\n\n\t\t\t#seat belts\n\t\t\tif(header[3]=='SEAT_BELTS' and int(row[3])>=freq4[1] and int(row[3])<=freq4[0] and (now[0]==' ' or now[0]!=prev[0])):\n prob=prob+ ' ' + header[3]\n tot=tot+cost4[0]\n prev[0]=row[1]\n\n\t\t\t#engine idle settings\n\t\t\tif(header[4]=='ENGINE_IDLE' and int(row[4])>=freq4[2] and (now[1]==' ' or now[1]!=prev[1])):\n prob=prob+ ' ' + header[4]\n tot=tot+cost4[1]\n prev[1]=row[1]\n\n\t\t\t#clutch plate\n\t\t\tif(header[5]=='CLUTCH' and int(row[5])>=freq4[3] and (now[2]==' ' or now[2]!=prev[2])):\n prob=prob+ ' ' + header[5]\n tot=tot+cost4[2]\n prev[2]=row[1]\n\n\t\t\t#water pump\n\t\t\tif(header[6]=='TRANSMISSION' and int(row[6])>=freq4[4] and (now[3]==' ' or now[3]!=prev[3])):\n prob=prob+ ' ' + header[6]\n tot=tot+cost4[3]\n prev[3]=row[1]\n\t\t\n\t\t\tro=row[1]\n\t\t\tif(s>=12):\n\t\t\t\ts=0\n\t\t\t\tif(tot>0):\n\t\t\t\t\tprob1=row[0] + ' has a problems in '+ prob+ ' in ' + ro + ' of total cost RS.' +str(tot)\n\t\t\t\t\tprint(prob1)\n\t\t\t\t\tprint('\\n')\n\t\t\t\t\tch=input()\n\t\t\t\t\tif(ch=='\\0'):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\ttot=0\n\t\t\t\t\tprob1=' '\n\t\t\t\tprob=' '\n\t\t\t\tif(k>=120):\n\t\t\t\t\tgraph(x)\n\t\t\t\t\tk=12\n\t\t\t\t\tx.clear()\n\n\n\n\n\n\n\n\n\n\ndef graph(x):\n\tstyle.use('ggplot')\n\ti=0\n\tfor p in range(0,140):\n\t\ty.append(p)\n\tfor l in x:\n\t\tif(l>=30):\n\t\t\tplt.bar(y[i],l,width= 1.3,color=\"red\")\n\t\telse:\n\t\t\tplt.bar(y[i],l,width=1.3,color=\"green\")\n\t\ti=i+1\n\n\tplt.ylim(0,250)\n\tplt.xlim(0,150)\n\tplt.title('TRIPS')\n\tplt.xlabel('TIME')\n\tplt.ylabel('ATTRIBUTE')\n\tplt.show()\n\ty.clear()\n\n\npath='dataset1.csv'\nprint('information for 0-3 years\\n')\nimmediate(path)\n#future(path,freq2)","sub_path":"immediate.py","file_name":"immediate.py","file_ext":"py","file_size_in_byte":7071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37520210","text":"\"\"\"Модуль генерации изображений заглушек\"\"\"\n\nimport os\nimport pathlib\n\nfrom PIL import Image, ImageDraw, ImageFont\nfrom flask import send_file, current_app, request\n\nfrom . import canvas\n\n\n@canvas.route('/', methods=['GET', 'POST'])\n@canvas.route('/<int:width>', methods=['GET', 'POST'])\n@canvas.route('/<int:width>x<int:height>', methods=['GET', 'POST'])\ndef main(width=None, height=None):\n \"\"\"Обработка запросов на генерацию изображения\"\"\"\n # Подготовка данных\n width = width or 480\n height = height or width\n maximum = 3840\n width = width if width < maximum else maximum\n height = height if height < maximum else maximum\n\n color = request.args.get('c') or 'cccccc'\n if len(color) == 3:\n color += color\n try:\n rgb = tuple(int(color[i:i + 2], 16) for i in (0, 2, 4))\n except ValueError:\n color = 'cccccc'\n rgb = (204, 204, 204)\n\n # Формирование PATH и NAME\n name = f'{width}x{height}.jpg'\n directory = os.path.join(current_app.config['STORAGE'], 'canvas', color.lower())\n path = os.path.join(directory, name)\n try:\n # Поиск в ранее сгенерированных файлов\n return send_file(path)\n except FileNotFoundError:\n # Формирование изображения\n img = Image.new('RGB', (width, height), rgb)\n rgb = tuple(350 - i for i in rgb)\n if width >= 50 and height >= 50:\n draw = ImageDraw.Draw(img)\n # Расчет размера шрифта\n font_size = 12\n txt = f'{width}x{height}'\n basedir = os.path.abspath(os.path.dirname(__file__))\n font_path = os.path.join(basedir, 'roboto.ttf')\n while True:\n font = ImageFont.truetype(font_path, font_size)\n tw, th = draw.textsize(txt, font)\n if tw > img.width * 0.5 or th > img.height * 0.5:\n break\n font_size += 1\n # Печать размера изображения\n font = ImageFont.truetype(font_path, font_size)\n tw, th = draw.textsize(txt, font)\n position = (img.width / 2 - tw / 2, img.height / 2 - th / 1.7)\n draw.text(position, txt, rgb, font=font)\n # Печать логотипа\n if width / height <= 2 and width >= 100:\n txt = 'LOGGER.SU'\n font = ImageFont.truetype(font_path, int(font_size / 2))\n tw, th = draw.textsize(txt, font=font)\n position = (int(th / 2), img.height - th - int(th / 2))\n draw.text(position, txt, rgb, font=font)\n del draw\n # Сохранение изображения\n pathlib.Path(directory).mkdir(parents=True, exist_ok=True)\n img.save(path)\n return send_file(path)\n","sub_path":"app/canvas/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"183375065","text":"interpolations = []\n\n\nclass Linear:\n def __init__(self):\n self.interpolator = CubicBezier(0, 0, 1, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\nclass Interpolation:\n \"\"\"Gère les interpolations des valeurs.\n Permet d'utiliser une fonction de type cubic bezier (http://cubic-bezier.com) pour intérpoler les valeurs.\"\"\"\n\n def __init__(self, start, stop, milliseconds: int, callback, method=Linear, args=()):\n self.startValue = type(start)(start) # Use the copy constructor, workaround for copy.copy()\n self.stopValue = type(stop)(stop)\n\n self.milliseconds = milliseconds\n self.method = method\n self.args = args\n self.callback = callback\n\n self.generator = self.Generator()\n self.paused = False\n\n def Generator(self):\n interpolator = self.method(*self.args)\n\n seconds = self.milliseconds / 1000.0\n diff = self.stopValue - self.startValue\n inc = 1.0 / 60 # pygame.time.Clock.get_fps()\n progression = self.startValue * 0\n current_second = inc\n\n while current_second < seconds:\n percent = 1 - ((seconds - current_second)) / seconds\n\n previous_step = progression\n progression = diff * interpolator.ease(percent)\n\n yield (self.startValue + progression, progression - previous_step)\n current_second += inc\n\n yield (self.stopValue, self.stopValue - (self.startValue + progression))\n\n def start(self):\n self.resume()\n if self not in interpolations:\n interpolations.append(self)\n return self\n\n def stop(self):\n if self in interpolations:\n interpolations.remove(self)\n\n def pause(self):\n self.paused = True\n\n def resume(self):\n self.paused = False\n\n def interpolate(self):\n if not self.paused:\n try:\n self.callback(*next(self.generator))\n except StopIteration:\n interpolations.remove(self)\n\n\ndef updateInterpolations():\n for interpolation in interpolations:\n interpolation.interpolate()\n\n\n\n\n# Predefined Cubic Bezier classes\nclass Ease:\n def __init__(self):\n self.interpolator = CubicBezier(.25, .1, .25, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\nclass EaseIn:\n def __init__(self):\n self.interpolator = CubicBezier(.42, 0, 1, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\nclass EaseOut:\n def __init__(self):\n self.interpolator = CubicBezier(0, 0, .58, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\nclass EaseInOut:\n def __init__(self):\n self.interpolator = CubicBezier(.42, 0, .58, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\n# Un grand merci pour https://github.com/gre/bezier-easing/blob/master/src/index.js\n# Librairie js qui implémente Cubic Bezier, souvent utilisé pour créer des animations en CSS\nclass CubicBezier:\n NEWTON_ITERATIONS = 4\n NEWTON_MIN_SLOPE = 0.001\n SUBDIVISION_PRECISION = 0.0000001\n SUBDIVISION_MAX_ITERATIONS = 10\n\n kSplineTableSize = 11\n kSampleStepSize = 1.0 / (kSplineTableSize - 1.0)\n\n def __init__(self, x1, y1, x2, y2):\n if not (0 <= x1 <= 1 and 0 <= x2 <= 1):\n raise RuntimeError(\"bezier x values must be in [0, 1] range\")\n\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n\n self.sampleValues = []\n if self.x1 != self.y1 or self.x2 != self.y2:\n for i in range(self.kSplineTableSize):\n self.sampleValues.append(self.calcBezier(i * self.kSampleStepSize, self.x1, self.x2))\n\n def ease(self, t):\n if self.x1 == self.y1 and self.x2 == self.y2:\n return t\n\n if t == 0:\n return 0\n if t == 1:\n return 1\n\n return self.calcBezier(self.getTForX(t), self.y1, self.y2)\n\n def getTForX(self, aX):\n intervalStart = 0.0\n currentSample = 1\n lastSample = self.kSplineTableSize - 1\n\n while currentSample != lastSample and self.sampleValues[currentSample] <= aX:\n intervalStart += self.kSampleStepSize\n currentSample += 1\n currentSample -= 1\n\n dist = (aX - self.sampleValues[currentSample]) / (\n self.sampleValues[currentSample + 1] - self.sampleValues[currentSample])\n guessForT = intervalStart + dist * self.kSampleStepSize\n\n initialSlope = self.getSlope(guessForT, self.x1, self.x2)\n if initialSlope >= self.NEWTON_MIN_SLOPE:\n return self.newtonRaphsonIterate(aX, guessForT, self.x1, self.x2)\n\n elif initialSlope == 0:\n return guessForT\n\n else:\n return self.binarySubdivide(aX, intervalStart, intervalStart + self.kSampleStepSize, self.x1, self.x2)\n\n @classmethod\n def A(cls, aA1, aA2):\n return 1.0 - 3.0 * aA2 + 3.0 * aA1\n\n @classmethod\n def B(cls, aA1, aA2):\n return 3.0 * aA2 - 6.0 * aA1\n\n @classmethod\n def C(cls, aA1):\n return 3.0 * aA1\n\n @classmethod\n def calcBezier(cls, aT, aA1, aA2):\n return ((cls.A(aA1, aA2) * aT + cls.B(aA1, aA2)) * aT + cls.C(aA1)) * aT\n\n @classmethod\n def getSlope(cls, aT, aA1, aA2):\n return 3.0 * cls.A(aA1, aA2) * aT * aT + 2.0 * cls.B(aA1, aA2) * aT + cls.C(aA1)\n\n @classmethod\n def binarySubdivide(cls, aX, aA, aB, mX1, mX2):\n currentX = 0\n currentT = 0\n i = 0\n\n firstTime = True\n\n while firstTime or (abs(currentX) > cls.SUBDIVISION_PRECISION and i < cls.SUBDIVISION_MAX_ITERATIONS):\n currentT = aA + (aB - aA) / 2.0\n currentX = cls.calcBezier(currentT, mX1, mX2) - aX\n if currentX > 0:\n aB = currentT\n else:\n aA = currentT\n\n i += 1\n firstTime = False\n\n return currentT\n\n @classmethod\n def newtonRaphsonIterate(cls, aX, aGuessT, mX1, mX2):\n for i in range(cls.NEWTON_ITERATIONS):\n currentSlope = cls.getSlope(aGuessT, mX1, mX2)\n if currentSlope == 0:\n return aGuessT\n\n currentX = cls.calcBezier(aGuessT, mX1, mX2) - aX\n aGuessT -= currentX / currentSlope\n\n return aGuessT\n","sub_path":"gameengine/core/Interpolation.py","file_name":"Interpolation.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"92373004","text":"from ..models.survey import Survey, SurveySection, SurveyQuest, SurveyQuestOptions, SurveyBrief, AutoIds, SurveyResponse, SurveyInvitation\nfrom mongoalchemy.fields import *\nfrom .kafkadao import KafkaDao as kafka\nfrom datetime import datetime\nfrom flask import jsonify\nimport json\nimport traceback\nfrom loggers import *\nlogger = createLogger(__name__)\n\nclass SurveyDao():\n def __init__(self):\n pass\n\n def getSingleSurvey(self, id):\n from bson import json_util\n try:\n survey = Survey.query.filter_by(id=int(id)).first()\n result = json.dumps(survey, default=survey.encode_model)\n return result\n except Exception:\n traceback.print_exc()\n raise Exception\n\n def createSurvey(self, data, db):\n surveySections = []\n for section in data.get('sections'):\n questions = []\n for question in section.get('questions'):\n q = SurveyQuest(qid = self.autoId('question_id'), name = question.get('name'), type = question.get('type'), options = question.get('options'))\n questions.append( q )\t\n s = SurveySection(section_id = self.autoId('section_id'), name= section.get('name'), questions = questions) \n surveySections.append( s )\n survey = Survey(id=self.autoId('survey'),name = data.get('name'), sections = surveySections)\n try:\n db.session.add(survey)\n sr = SurveyBrief(id=survey.id, name = survey.name, start_date = survey.start_date) \n db.session.add(sr)\n db.session.flush()\n response = None\n return response\n except Exception:\n traceback.print_exc()\n raise Exception\n\n def getSurvey(self):\n from bson import json_util\n try:\n surveys = SurveyBrief.query.all()\n l = [json.dumps(ob, default=ob.encode_model) for ob in surveys]\n return l\n except Exception:\n traceback.print_exc()\n raise Exception\n\n def autoId(self, name):\n from bson import json_util \n try:\n ids = AutoIds.query.filter_by(id=name).first()\n id = ids.sequence_value + 1\n ids.sequence_value = id\n ids.save()\n return id\n except AttributeError:\n auto_id = AutoIds(id=name, sequence_value=1)\n auto_id.save()\n return 1\n except Exception:\n traceback.print_exc()\n\n def sendSurveyLink(self, data, db):\n import re\n regex = re.compile(r\"href=[\\'\\\"]?([^\\'\\\" >]+)\")\n survey_name = data.get('survey_name')\n survey_id = data.get('survey_id')\n survey_oid = data.get('survey_identifier')\n userList = data.get('selected_users')\n url = data.get('url')\n cm = data.get('message')\n messages = []\n for user in userList:\n link = url+\"/\"+survey_oid+\"/\"+survey_id+\"/\"+user.get('userId')\n message = {}\n message['chat_id'] = user.get('userId')\n message['messageType'] = 'outgoing'\n message['userMessage'] = None\n message['text'] = cm+'\\n\\n\\n<a href=\"'+link+ '\">Take Survey</a>'\n messages.append(message)\n sent_on = []\n try:\n for message in messages:\n kafka.publish(message = message)\n f = re.search(regex, message.get('text'))\n if self.checkForExistingInvitation(survey_id=int(survey_id), user_id=message.get('chat_id')) >= 1:\n inviation = SurveyInvitation.query.filter_by(survey_id=int(survey_id), user_id=message.get('chat_id')).first()\n sent_on = inviation.sent_on\n sent_on.append(datetime.now())\n inviation.save()\n else:\n survey_invitation = SurveyInvitation(survey_id=int(survey_id) , survey_name=survey_name, survey_link=f.group(1), message=cm, user_id=message.get('chat_id'), sent_on = [datetime.now()])\n db.session.add(survey_invitation)\t\t\n except Exception:\n traceback.print_exc()\n raise Exception\n\t \n def checkForExistingInvitation(self,survey_id, user_id):\n try:\n inviation = SurveyInvitation.query.filter_by(survey_id=int(survey_id), user_id=user_id).count()\n return inviation\n except Exception:\n traceback.print_exc()\n raise Exception\n\t \n ''' Save the survey response '''\n def saveSurveyResponse(self, data, db):\n survey_response = SurveyResponse(id = self.autoId(\"survey_response_id\"), survey_id = int(data.get('survey_id')), survey_name = data.get('survey_name'), user_id = data.get('user_id'), sections = data.get('sections'))\n try:\n db.session.add(survey_response)\n survey_brief = SurveyBrief.query.filter_by(id = int(data.get('survey_id'))).first()\n vote = survey_brief.votes + 1\n survey_brief.votes = vote\n survey_brief.save()\n db.session.flush()\n response = {}\n response['message'] = \"You have successfully completed the survey. Thank you.\"\n return response\n except Exception:\n traceback.print_exc()\n raise Exception\n\t \n ''' Validate if user has already submitted the survey response '''\n def checkSurveyResponseExist(self, user_id, survey_id):\n try:\n doc = SurveyResponse.query.filter_by(survey_id = int(survey_id), user_id = user_id).count()\n if doc == 1:\n return True\n else:\n return False\n except Exception:\n traceback.print_exc()\n raise Exception\t \n","sub_path":"bot/application/dao/surveydao.py","file_name":"surveydao.py","file_ext":"py","file_size_in_byte":5145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"488239679","text":"# __author__ = 'Administrator'\r\n# coding: utf-8\r\n\r\nimport os\r\n\r\nfrom PIL import Image, ImageDraw, ImageFont\r\n\r\n\r\nfontsize = 23\r\nfonttype = u'msyh.ttf'\r\ncolor = (255, 240, 241)\r\n\r\n\r\ndef watermark(filepath, string):\r\n '''在文件同级目录创建图片的水印图片'''\r\n ima = Image.open(filepath)\r\n x, y = ima.size\r\n font = ImageFont.truetype(fonttype, fontsize)\r\n draw = ImageDraw.Draw(ima)\r\n xr, yr = draw.textsize(string, font=font)\r\n if xr >= x or yr >= y:\r\n rate = xr / x + 1 if xr / x > 0 else yr / y + 1\r\n font = ImageFont.truetype(fonttype, fontsize / rate)\r\n xr, yr = draw.textsize(string, font=font)\r\n draw.text((x - xr, y - yr), string, font=font, fill=color)\r\n ##draw.bitmap(xy, bitmap, options)\r\n f1, ff = os.path.splitext(filepath)\r\n newfilepath = u'%s%s%s' % (f1, u'_watermark', ff)\r\n ima.save(newfilepath)","sub_path":"demo/common/utils/watermark.py","file_name":"watermark.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"70086567","text":"import pickle\nimport numpy as np\nimport cv2\n\n\ndef draw_bbox(img, rects):\n im = img.copy()\n for r in rects:\n xmin, ymin, xmax, ymax = r\n col = (255, 0, 0)\n cv2.rectangle(im, (xmin, ymin), (xmax, ymax), tuple(col), 2)\n return im\n\n\nPICKLEPATH = '../../../data/wider_face/train_bbox_annotations_with_splits.pkl'\nIMAGEDIR = '../../../data/wider_face/'\n\nwith open(PICKLEPATH, 'rb') as f:\n ants = pickle.load(f)\n\n\n\n\n\n\nfor ind, a in enumerate(ants):\n bbox = a['ann']['bboxes']\n valid = (bbox[:,2] > bbox[:,0]) and (bbox[:,3] > bbox[:,1])\n if np.sum(valid) != len(bbox):\n print ('Invalid bbox annotation detected ...')\n print ('Removing !')\n ants[ind]['ann']['bboxes'] = bbox[valid]\n ants[ind]['ann']['labels'] = a['ann']['labels'][valid]\n assert len(ants[ind]['ann']['bboxes']) == len(ants[ind]['ann']['labels'])\n\nwith open(PICKLEPATH, 'wb') as f:\n pickle.dump(ants, f)","sub_path":"src/etl/3_visualize_bbox_annotations.py","file_name":"3_visualize_bbox_annotations.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"500221762","text":"import matplotlib.pyplot as plt, mpld3\nfrom matplotlib import pyplot, transforms\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nfrom matplotlib.patches import Ellipse\nimport pandas as pd\nimport datetime as dt\n\n\ndef grafica(year):\n r_earth = 6371\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]\n x = r_earth*np.cos(u)*np.sin(v)\n y = r_earth*np.sin(u)*np.sin(v)\n z = r_earth*np.cos(v)\n ax.plot_wireframe(x, y, z, color=\"b\",alpha=0.1)\n ax.set_xlim(-50000, 50000)\n ax.set_ylim(-50000, 50000)\n ax.set_zlim(-50000, 50000)\n\n data=pd.read_json(\"Data/satcat.json\")\n final=int(year)\n inicio=int(final)-5\n\n\n data_filter=data.loc[(data['LAUNCH_YEAR']>=inicio)&(data['LAUNCH_YEAR']<=final),['INCLINATION','PERIGEE','APOGEE','LAUNCH_YEAR']]\n\n\n for ind in data_filter.index:\n ang = data_filter['INCLINATION'][ind]\n perigee = data_filter['PERIGEE'][ind]\n apogee = data_filter['APOGEE'][ind]\n\n u_e = np.linspace(0, 2*np.pi, 100)\n h = 362\n a = (perigee + apogee + 2*r_earth)/2\n c = a - (perigee + r_earth)\n ecc = c / a\n b = np.sqrt(pow(a,2)*(1-pow(ecc,2)))\n x_e = h + a * np.cos(u_e)\n y_e = b * np.sin(u_e)\n\n base = pyplot.gca().transData\n rot = transforms.Affine2D().rotate_deg(ang)\n\n ax.plot(x_e, y_e, 'r',alpha=0.1, transform = rot + base)\n\n fig.patch.set_facecolor('xkcd:black')\n ax.set_facecolor('xkcd:black')\n ax.grid(color='black')\n ax.tick_params(axis='x', colors='white')\n ax.tick_params(axis='y', colors='white')\n ax.tick_params(axis='z', colors='white')\n ax.view_init(elev=10., azim=180)\n plt.tight_layout()\n plt.savefig('image.png')\n # plt.show()\n #print (mpld3.fig_to_html(plt.show()))\n print('Done')\n#grafica(1967)\n","sub_path":"Orbits_Graph.py","file_name":"Orbits_Graph.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"45299517","text":"import random\r\n\r\ndef jogar():\r\n print(\"*****************************\")\r\n print(\"***** ADIVINHE O NUMERO *****\")\r\n print(\"*****************************\")\r\n\r\n print(\"Escolha o nível de dificuldade :\")\r\n nivel = int(input(\"(1) Fácil (2) Médio (3) Difícil\\n\"))\r\n tentativas = 0\r\n rodada = 1\r\n\r\n if(nivel == 1):\r\n tentativas = 20\r\n elif(nivel == 2):\r\n tentativas = 10\r\n else:\r\n tentativas = 5\r\n\r\n numero_secreto = random.randrange(1, 101)\r\n\r\n print(\"Favor informar um número entre 1 e 100.\")\r\n while(rodada <= tentativas):\r\n print(\"-\" * 40)\r\n print(\"Tentativa {} de {}.\".format(rodada, tentativas))\r\n tentativa = int(input(\"Informe o número :\"))\r\n print(\"Você digitou :\", tentativa)\r\n\r\n acertou = tentativa == numero_secreto\r\n maior = tentativa > numero_secreto\r\n menor = tentativa < numero_secreto\r\n\r\n if(tentativa < 0 or tentativa > 100):\r\n print(\"Favor informar um número entre 1 e 100.\")\r\n continue\r\n\r\n if(acertou):\r\n print(\"Você acertou o número sorteado.\")\r\n break\r\n else:\r\n if(maior):\r\n print(\"Não foi dessa vez. O número informado é maior do que o número sorteado\")\r\n elif(menor):\r\n print(\"Não foi dessa vez. O número informado é menor do que o número sorteado\")\r\n rodada += 1\r\n print(\"Infelizmente você chegou ao final do jogo. O número secreto era {}.\".format(numero_secreto))\r\n print(\"Fim do Jogo\")\r\n\r\nif(__name__ == \"__main__\"):\r\n jogar()","sub_path":"adivinhacao.py","file_name":"adivinhacao.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595950129","text":"import datetime as dt\nimport pandas as pd\nimport math\nimport copy\n\nfrom paul_resources import InformationTable\nfrom option_model.Distribution_Module import Distribution, Distribution_MultiIndex, float_to_event_distribution, \\\n float_to_volbeta_distribution\nfrom option_model.Option_Module import get_time_to_expiry\nfrom option_model.Timing_Module import event_prob_by_expiry\nimport logging\n\n# Logging Setup\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nformatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s', \"%m/%d/%Y %H:%M\")\n\nfile_handler = logging.FileHandler('event_instances.log')\nfile_handler.setLevel(logging.INFO)\nfile_handler.setFormatter(formatter)\n\n#stream_handler = logging.StreamHandler()\n\nlogger.addHandler(file_handler)\n#logger.addHandler(stream_handler)\n\nclass GeneralEvent(object):\n name = 'General Event'\n abbrev_name = 'GenEvent'\n timing = None\n instances = ['Event']\n #main_lever = 2.0\n\n def __init__(self, timing_descriptor = timing):\n self.timing_descriptor = timing_descriptor\n\n for cls in type(self).__mro__[0:-1]:\n cls.instances.append(self)\n \n if type(self).__name__ == 'GeneralEvent':\n logger.info(\"General Event Instantiated Successfully\")\n\n def __str__(self):\n return \"{}\".format(self.abbrev_name)\n\n def __repr__(self):\n return \"{}\".format(self.abbrev_name)\n\n\nclass Event(GeneralEvent):\n name = 'Event'\n abbrev_name = 'SysEvent'\n timing = None\n mult = 1.0\n \n def __init__(self,\n stock: 'str',\n event_input: 'float or distribution object' = None,\n timing_descriptor = timing,\n event_name = None,\n idio_mult = 1.0):\n super().__init__(timing_descriptor = timing_descriptor)\n self.event_input_value = event_input\n \n self.stock = stock\n \n if type(event_input) is int or type(event_input) is float:\n self.event_input = float_to_event_distribution(event_input)\n else:\n self.event_input = event_input\n \n #if timing_descriptor is None:\n # self.timing_descriptor = self.timing\n #self.timing_descriptor = timing_descriptor\n if event_name is None:\n self.event_name = self.abbrev_name\n else:\n self.event_name = event_name\n self.idio_mult = idio_mult\n\n logger.info(\"{} {} Instantiated Successfully\".format(self.stock, self.name))\n \n if type(self).__name__ == 'Event':\n logger.info(\"{} Systematic Event Instantiated Successfully\".format(self.stock))\n \n def __str__(self):\n return \"{} ({:.2f}% move)\".format(self.name, self.modeled_move*100)\n\n def __repr__(self):\n return \"{}\".format(self.event_name)\n #return \"{} ({})\".format(self.abbrev_name, self.stock)\n\n @property\n def event_input_distribution_df(self):\n return self.event_input.distribution_df\n\n @property\n def modeled_move(self):\n return self.get_distribution().mean_move\n\n def set_idio_mult(self, new_value):\n self.idio_mult = new_value\n\n def set_move_input(self, new_value):\n self.event_input = new_value\n\n def get_distribution(self, expiry = None, *args, **kwargs):\n event_by_expiry = event_prob_by_expiry(self.timing_descriptor, expiry)\n event_not_by_expiry = 1 - event_by_expiry\n\n distribution_df = copy.deepcopy(self.event_input_distribution_df)\n distribution_df.loc[:, 'Pct_Move'] *= self.mult*self.idio_mult\n distribution_df.loc[:, 'Relative_Price'] = distribution_df.loc[:, 'Pct_Move'] + 1\n distribution_df.loc[:, 'Prob'] *= event_by_expiry\n \n no_event_scenario = {'State': ['No_Event'],\n 'Prob': [event_not_by_expiry],\n 'Pct_Move': [0],\n 'Relative_Price': [1.0]}\n \n no_event_scenario = pd.DataFrame(no_event_scenario).set_index('State').loc[:, ['Prob', 'Pct_Move', 'Relative_Price']]\n \n distribution_df = distribution_df.append(no_event_scenario)\n return Distribution(distribution_df)\n\n @property\n def event_bid(self):\n return Event(self.stock,\n self.event_input*.9,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n \n @property\n def event_ask(self):\n return Event(self.stock,\n self.event_input*1.1,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n @property\n def event_width(self):\n return self.event_ask.get_distribution().mean_move - self.event_bid.get_distribution().mean_move\n\nclass IdiosyncraticVol(Event):\n name = 'Idiosyncratic Vol'\n abbrev_name = 'Idio_Vol'\n timing = None\n mult = 1.0\n instances = []\n\n def __init__(self,\n stock: 'str',\n event_input: 'float',\n idio_mult = 1.0):\n super().__init__(stock, idio_mult = idio_mult)\n \n if type(event_input) is int or type(event_input) is float:\n self.event_input = float_to_volbeta_distribution(event_input)\n else:\n self.event_input = event_input\n logger.info(\"{} {} Instantiated Successfully\".format(self.stock, self.name))\n \n def get_distribution(self, expiry):\n time_to_expiry = get_time_to_expiry(expiry)\n distribution_df = copy.deepcopy(self.event_input_distribution_df)\n distribution_df.loc[:, 'Pct_Move'] *= self.mult*self.idio_mult*math.sqrt(time_to_expiry)\n distribution_df.loc[:, 'Relative_Price'] = distribution_df.loc[:, 'Pct_Move'] + 1\n return Distribution(distribution_df)\n\n @property\n def event_bid(self):\n return IdiosyncraticVol(self.stock,\n self.event_input*.95,\n self.idio_mult)\n \n @property\n def event_ask(self):\n return IdiosyncraticVol(self.stock,\n self.event_input*1.05,\n self.idio_mult)\n\nclass SysEvt_PresElection(Event):\n name = 'U.S. Presidential Election'\n abbrev_name = 'Elec.'\n timing = dt.date(2018, 11, 3)\n mult = 1.0\n instances = []\n \n def __init__(self,\n stock: 'str',\n event_input: 'float',\n idio_mult = 1.0):\n super().__init__(stock = stock,\n event_input = event_input,\n timing_descriptor = self.timing,\n idio_mult = idio_mult)\n \n logger.info(\"{} Presidential Election Event Instantiated Successfully\".format(self.stock))\n\nclass Earnings(Event):\n name = 'Earnings'\n abbrev_name = 'Earns.'\n timing = None\n mult = 1.0\n instances = []\n \n def __init__(self,\n stock: 'str',\n event_input: 'float',\n timing_descriptor,\n event_name = name,\n idio_mult = 1.0):\n super().__init__(stock = stock,\n event_input = event_input,\n timing_descriptor = timing_descriptor,\n event_name = event_name,\n idio_mult = idio_mult,\n )\n \n logger.info(\"{} {} Earnings Event Instantiated Successfully\".format(self.stock, self.quarter))\n \n def __repr__(self):\n return \"{} ({})\".format(self.abbrev_name, self.quarter)\n #return \"{} ({})\".format(self.abbrev_name, Timing(self.timing_descriptor).timing_descriptor_abbrev)\n #return \"{}-{} ({})\".format(self.abbrev_name, self.timing_descriptor, self.stock)\n \n @property\n def quarter(self):\n return self.event_name[0:2]\n \n @property\n def event_bid(self):\n return Earnings(self.stock,\n self.event_input*.925,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n \n @property\n def event_ask(self):\n return Earnings(self.stock,\n self.event_input*1.075,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n \n\nclass ComplexEvent(Event):\n name = 'Complex_Event'\n abbrev_name = 'Complex_Evt'\n timing = None\n mult = 1.0\n instances = []\n \n def __init__(self,\n stock: 'str',\n event_input: 'float',\n timing_descriptor,\n event_name = None,\n idio_mult = 1.0):\n super().__init__(stock = stock,\n event_input = event_input,\n timing_descriptor = timing_descriptor,\n event_name = event_name,\n idio_mult = idio_mult,\n )\n \n logger.info(\"{} {} Complex Event Instantiated Successfully\".format(self.stock, self.timing_descriptor))\n @property\n def event_bid(self):\n return ComplexEvent(self.stock,\n self.event_input*.925,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n \n @property\n def event_ask(self):\n return ComplexEvent(self.stock,\n self.event_input*1.075,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n\n \n def event_prob_success(self, new_prob_success):\n new_distribution = Distribution_MultiIndex(self.event_input_distribution_df)\n new_distribution.set_prob_success(new_prob_success)\n new_event = ComplexEvent(self.stock,\n new_distribution,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n print(new_event.event_input_distribution_df.to_string())\n return new_event\n \n @property\n def event_high_prob_success(self):\n return self.event_prob_success(.95)\n\n @property\n def event_low_prob_success(self):\n return self.event_prob_success(.05)\n \n @property\n def event_max_optionality(self):\n new_distribution = Distribution_MultiIndex(self.event_input_distribution_df)\n \n most_positive_state = new_distribution.positive_scenario_states[0][1]\n new_distribution.set_positive_scenario_substate_prob(most_positive_state, 1.0)\n \n most_negative_state = new_distribution.negative_scenario_states[-1][1]\n new_distribution.set_negative_scenario_substate_prob(most_negative_state, 1.0)\n\n new_distribution.set_prob_success(.5)\n\n new_event = ComplexEvent(self.stock,\n new_distribution,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n print(new_event.event_input_distribution_df.to_string())\n return new_event\n return self.event_prob_success(.05)\n\nclass TakeoutEvent(GeneralEvent):\n name = 'Takeout'\n abbrev_name = 'T.O.'\n timing = None\n mult = 1.0\n instances = []\n \n takeout_buckets = pd.read_csv('TakeoutBuckets.csv')\n takeout_buckets.set_index('Rank', inplace=True)\n\n base_takeout_premium = .35\n base_mcap = 8750\n mcap_sensitivity = .3\n \"\"\"\n def __init__(self,\n stock: 'str',\n takeout_bucket: 'int',\n event_input: 'float or distribution object' = None,\n timing_descriptor = None,\n event_name = name,\n idio_mult = 1.0):\n super().__init__()\n \"\"\" \n def __init__(self, stock: 'str', takeout_bucket: 'int'):\n super().__init__()\n self.stock = stock\n self.takeout_bucket = takeout_bucket\n logger.info(\"{} Takeout Event Instantiated Successfully.\".format(self.stock))\n\n def __str__(self):\n return \"{}-{} ({})\".format(self.abbrev_name, self.takeout_bucket, self.stock)\n \n def __repr__(self):\n return \"{} Tier {} ({})\".format(self.abbrev_name, self.takeout_bucket, self.stock)\n\n @property\n def takeout_prob(self):\n return self.takeout_buckets.loc[self.takeout_bucket, 'Prob']\n \n @property\n def mcap(self):\n try:\n return InformationTable.loc[self.stock, 'Market Cap'] \n except Exception:\n logger.error(\"{} did not register a Market Cap. Check error source.\".format(self.stock))\n return self.base_mcap\n\n @property\n def takeout_premium_adjustment(self):\n return min(((1 / (self.mcap/self.base_mcap)) - 1)*self.mcap_sensitivity, 1.5)\n\n @property\n def takeout_premium(self):\n return self.base_takeout_premium * (1 + self.takeout_premium_adjustment)\n\n \n def get_distribution(self, expiry: 'dt.date', *args, **kwargs):\n time_to_expiry = get_time_to_expiry(expiry)\n prob_takeout_by_expiry = time_to_expiry * self.takeout_prob\n prob_no_takeout_by_expiry = 1 - prob_takeout_by_expiry\n\n relative_price_takeout = (1 + self.takeout_premium)\n relative_price_no_takeout = 1-(prob_takeout_by_expiry*self.takeout_premium) / (prob_no_takeout_by_expiry)\n \n distribution_info = {'States': ['Takeout', 'No Takeout'],\n 'Prob': [prob_takeout_by_expiry, prob_no_takeout_by_expiry],\n 'Relative_Price': [relative_price_takeout, relative_price_no_takeout],\n 'Pct_Move': [self.takeout_premium, relative_price_no_takeout-1]}\n \n distribution_df = pd.DataFrame(distribution_info).set_index('States').loc[:, ['Prob', 'Pct_Move', 'Relative_Price']]\n return Distribution(distribution_df)\n \n @property\n def event_bid(self):\n return TakeoutEvent(self.stock, min(self.takeout_bucket + 2, 7))\n #return TakeoutEvent(self.stock, 7)\n \n @property\n def event_ask(self):\n return TakeoutEvent(self.stock, max(self.takeout_bucket - 1, 1))\n","sub_path":"Old_Versions/Event_Module_oldR/Event_Module_4.py","file_name":"Event_Module_4.py","file_ext":"py","file_size_in_byte":14455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529334388","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 19 14:04:54 2021\n\n@author: trduong\n\"\"\"\n\nimport torch \nimport pyro \n\ndef weather():\n cloudy = torch.distributions.Bernoulli(0.3).sample()\n cloudy = 'cloudy' if cloudy.item() == 1 else 'sunny'\n mean_temp = {'cloudy': 55.0, 'sunny': 75.0}[cloudy]\n scale_temp = {'cloudy': 10.0, 'sunny': 15.0}[cloudy]\n temp = torch.distributions.Normal(mean_temp, scale_temp).rsample()\n return cloudy, temp.item()\n\ndef ice_cream_sales():\n cloudy, temp = weather()\n expected_sales = 200. if cloudy == 'sunny' and temp > 80.0 else 50.\n ice_cream = pyro.sample('ice_cream', pyro.distributions.Normal(expected_sales, 10.0))\n return ice_cream\n\n\nif __name__ == \"__main__\":\n for _ in range(3):\n print(weather())","sub_path":"my-implementation/intro_pyro.py","file_name":"intro_pyro.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"223090375","text":"\"\"\"\nresolve.py: a recursive resolver built using dnspython\n\"\"\"\n\nimport argparse\n\nimport dns.message\nimport dns.name\nimport dns.query\nimport dns.rdata\nimport dns.rdataclass\nimport dns.rdatatype\n\nFORMATS = ((\"CNAME\", \"{alias} is an alias for {name}\"),\n (\"A\", \"{name} has address {address}\"),\n (\"AAAA\", \"{name} has IPv6 address {address}\"),\n (\"MX\", \"{name} mail is handled by {preference} {exchange}\"))\n\n# current as of 19 March 2018\nROOT_SERVERS = (\"198.41.0.4\",\n \"199.9.14.201\",\n \"192.33.4.12\",\n \"199.7.91.13\",\n \"192.203.230.10\",\n \"192.5.5.241\",\n \"192.112.36.4\",\n \"198.97.190.53\",\n \"192.36.148.17\",\n \"192.58.128.30\",\n \"193.0.14.129\",\n \"199.7.83.42\",\n \"202.12.27.33\")\n\nQUERIED_SERVERS_STACK = {} \n\ndef collect_results(name: str) -> dict:\n \"\"\"\"\n This function parses final answers into the proper data structure that\n print_results requires. The main work is done within the `lookup` function.\n \"\"\"\n full_response = {}\n target_name = dns.name.from_text(name)\n # lookup CNAME\n response = lookup(target_name, dns.rdatatype.CNAME)\n cnames = []\n for answers in response.answer:\n for answer in answers:\n cnames.append({\"name\": answer, \"alias\": name})\n # lookup A\n response = lookup(target_name, dns.rdatatype.A)\n arecords = []\n for answers in response.answer:\n a_name = answers.name\n for answer in answers:\n if answer.rdtype == 1: # A record\n arecords.append({\"name\": a_name, \"address\": str(answer)})\n # lookup AAAA\n response = lookup(target_name, dns.rdatatype.AAAA)\n aaaarecords = []\n for answers in response.answer:\n aaaa_name = answers.name\n for answer in answers:\n if answer.rdtype == 28: # AAAA record\n aaaarecords.append({\"name\": aaaa_name, \"address\": str(answer)})\n # lookup MX\n response = lookup(target_name, dns.rdatatype.MX)\n mxrecords = []\n for answers in response.answer:\n mx_name = answers.name\n for answer in answers:\n if answer.rdtype == 15: # MX record\n mxrecords.append({\"name\": mx_name,\n \"preference\": answer.preference,\n \"exchange\": str(answer.exchange)})\n\n full_response[\"CNAME\"] = cnames\n full_response[\"A\"] = arecords\n full_response[\"AAAA\"] = aaaarecords\n full_response[\"MX\"] = mxrecords\n\n return full_response\n\ndef lookup(target_name: dns.name.Name,\n qtype: dns.rdata.Rdata) -> dns.message.Message:\n \"\"\"\n This function uses a recursive resolver to find the relevant answer to the\n query.\n\n TODO: replace this implementation with one which asks the root servers\n and recurses to find the proper answer.\n \"\"\"\n outbound_query = dns.message.make_query(target_name, qtype)\n for addr in ROOT_SERVERS:\n try:\n response = dns.query.udp(outbound_query, addr, 3)\n except dns.exception.Timeout:\n continue\n except dns.query.BadResponse:\n continue\n except dns.query.UnexpectedSource:\n continue\n '''\n For every A record in received in the response, add it to the set\n of unique server\n '''\n name_servers = []#store all the unique name server to a query\n for each in response.additional:\n if each.rdtype == dns.rdatatype.A and each not in name_servers:\n name_servers.append(each)\n\n auth_servers = []\n for each in name_servers:\n try:\n _name_query = dns.message.make_query(target_name, qtype)\n response = dns.query.udp(_name_query, str(each.items[0]), 3)\n except dns.exception.Timeout:\n continue\n except dns.query.BadResponse:\n continue\n except dns.query.UnexpectedSource:\n continue\n if response.answer:\n return response\n if response.authority and not response.additional:\n continue\n for each in response.additional:\n if each.rdtype == dns.rdatatype.A:\n try:\n _authority_query = dns.message.make_query(target_name,\n qtype)\n response = dns.query.udp(_authority_query,\n str(each.items[0]), 3)\n except dns.exception.Timeout:\n continue\n except dns.query.BadResponse:\n continue\n except dns.query.UnexpectedSource:\n continue\n if response.answer:\n return response\n #QUERIED_SERVERS_STACK.update\n return response\n\ndef print_results(results: dict) -> None:\n \"\"\"\n take the results of a `lookup` and print them to the screen like the host\n program would.\n \"\"\"\n\n for rtype, fmt_str in FORMATS:\n for result in results.get(rtype, []):\n print(fmt_str.format(**result))\n\ndef main():\n \"\"\"\n if run from the command line, take args and call\n printresults(lookup(hostname))\n \"\"\"\n argument_parser = argparse.ArgumentParser()\n argument_parser.add_argument(\"name\", nargs=\"+\",\n help=\"DNS name(s) to look up\")\n argument_parser.add_argument(\"-v\", \"--verbose\",\n help=\"increase output verbosity\",\n action=\"store_true\")\n program_args = argument_parser.parse_args()\n fuckall = []\n for a_domain_name in program_args.name:\n if a_domain_name not in fuckall:\n print_results(collect_results(a_domain_name))\n fuckall.append(a_domain_name)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hw4/resolve.py","file_name":"resolve.py","file_ext":"py","file_size_in_byte":6016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"373705246","text":"import numpy as np\nimport matplotlib.pyplot as plot\n\ndef coefs():\n return 4,3,1\n\ndef f(x):\n a, b, c = coefs()\n return a * x[0] + x[1] + 4 * np.sqrt(1 + b * x[0] ** 2 + c * x[1] ** 2)\n\ndef grad_f(x):\n a, b, c = coefs()\n return np.asarray([a + 4 * b * x[0] / np.sqrt(1 + b * x[0] ** 2 + c * x[1] ** 2),\n 1 + 4 * c * x[1] / np.sqrt(1 + b * x[0] ** 2 + c * x[1] ** 2)])\n\ndef norm(x):\n if x is None:\n return float('inf')\n return np.sqrt(x[0] ** 2 + x[1] ** 2)\n\ndef fib(n):\n numbers = [1, 1]\n for i in range(2, n):\n num = numbers[i - 2] + numbers[i - 1]\n numbers.append(num)\n return numbers\n\ndef fib_min(nums, x_k, grad_k):\n a = 0\n b = 1\n lam = a + nums[-3] / nums[-1] * (b - a)\n mu = a + nums[-2] / nums[-1] * (b - a)\n f_lam = f(x_k - lam * grad_k)\n f_mu = f(x_k - mu * grad_k)\n for i in range(1, len(nums)):\n if f_lam > f_mu:\n a = lam\n lam = mu\n mu = a + nums[-1 - i - 1] / nums[-1 - i] * (b - a)\n if i == len(nums) - 3:\n break\n f_lam = f_mu\n f_mu = f(x_k - mu * grad_k)\n else:\n b = mu\n mu = lam\n lam = a + nums[-1 - i - 2] / nums[-1 - i] * (b - a)\n if i == len(nums) - 3:\n break\n f_mu = f_lam\n f_lam = f(x_k - lam * grad_k)\n if f_lam >= f_mu:\n return (lam + b) / 2\n else:\n return (a + mu) / 2\n\nclass Solver:\n x: list\n iters = 0\n fib_iter_num = 20\n\n def __init__(self):\n self.x = []\n\n def get_x_seq(self):\n return self.x.copy()\n\n def get_iter_num(self):\n return self.iters\n\n def draw_contoures(self):\n fig, axis = plot.subplots()\n x = np.ndarray((1,len(self.x)))\n y = np.ndarray((1,len(self.x)))\n for i in range(len(self.x)):\n x[0, i] = self.x[i][0]\n y[0, i] = self.x[i][1]\n x_mesh_min = np.min(x)\n x_mesh_max = np.max(x)\n x_mesh_delta = (x_mesh_max - x_mesh_min) / 10\n x_mesh_min -= x_mesh_delta\n x_mesh_max += x_mesh_delta\n y_mesh_min = np.min(y)\n y_mesh_max = np.max(y)\n y_mesh_delta = (y_mesh_max - y_mesh_min) / 10\n y_mesh_min -= y_mesh_delta\n y_mesh_max += y_mesh_delta\n mesh_dest = max(x_mesh_max - x_mesh_min, y_mesh_max - y_mesh_min)\n x_mesh_max = x_mesh_min + mesh_dest\n y_mesh_max = y_mesh_min + mesh_dest\n x_mesh, y_mesh = np.mgrid[x_mesh_min:x_mesh_max:100j, y_mesh_min:y_mesh_max:100j]\n z = np.ndarray(x_mesh.shape)\n for i in range(x_mesh.shape[0]):\n for j in range(x_mesh.shape[1]):\n z[i,j] = f((x_mesh[i,j], y_mesh[i,j]))\n cs = axis.contour(x_mesh, y_mesh, z, levels=15)\n axis.plot(x.tolist()[0], y.tolist()[0], 'bX--')\n axis.clabel(cs, colors=\"black\")\n fig.set_figwidth(8)\n fig.set_figheight(8)\n return fig, axis\n\n\nclass FastestDesc(Solver):\n def __init__(self):\n super(FastestDesc, self).__init__()\n\n def get_solution(self, x_0, eps):\n self.x = [np.asarray(x_0)]\n self.iters = 0\n fib_nums = fib(self.fib_iter_num)\n grad = None\n while norm(grad) >= eps:\n grad = grad_f(self.x[-1])\n alpha = fib_min(fib_nums, self.x[-1], grad)\n self.x.append(self.x[-1] - alpha * grad)\n self.iters += 1\n print(\"x1 = \", self.x[-1][0], \"x2 = \", self.x[-1][1])\n print(\"step =\", alpha)\n return self.x[-1]\n\nclass DFP(Solver):\n def __init__(self):\n super().__init__()\n\n def refresh_matrix(self, A):\n dx = self.x[-1] - self.x[-2]\n dw = grad_f(self.x[-2]) - grad_f(self.x[-1])\n return A - np.outer(dx, dx) / np.dot(dw, dx) - A.dot(np.outer(dw, dw)).dot(A.transpose()) / (np.dot(dw, A.dot(dw)))\n\n def get_solution(self, x_0, eps):\n self.x = [np.asarray(x_0)]\n self.iters = 0\n fib_nums = fib(self.fib_iter_num)\n grad = None\n A = np.eye(2)\n while norm(grad) >= eps:\n grad = grad_f(self.x[-1])\n p = A.dot(grad)\n alpha = fib_min(fib_nums, self.x[-1], p)\n self.x.append(self.x[-1] - alpha * p)\n self.iters += 1\n if self.iters % 2 == 0:\n A = self.refresh_matrix(A)\n print(\"x1 = \", self.x[-1][0],\"x2 = \", self.x[-1][1] )\n print(\"step =\", alpha)\n return self.x[-1]\n","sub_path":"LAB4/gradient/DFP.py","file_name":"DFP.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371067067","text":"#last updated by Andre on 9/02/2015\nfrom Node import Node\n\nclass Signal:\n def __init__(self, experiment, link, value):\n self.experiment = experiment\n self.turnSent = experiment.turnCount\n self.link = link\n self.value = value\n link.end.receivedSignals.append(self)\n link.start.sentSignals.append(self)\n \n \n","sub_path":"Signal.py","file_name":"Signal.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"577704545","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def is_sys_tree(self, root):\n def check(p, q):\n if not p and not q:\n return True\n if not p or not q:\n return False\n if p.val != q.val:\n return False\n return check(p.left, q.right) and check(p.right, q.left)\n return check(root, root)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nprint(\"--------------------ansert----------------------思路1\")\n\n\n# class Solution(object):\n# def isSymmetric(self, root):\n# \"\"\"\n# :type root: TreeNode\n# :rtype: bool\n# \"\"\"\n#\n# def check(node1, node2):\n# if not node1 and not node2:\n# return True\n# elif not node1 or not node2:\n# return False\n#\n# if node1.val != node2.val:\n# return False\n# return check(node1.left, node2.right) and check(node1.right, node2.left)\n#\n# return check(root, root)\n\n\n","sub_path":"sample/100_Same_Tree.py","file_name":"100_Same_Tree.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"268572325","text":"import warnings\nimport copy\nimport json\nimport logging\nfrom contextlib import contextmanager\nfrom functools import partial\nfrom numbers import Number\nimport os\nfrom pathlib import Path\nimport platform\nimport re\nimport shutil\nimport time\nfrom typing import Any, Dict, Optional, Sequence, Union, Callable, List, Tuple\nimport uuid\n\nimport ray\nfrom ray.air import CheckpointConfig\nfrom ray.air._internal.uri_utils import URI\nfrom ray.air._internal.checkpoint_manager import _TrackedCheckpoint, CheckpointStorage\nfrom ray.air.constants import (\n EXPR_ERROR_PICKLE_FILE,\n EXPR_ERROR_FILE,\n TRAINING_ITERATION,\n)\n\nimport ray.cloudpickle as cloudpickle\nfrom ray.exceptions import RayActorError, RayTaskError\nfrom ray.train import Checkpoint\nfrom ray.train._internal.checkpoint_manager import (\n _TrainingResult,\n _CheckpointManager as _NewCheckpointManager,\n)\nfrom ray.train._internal.storage import _use_storage_context, StorageContext\nfrom ray.tune import TuneError\nfrom ray.tune.error import _TuneRestoreError\nfrom ray.tune.execution.checkpoint_manager import _CheckpointManager\nfrom ray.tune.logger import NoopLogger\n\n# NOTE(rkn): We import ray.tune.registry here instead of importing the names we\n# need because there are cyclic imports that may cause specific names to not\n# have been defined yet. See https://github.com/ray-project/ray/issues/1716.\nfrom ray.tune.registry import get_trainable_cls, validate_trainable\nfrom ray.tune.result import (\n DONE,\n NODE_IP,\n PID,\n TRIAL_ID,\n DEBUG_METRICS,\n TRIAL_INFO,\n STDOUT_FILE,\n STDERR_FILE,\n DEFAULT_EXPERIMENT_NAME,\n _get_defaults_results_dir,\n)\nfrom ray.train import SyncConfig\nfrom ray.tune.execution.placement_groups import (\n PlacementGroupFactory,\n resource_dict_to_pg_factory,\n)\nfrom ray.tune.trainable.metadata import _TrainingRunMetadata\nfrom ray.tune.utils.serialization import TuneFunctionDecoder, TuneFunctionEncoder\nfrom ray.tune.trainable.util import TrainableUtil\nfrom ray.tune.utils import date_str, flatten_dict\nfrom ray.tune.utils.util import _split_remote_local_path\nfrom ray.util.annotations import DeveloperAPI, Deprecated\nfrom ray.util.debug import log_once\nfrom ray._private.utils import binary_to_hex, hex_to_binary\n\n\nDEBUG_PRINT_INTERVAL = 5\n_DEFAULT_WIN_MAX_PATH_LENGTH = 260\nTRIAL_STATE_FILENAME = \"trial_metadata.json\"\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass _Location:\n \"\"\"Describes the location at which Trial is placed to run.\"\"\"\n\n def __init__(self, hostname=None, pid=None):\n self.hostname = hostname\n self.pid = pid\n\n def __str__(self):\n if not self.pid:\n return \"\"\n elif self.hostname == platform.node():\n return \"pid={}\".format(self.pid)\n else:\n return \"{}:{}\".format(self.hostname, self.pid)\n\n\n@DeveloperAPI\nclass ExportFormat:\n \"\"\"Describes the format to import/export the trial Trainable.\n\n This may correspond to different file formats based on the\n Trainable implementation.\n \"\"\"\n\n CHECKPOINT = \"checkpoint\"\n MODEL = \"model\"\n ONNX = \"onnx\"\n H5 = \"h5\"\n\n @staticmethod\n def validate(formats):\n \"\"\"Validates formats.\n\n Raises:\n ValueError if the format is unknown.\n \"\"\"\n for i in range(len(formats)):\n formats[i] = formats[i].strip().lower()\n if formats[i] not in [\n ExportFormat.CHECKPOINT,\n ExportFormat.MODEL,\n ExportFormat.ONNX,\n ExportFormat.H5,\n ]:\n raise TuneError(\"Unsupported import/export format: \" + formats[i])\n\n\nclass _CheckpointDeleter:\n \"\"\"Checkpoint deleter callback for a runner.\"\"\"\n\n def __init__(self, trial_id, ray_actor):\n self.trial_id = trial_id\n self.ray_actor = ray_actor\n\n def __call__(self, checkpoint: _TrackedCheckpoint):\n \"\"\"Requests checkpoint deletion asynchronously.\n\n Args:\n checkpoint: Checkpoint to delete.\n \"\"\"\n if not self.ray_actor:\n return\n\n if (\n checkpoint.storage_mode == CheckpointStorage.PERSISTENT\n and checkpoint.dir_or_data\n ):\n checkpoint_path = checkpoint.dir_or_data\n\n logger.debug(\n \"Trial %s: Deleting checkpoint %s\", self.trial_id, checkpoint_path\n )\n\n # TODO(ujvl): Batch remote deletes.\n # We first delete the remote checkpoint. If it is on the same\n # node as the driver, it will also remove the local copy.\n ray.get(self.ray_actor.delete_checkpoint.remote(checkpoint_path))\n\n # Delete local copy, if any exists.\n if os.path.exists(checkpoint_path):\n try:\n checkpoint_dir = TrainableUtil.find_checkpoint_dir(checkpoint_path)\n shutil.rmtree(checkpoint_dir)\n except FileNotFoundError:\n logger.debug(\"Local checkpoint dir not found during deletion.\")\n\n\nclass _TrialInfo:\n \"\"\"Serializable struct for holding information for a Trial.\n\n Attributes:\n trial_name: String name of the current trial.\n trial_id: trial_id of the trial\n trial_resources: resources used by trial.\n \"\"\"\n\n def __init__(self, trial: \"Trial\"):\n self._trial_name = str(trial)\n self._trial_id = trial.trial_id\n self._trial_resources = trial.placement_group_factory\n self._experiment_name = trial.experiment_dir_name\n\n @property\n def experiment_name(self):\n return self._experiment_name\n\n @property\n def trial_name(self):\n return self._trial_name\n\n @property\n def trial_id(self):\n return self._trial_id\n\n @property\n def trial_resources(self) -> PlacementGroupFactory:\n return self._trial_resources\n\n @trial_resources.setter\n def trial_resources(self, new_resources: PlacementGroupFactory):\n self._trial_resources = new_resources\n\n\nclass _TemporaryTrialState:\n \"\"\"Temporary trial state.\n\n Values saved here should not be restored on resume.\n \"\"\"\n\n def __init__(self):\n self.location = _Location()\n\n self.ray_actor = None\n\n self.saving_to = None\n self.restoring_from = None\n\n self.num_restore_failures = 0\n\n def __getstate__(self):\n return {}\n\n\ndef _get_max_path_length() -> int:\n if hasattr(os, \"pathconf\"):\n return os.pathconf(\"/\", \"PC_PATH_MAX\")\n # Windows\n return _DEFAULT_WIN_MAX_PATH_LENGTH\n\n\ndef _create_unique_logdir_name(root: str, relative_logdir: str) -> str:\n candidate = Path(root).expanduser().joinpath(relative_logdir)\n if candidate.exists():\n relative_logdir_old = relative_logdir\n relative_logdir += \"_\" + uuid.uuid4().hex[:4]\n logger.info(\n f\"Creating a new dirname {relative_logdir} because \"\n f\"trial dirname '{relative_logdir_old}' already exists.\"\n )\n return relative_logdir\n\n\ndef _noop_logger_creator(\n config: Dict[str, Any], logdir: str, should_chdir: bool = True\n):\n # Upon remote process setup, record the actor's original working dir before\n # changing to the Tune logdir\n os.environ.setdefault(\"TUNE_ORIG_WORKING_DIR\", os.getcwd())\n\n os.makedirs(logdir, exist_ok=True)\n if should_chdir:\n # Set the working dir to the trial directory in the remote process,\n # for user file writes\n if not ray._private.worker._mode() == ray._private.worker.LOCAL_MODE:\n os.chdir(logdir)\n return NoopLogger(config, logdir)\n\n\ndef _get_trainable_kwargs(\n trial: \"Trial\",\n should_chdir: bool = False,\n) -> Dict[str, Any]:\n trial.init_local_path()\n\n logger_creator = partial(\n _noop_logger_creator,\n logdir=trial.local_path,\n should_chdir=should_chdir,\n )\n\n trial_config = copy.deepcopy(trial.config)\n trial_config[TRIAL_INFO] = _TrialInfo(trial)\n stdout_file, stderr_file = trial.log_to_file\n trial_config[STDOUT_FILE] = stdout_file\n trial_config[STDERR_FILE] = stderr_file\n\n kwargs = {\n \"config\": trial_config,\n \"logger_creator\": logger_creator,\n }\n\n if _use_storage_context():\n assert trial.storage\n assert trial.storage.trial_dir_name\n kwargs[\"storage\"] = trial.storage\n\n if trial.uses_cloud_checkpointing:\n # We keep these kwargs separate for backwards compatibility\n # with trainables that don't provide these keyword arguments\n kwargs[\"remote_checkpoint_dir\"] = trial.remote_path\n kwargs[\"sync_config\"] = trial.legacy_sync_config\n\n return kwargs\n\n\n@contextmanager\ndef _change_working_directory(trial):\n \"\"\"Context manager changing working directory to trial logdir.\n Used in local mode.\n\n For non-local mode it is no-op.\n \"\"\"\n if ray._private.worker._mode() == ray._private.worker.LOCAL_MODE:\n old_dir = os.getcwd()\n try:\n os.chdir(trial.local_path)\n yield\n finally:\n os.chdir(old_dir)\n else:\n yield\n\n\n@DeveloperAPI\nclass Trial:\n \"\"\"A trial object holds the state for one model training run.\n\n Trials are themselves managed by the TrialRunner class, which implements\n the event loop for submitting trial runs to a Ray cluster.\n\n Trials start in the PENDING state, and transition to RUNNING once started.\n On error, it transitions to ERROR, otherwise TERMINATED on success.\n\n There are resources allocated to each trial. These should be specified\n using ``PlacementGroupFactory``.\n\n Attributes:\n trainable_name: Name of the trainable object to be executed.\n config: Provided configuration dictionary with evaluated params.\n trial_id: Unique identifier for the trial.\n path: Path where results for this trial are stored. Can be on\n the local node or on cloud storage.\n local_path: Path on the local disk where results are stored.\n remote_path: Path on cloud storage where results are stored,\n or None if not set.\n relative_logdir: Directory of the trial relative to its\n experiment directory.\n evaluated_params: Evaluated parameters by search algorithm,\n experiment_tag: Identifying trial name to show in the console\n status: One of PENDING, RUNNING, PAUSED, TERMINATED, ERROR/\n error_file: Path to the errors that this trial has raised.\n\n \"\"\"\n\n _nonjson_fields = [\n \"results\",\n \"extra_arg\",\n \"placement_group_factory\",\n \"_resources\",\n \"_default_placement_group_factory\",\n ]\n\n PENDING = \"PENDING\"\n RUNNING = \"RUNNING\"\n PAUSED = \"PAUSED\"\n TERMINATED = \"TERMINATED\"\n ERROR = \"ERROR\"\n\n def __init__(\n self,\n trainable_name: str,\n *,\n config: Optional[Dict] = None,\n trial_id: Optional[str] = None,\n storage: Optional[StorageContext] = None,\n experiment_path: Optional[str] = None,\n experiment_dir_name: Optional[str] = None,\n evaluated_params: Optional[Dict] = None,\n experiment_tag: str = \"\",\n placement_group_factory: Optional[PlacementGroupFactory] = None,\n stopping_criterion: Optional[Dict[str, float]] = None,\n sync_config: Optional[SyncConfig] = None,\n checkpoint_config: Optional[CheckpointConfig] = None,\n export_formats: Optional[List[str]] = None,\n restore_path: Optional[str] = None,\n trial_name_creator: Optional[Callable[[\"Trial\"], str]] = None,\n trial_dirname_creator: Optional[Callable[[\"Trial\"], str]] = None,\n log_to_file: Union[Optional[str], Tuple[Optional[str], Optional[str]]] = None,\n max_failures: int = 0,\n stub: bool = False,\n _setup_default_resource: bool = True,\n # Deprecated\n local_dir: Optional[str] = None,\n ):\n \"\"\"Initialize a new trial.\n\n The args here take the same meaning as the command line flags defined\n in ray.tune.experiment.config_parser.\n\n Args:\n _setup_default_resource: Whether to set up default resources.\n When initializing trials from checkpoints, this field is set to false,\n so that setting up default resources can be delayed till after\n ``trial.config`` is loaded from checkpoints.\n \"\"\"\n # If this is set, trainables are not validated or looked up.\n # This can be used e.g. to initialize Trial objects from checkpoints\n # without loading the trainable first.\n self.stub = stub\n\n if not self.stub:\n validate_trainable(trainable_name)\n # Trial config\n self.trainable_name = trainable_name\n self.trial_id = Trial.generate_id() if trial_id is None else trial_id\n\n self.temporary_state = _TemporaryTrialState()\n self.run_metadata = _TrainingRunMetadata()\n\n # Create a copy, since `init_local_path` updates the context with the\n # generated trial dirname.\n self.storage = copy.copy(storage)\n\n if _use_storage_context():\n self._legacy_orig_experiment_path = None\n self._legacy_orig_experiment_dir_name = None\n self._legacy_local_experiment_path = None\n self._legacy_remote_experiment_path = None\n self._legacy_experiment_dir_name = None\n self.legacy_sync_config = None\n else:\n # Set to pass through on `Trial.reset()`\n self._legacy_orig_experiment_path = experiment_path\n self._legacy_orig_experiment_dir_name = experiment_dir_name\n\n self._legacy_experiment_dir_name = experiment_dir_name\n\n # Sync config\n self.legacy_sync_config = sync_config or SyncConfig()\n\n local_experiment_path, remote_experiment_path = _split_remote_local_path(\n experiment_path, None\n )\n\n # Backwards compatibility for `local_dir`\n if local_dir:\n if local_experiment_path:\n raise ValueError(\n \"Only one of `local_dir` or `experiment_path` \"\n \"can be passed to `Trial()`.\"\n )\n local_experiment_path = local_dir\n\n # Derive experiment dir name from local path\n if not experiment_dir_name and local_experiment_path:\n # Maybe derive experiment dir name from local storage dir\n experiment_dir_name = Path(local_experiment_path).name\n elif not experiment_dir_name:\n experiment_dir_name = DEFAULT_EXPERIMENT_NAME\n\n # Set default experiment dir name\n if not local_experiment_path:\n local_experiment_path = str(\n Path(_get_defaults_results_dir()) / experiment_dir_name\n )\n os.makedirs(local_experiment_path, exist_ok=True)\n\n # Set remote experiment path if upload_dir is set\n if self.legacy_sync_config.upload_dir:\n if remote_experiment_path:\n if not remote_experiment_path.startswith(\n self.legacy_sync_config.upload_dir\n ):\n raise ValueError(\n f\"Both a `SyncConfig.upload_dir` and an `experiment_path` \"\n f\"pointing to remote storage were passed, but they do not \"\n f\"point to the same location. Got: \"\n f\"`experiment_path={experiment_path}` and \"\n \"`SyncConfig.upload_dir=\"\n f\"{self.legacy_sync_config.upload_dir}`. \"\n )\n warnings.warn(\n \"If `experiment_path` points to a remote storage location, \"\n \"do not set `SyncConfig.upload_dir`. \",\n DeprecationWarning,\n )\n else:\n remote_experiment_path = str(\n URI(self.legacy_sync_config.upload_dir) / experiment_dir_name\n )\n\n # Finally, set properties\n self._legacy_local_experiment_path = local_experiment_path\n self._legacy_remote_experiment_path = remote_experiment_path\n\n self.config = config or {}\n # Save a copy of the original unresolved config so that we can swap\n # out and update any reference config values after restoration.\n self.__unresolved_config = self.config\n\n # Parameters that Tune varies across searches.\n self.evaluated_params = evaluated_params or {}\n self.experiment_tag = experiment_tag\n self.stopping_criterion = stopping_criterion or {}\n\n self._setup_default_resource = _setup_default_resource\n\n if placement_group_factory and not isinstance(\n placement_group_factory, PlacementGroupFactory\n ):\n placement_group_factory = resource_dict_to_pg_factory(\n placement_group_factory\n )\n\n self._default_placement_group_factory = placement_group_factory\n # Will be created in create_placement_group_factory().\n self.placement_group_factory = None\n\n self.log_to_file = log_to_file\n # Make sure `stdout_file, stderr_file = Trial.log_to_file` works\n if (\n not self.log_to_file\n or not isinstance(self.log_to_file, Sequence)\n or not len(self.log_to_file) == 2\n ):\n self.log_to_file = (None, None)\n\n self.max_failures = max_failures\n\n # Local trial state that is updated during the run\n self._default_result_or_future: Union[ray.ObjectRef, dict, None] = None\n\n self.export_formats = export_formats\n self.status = Trial.PENDING\n self.relative_logdir = None\n\n self.trial_name_creator = trial_name_creator\n self.trial_dirname_creator = trial_dirname_creator\n self.custom_trial_name = None\n self.custom_dirname = None\n\n # Checkpoint config\n checkpoint_config = checkpoint_config or CheckpointConfig()\n if not _use_storage_context():\n # TODO(justinvyu): Why is this needed?\n checkpoint_config.checkpoint_score_attribute = (\n checkpoint_config.checkpoint_score_attribute or TRAINING_ITERATION\n )\n\n if _use_storage_context():\n self.run_metadata.checkpoint_manager = _NewCheckpointManager(\n checkpoint_config=checkpoint_config\n )\n else:\n self.run_metadata.checkpoint_manager = _CheckpointManager(\n checkpoint_config=checkpoint_config,\n delete_fn=_CheckpointDeleter(str(self), self.temporary_state.ray_actor),\n )\n\n # Restoration fields\n self.restore_path = restore_path\n self._restore_checkpoint_result: Optional[_TrainingResult] = None\n if restore_path:\n # tune.run(restore) passes in a path without metrics.\n self._restore_checkpoint_result = _TrainingResult(\n checkpoint=Checkpoint.from_directory(restore_path), metrics={}\n )\n\n if trial_name_creator:\n self.custom_trial_name = trial_name_creator(self)\n\n if trial_dirname_creator:\n self.custom_dirname = trial_dirname_creator(self)\n if os.path.sep in self.custom_dirname:\n raise ValueError(\n f\"Trial dirname must not contain '/'. Got {self.custom_dirname}\"\n )\n\n self._state_json = None\n\n def create_placement_group_factory(self):\n \"\"\"Compute placement group factory if needed.\n\n Note: this must be called after all the placeholders in\n self.config are resolved.\n \"\"\"\n trainable_cls = self.get_trainable_cls()\n if not trainable_cls or not self._setup_default_resource:\n # Create placement group factory using default resources.\n self.placement_group_factory = (\n self._default_placement_group_factory or resource_dict_to_pg_factory()\n )\n return\n\n default_resources = trainable_cls.default_resource_request(self.config)\n\n # If Trainable returns resources, do not allow manual override via\n # `resources_per_trial` by the user.\n if default_resources and self._default_placement_group_factory:\n raise TuneError(\n \"Resources for {} have been automatically set to {} \"\n \"by its `default_resource_request()` method. Please \"\n \"clear the `resources_per_trial` option.\".format(\n trainable_cls, default_resources\n )\n )\n\n if default_resources and not isinstance(\n default_resources, PlacementGroupFactory\n ):\n default_resources = resource_dict_to_pg_factory(default_resources)\n\n self.placement_group_factory = (\n # default_resource_request\n default_resources\n # resources_per_trial\n or self._default_placement_group_factory\n # cpu=1\n or resource_dict_to_pg_factory()\n )\n\n def _get_default_result_or_future(self) -> Optional[dict]:\n \"\"\"Calls ray.get on self._default_result_or_future and assigns back.\n\n Returns None in case of exceptions.\n Will also set the trial location if runner is set.\n \"\"\"\n if self._default_result_or_future and isinstance(\n self._default_result_or_future, ray.ObjectRef\n ):\n try:\n self._default_result_or_future = ray.get(self._default_result_or_future)\n except RayActorError: # error during initialization\n self._default_result_or_future = None\n if self._default_result_or_future and self.temporary_state.ray_actor:\n self.set_location(\n _Location(\n self._default_result_or_future.get(NODE_IP),\n self._default_result_or_future.get(PID),\n )\n )\n return self._default_result_or_future\n\n def resolve_config_placeholders(self, placeholder_resolvers: Dict[Tuple, Any]):\n from ray.tune.impl.placeholder import resolve_placeholders\n\n # Make a copy of the unresolved config before resolve it.\n self.config = copy.deepcopy(self.__unresolved_config)\n resolve_placeholders(self.config, placeholder_resolvers)\n\n @property\n def last_result(self) -> dict:\n # The logic in here is as follows:\n # 1. If the trial has reported at least once, last_result would have\n # been set and therefore would not be empty. We can just return it.\n # 2. If the trial has not reported at least once but we have the\n # future for the default results dict, (obtained through\n # Trainable.get_auto_filled_metrics), we get that future\n # and return it.\n # 3. In the worst case where we have nothing, we just set the\n # trial_id and return that.\n result = self.run_metadata.last_result\n if not {k for k in result if k != TRIAL_ID}:\n self._get_default_result_or_future()\n result = self._default_result_or_future or result\n result.setdefault(TRIAL_ID, self.trial_id)\n return result\n\n @property\n def metric_analysis(self):\n return self.run_metadata.metric_analysis\n\n @property\n def metric_n_steps(self):\n return self.run_metadata.metric_n_steps\n\n def get_ray_actor_ip(self) -> Optional[str]:\n if self.temporary_state.location.hostname:\n return self.temporary_state.location.hostname\n\n if not self.temporary_state.ray_actor:\n return None\n\n hostname, pid = ray.get(\n self.temporary_state.ray_actor.get_current_ip_pid.remote()\n )\n self.temporary_state.location = _Location(hostname, pid)\n return self.temporary_state.location.hostname\n\n @property\n @Deprecated(\"Replaced by `local_experiment_path`\")\n def local_dir(self):\n return self.local_experiment_path\n\n @property\n def experiment_dir_name(self):\n if _use_storage_context():\n return self.storage.experiment_dir_name\n\n return self._legacy_experiment_dir_name\n\n @experiment_dir_name.setter\n def experiment_dir_name(self, name: str):\n if _use_storage_context():\n raise RuntimeError(\"Set storage.experiment_dir_name instead.\")\n\n self._legacy_experiment_dir_name = name\n\n @property\n def remote_experiment_path(self) -> str:\n if _use_storage_context():\n return self.storage.experiment_fs_path\n\n return str(self._legacy_remote_experiment_path)\n\n @remote_experiment_path.setter\n def remote_experiment_path(self, remote_path: str):\n if _use_storage_context():\n raise RuntimeError(\"Set storage.experiment_dir_name instead.\")\n\n self._legacy_remote_experiment_path = remote_path\n\n @property\n def local_experiment_path(self) -> str:\n if _use_storage_context():\n return self.storage.experiment_local_path\n\n return str(self._legacy_local_experiment_path)\n\n @local_experiment_path.setter\n def local_experiment_path(self, local_path: str):\n if _use_storage_context():\n raise RuntimeError(\"Set storage.experiment_dir_name instead.\")\n\n relative_checkpoint_dirs = []\n if self.local_path:\n # Save the relative paths of persistent trial checkpoints, which are saved\n # relative to the old `local_dir`/`logdir`\n for checkpoint in self.get_trial_checkpoints():\n checkpoint_dir = checkpoint.dir_or_data\n if not isinstance(checkpoint_dir, str):\n logger.warning(\n f\"No data found in checkpoint for trial {self} and metrics \"\n f\"{checkpoint.metrics} (type: {type(checkpoint_dir)}). \"\n f\"Skipping.\"\n )\n continue\n\n relative_checkpoint_dirs.append(\n os.path.relpath(checkpoint_dir, self.local_path)\n )\n\n # Update the underlying `_legacy_local_experiment_path`,\n # which also updates the trial `local_path`\n self._legacy_local_experiment_path = local_path\n\n if self.local_path:\n for checkpoint, relative_checkpoint_dir in zip(\n self.get_trial_checkpoints(), relative_checkpoint_dirs\n ):\n # Reconstruct the checkpoint dir using the (possibly updated)\n # trial logdir and the relative checkpoint directory.\n checkpoint.dir_or_data = os.path.join(\n self.local_path, relative_checkpoint_dir\n )\n\n @property\n @Deprecated(\"Replaced by `local_path`\")\n def logdir(self) -> Optional[str]:\n # Deprecate: Raise in 2.5, Remove in 2.6\n return self.local_path\n\n @property\n def local_path(self) -> Optional[str]:\n if _use_storage_context():\n return self.storage.trial_local_path\n\n if not self.local_experiment_path or not self.relative_logdir:\n return None\n return str(Path(self.local_experiment_path).joinpath(self.relative_logdir))\n\n @local_path.setter\n def local_path(self, logdir):\n if _use_storage_context():\n raise RuntimeError(\"Set storage.trial_dir_name instead.\")\n\n relative_logdir = Path(logdir).relative_to(self.local_experiment_path)\n if \"..\" in str(relative_logdir):\n raise ValueError(\n f\"The `local_path` points to a directory outside the trial's \"\n f\"`local_experiment_path` ({self.local_experiment_path}), \"\n f\"which is unsupported. Use a logdir within the \"\n f\"local directory instead. Got: {logdir}\"\n )\n if log_once(\"logdir_setter\"):\n logger.warning(\n \"Deprecated. In future versions only the relative logdir \"\n \"will be used and calling logdir will raise an error.\"\n )\n self.relative_logdir = relative_logdir\n\n @property\n @Deprecated(\"Replaced by `remote_path`\")\n def remote_checkpoint_dir(self) -> Optional[str]:\n # Deprecate: Raise in 2.5, Remove in 2.6\n return self.remote_path\n\n @property\n def remote_path(self) -> Optional[str]:\n # TODO(justinvyu): Remove remote_path. It's just path vs local_path now.\n if _use_storage_context():\n return self.path\n\n if not self._legacy_remote_experiment_path or not self.relative_logdir:\n return None\n uri = URI(self._legacy_remote_experiment_path)\n return str(uri / self.relative_logdir)\n\n @property\n def path(self) -> Optional[str]:\n if _use_storage_context():\n return self.storage.trial_fs_path\n\n return self.remote_path or self.local_path\n\n @property\n def has_reported_at_least_once(self) -> bool:\n return bool(self.run_metadata.last_result)\n\n @property\n def node_ip(self):\n return self.location.hostname\n\n @property\n def sync_on_checkpoint(self):\n if _use_storage_context():\n return self.storage.sync_config.sync_on_checkpoint\n\n return self.legacy_sync_config.sync_on_checkpoint\n\n @property\n def checkpoint_at_end(self):\n config = self.run_metadata.checkpoint_manager.checkpoint_config\n return config.checkpoint_at_end\n\n @property\n def checkpoint_freq(self):\n config = self.run_metadata.checkpoint_manager.checkpoint_config\n return config.checkpoint_frequency\n\n @property\n def latest_checkpoint_result(self) -> Optional[_TrainingResult]:\n # NOTE: Fallback to the checkpoint passed in from `tune.run(restore)`\n # if the trial hasn't saved any checkpoints itself yet.\n return (\n self.run_metadata.checkpoint_manager.latest_checkpoint_result\n or self._restore_checkpoint_result\n )\n\n @property\n def checkpoint(self) -> Optional[Checkpoint]:\n \"\"\"Returns the most recent checkpoint if one has been saved.\"\"\"\n if _use_storage_context():\n return (\n self.latest_checkpoint_result.checkpoint\n if self.latest_checkpoint_result\n else None\n )\n\n if self.status == Trial.ERROR:\n checkpoint = (\n self.run_metadata.checkpoint_manager.newest_persistent_checkpoint\n )\n else:\n checkpoint = self.run_metadata.checkpoint_manager.newest_checkpoint\n if checkpoint.dir_or_data is None:\n checkpoint = _TrackedCheckpoint(\n dir_or_data=self.restore_path,\n storage_mode=CheckpointStorage.PERSISTENT,\n )\n return checkpoint\n\n @classmethod\n def generate_id(cls):\n return str(uuid.uuid4().hex)[:8]\n\n @property\n def uses_cloud_checkpointing(self):\n # TODO(justinvyu): This is entangled in the old restore codepaths.\n # Remove this once those are gone.\n if _use_storage_context():\n return False\n\n return bool(self.remote_path)\n\n def reset(self):\n # If there is `default_resource_request` associated with the trainable,\n # clear `resources` and `placement_group_factory`.\n # This is mainly relevant for RLlib tuning jobs, where we save users\n # of the trouble to specify the resources themselves by having some\n # default resources for popular RLlib algorithms.\n trainable_cls = self.get_trainable_cls()\n clear_resources = trainable_cls and trainable_cls.default_resource_request(\n self.config\n )\n placement_group_factory = (\n self.placement_group_factory if not clear_resources else None\n )\n\n checkpoint_config = self.run_metadata.checkpoint_manager.checkpoint_config\n return Trial(\n self.trainable_name,\n config=self.config,\n trial_id=None,\n experiment_path=self._legacy_orig_experiment_path,\n experiment_dir_name=self._legacy_orig_experiment_dir_name,\n evaluated_params=self.evaluated_params,\n experiment_tag=self.experiment_tag,\n placement_group_factory=placement_group_factory,\n stopping_criterion=self.stopping_criterion,\n sync_config=self.legacy_sync_config,\n checkpoint_config=checkpoint_config,\n export_formats=self.export_formats,\n restore_path=self.restore_path,\n trial_name_creator=self.trial_name_creator,\n trial_dirname_creator=self.trial_dirname_creator,\n log_to_file=self.log_to_file,\n max_failures=self.max_failures,\n storage=self.storage,\n )\n\n @Deprecated(\"Replaced by `init_local_path()`\")\n def init_logdir(self):\n # Deprecate: Raise in 2.5, Remove in 2.6\n self.init_local_path()\n\n def init_local_path(self):\n \"\"\"Init logdir.\"\"\"\n if not self.relative_logdir:\n self.relative_logdir = _create_unique_logdir_name(\n str(self.local_experiment_path), self._generate_dirname()\n )\n\n if _use_storage_context():\n # Populate the storage context with the trial dir name we just generated.\n assert self.storage\n self.storage.trial_dir_name = self.relative_logdir\n\n assert self.local_path\n logdir_path = Path(self.local_path)\n max_path_length = _get_max_path_length()\n if len(str(logdir_path)) >= max_path_length:\n logger.warning(\n f\"The path to the trial log directory is too long \"\n f\"(max length: {max_path_length}. \"\n f\"Consider using `trial_dirname_creator` to shorten the path. \"\n f\"Path: {logdir_path}\"\n )\n logdir_path.mkdir(parents=True, exist_ok=True)\n\n self.invalidate_json_state()\n\n def update_resources(self, resources: Union[dict, PlacementGroupFactory]):\n \"\"\"EXPERIMENTAL: Updates the resource requirements.\n\n Should only be called when the trial is not running.\n\n Raises:\n ValueError if trial status is running.\n \"\"\"\n if self.status is Trial.RUNNING:\n raise ValueError(\"Cannot update resources while Trial is running.\")\n\n placement_group_factory = resources\n if isinstance(resources, dict):\n placement_group_factory = resource_dict_to_pg_factory(resources)\n\n self.placement_group_factory = placement_group_factory\n\n self.invalidate_json_state()\n\n def set_ray_actor(self, ray_actor):\n self.temporary_state.ray_actor = ray_actor\n if ray_actor:\n # Do not block here, the result will be gotten when last_result\n # property is accessed\n self._default_result_or_future = ray_actor.get_auto_filled_metrics.remote(\n debug_metrics_only=True\n )\n if not _use_storage_context():\n self.run_metadata.checkpoint_manager.set_delete_fn(\n _CheckpointDeleter(str(self), ray_actor)\n )\n\n def set_location(self, location):\n \"\"\"Sets the location of the trial.\"\"\"\n self.temporary_state.location = location\n\n def set_status(self, status):\n \"\"\"Sets the status of the trial.\"\"\"\n self.status = status\n if status == Trial.RUNNING:\n if self.run_metadata.start_time is None:\n self.run_metadata.start_time = time.time()\n self.invalidate_json_state()\n\n def set_config(self, config):\n self.config = config\n self.invalidate_json_state()\n\n def set_experiment_tag(self, experiment_tag):\n self.experiment_tag = experiment_tag\n self.invalidate_json_state()\n\n @property\n def num_failures(self):\n return self.run_metadata.num_failures\n\n @property\n def num_failures_after_restore(self):\n return self.run_metadata.num_failures_after_restore\n\n @property\n def error_file(self):\n if not self.local_path or not self.run_metadata.error_filename:\n return None\n return os.path.join(self.local_path, self.run_metadata.error_filename)\n\n @property\n def pickled_error_file(self):\n if not self.local_path or not self.run_metadata.pickled_error_filename:\n return None\n return os.path.join(self.local_path, self.run_metadata.pickled_error_filename)\n\n def handle_error(self, exc: Optional[Union[TuneError, RayTaskError]] = None):\n if isinstance(exc, _TuneRestoreError):\n exc = exc.exc\n if self.temporary_state.num_restore_failures >= int(\n os.environ.get(\"TUNE_RESTORE_RETRY_NUM\", 0)\n ):\n # Restore was unsuccessful, try again without checkpoint.\n self.clear_checkpoint()\n self.run_metadata.num_failures += 1\n else:\n self.temporary_state.num_restore_failures += 1\n else:\n self.run_metadata.num_failures += 1\n\n if self.local_path:\n self.run_metadata.error_filename = EXPR_ERROR_FILE\n if isinstance(exc, RayTaskError):\n # Piping through the actual error to result grid.\n self.run_metadata.pickled_error_filename = EXPR_ERROR_PICKLE_FILE\n with open(self.pickled_error_file, \"wb\") as f:\n cloudpickle.dump(exc, f)\n with open(self.error_file, \"a+\") as f:\n f.write(\n \"Failure # {} (occurred at {})\\n\".format(\n self.run_metadata.num_failures, date_str()\n )\n )\n f.write(str(exc) + \"\\n\")\n self.run_metadata.invalidate_cache()\n\n def should_stop(self, result):\n \"\"\"Whether the given result meets this trial's stopping criteria.\"\"\"\n if result.get(DONE):\n return True\n\n for criteria, stop_value in self.stopping_criterion.items():\n if criteria not in result:\n raise TuneError(\n \"Stopping criteria {} not provided in result dict. Keys \"\n \"are {}.\".format(criteria, list(result.keys()))\n )\n elif isinstance(criteria, dict):\n raise ValueError(\n \"Stopping criteria is now flattened by default. \"\n \"Use forward slashes to nest values `key1/key2/key3`.\"\n )\n elif result[criteria] >= stop_value:\n return True\n return False\n\n def should_checkpoint(self):\n \"\"\"Whether this trial is due for checkpointing.\"\"\"\n result = self.last_result or {}\n if result.get(DONE) and self.checkpoint_at_end:\n return True\n return (\n self.checkpoint_freq\n and result.get(TRAINING_ITERATION, 0) % self.checkpoint_freq == 0\n )\n\n def has_checkpoint(self):\n if _use_storage_context():\n return self.checkpoint is not None\n return self.checkpoint.dir_or_data is not None\n\n def clear_checkpoint(self):\n if _use_storage_context():\n if self.latest_checkpoint_result:\n self.latest_checkpoint_result.checkpoint = None\n self.temporary_state.restoring_from = None\n self.run_metadata.invalidate_cache()\n return\n\n self.checkpoint.dir_or_data = None\n self.temporary_state.restoring_from = None\n self.run_metadata.invalidate_cache()\n\n def on_checkpoint(self, checkpoint: Union[_TrackedCheckpoint, _TrainingResult]):\n \"\"\"Hook for handling checkpoints taken by the Trainable.\n\n Args:\n checkpoint: Checkpoint taken.\n \"\"\"\n if _use_storage_context():\n checkpoint_result = checkpoint\n assert isinstance(checkpoint_result, _TrainingResult)\n self.run_metadata.checkpoint_manager.register_checkpoint(checkpoint_result)\n # Increment the checkpoint index to keep the checkpoint index in sync.\n # This index will get restored when the trial is restored and will\n # be passed to the Trainable as the starting checkpoint index.\n self.storage.current_checkpoint_index += 1\n else:\n self.run_metadata.checkpoint_manager.on_checkpoint(checkpoint)\n self.invalidate_json_state()\n self.run_metadata.invalidate_cache()\n\n def on_restore(self):\n \"\"\"Handles restoration completion.\"\"\"\n assert self.is_restoring\n\n if _use_storage_context():\n assert isinstance(self.temporary_state.restoring_from, _TrainingResult)\n\n self.run_metadata.last_result = self.temporary_state.restoring_from.metrics\n self.run_metadata.last_result.setdefault(\"config\", self.config)\n self.temporary_state.restoring_from = None\n self.temporary_state.num_restore_failures = 0\n\n def should_recover(self):\n \"\"\"Returns whether the trial qualifies for retrying.\n\n This is if the trial has not failed more than max_failures. Note this\n may return true even when there is no checkpoint, either because\n `self.checkpoint_freq` is `0` or because the trial failed before\n a checkpoint has been made.\n \"\"\"\n return (\n self.run_metadata.num_failures < self.max_failures\n or self.max_failures < 0\n or (\n self.run_metadata.num_failures == self.max_failures\n and self.temporary_state.num_restore_failures\n < int(os.environ.get(\"TUNE_RESTORE_RETRY_NUM\", 0))\n )\n )\n\n def update_last_result(self, result):\n if self.experiment_tag:\n result.update(experiment_tag=self.experiment_tag)\n\n self.set_location(_Location(result.get(NODE_IP), result.get(PID)))\n self.run_metadata.last_result = result\n self.run_metadata.last_result_time = time.time()\n\n metric_result = self.last_result.copy()\n for remove_metric in DEBUG_METRICS:\n metric_result.pop(remove_metric, None)\n\n for metric, value in flatten_dict(metric_result).items():\n if isinstance(value, Number):\n self.run_metadata.update_metric(\n metric, value, step=result.get(\"training_iteration\")\n )\n\n def get_trainable_cls(self):\n if self.stub:\n return None\n return get_trainable_cls(self.trainable_name)\n\n def get_trial_checkpoints(self) -> List[_TrackedCheckpoint]:\n return self.run_metadata.checkpoint_manager.best_checkpoints()\n\n def is_finished(self):\n return self.status in [Trial.ERROR, Trial.TERMINATED]\n\n @property\n def is_restoring(self):\n return self.temporary_state.restoring_from is not None\n\n @property\n def is_saving(self):\n return self.temporary_state.saving_to is not None\n\n def __repr__(self):\n return self._trainable_name(include_trial_id=True)\n\n def __str__(self):\n return self._trainable_name(include_trial_id=True)\n\n def _trainable_name(self, include_trial_id=False):\n \"\"\"Combines ``env`` with ``trainable_name`` and ``trial_id``.\n\n Can be overridden with a custom string creator.\n \"\"\"\n if self.custom_trial_name:\n return self.custom_trial_name\n\n if \"env\" in self.config:\n env = self.config[\"env\"]\n if isinstance(env, type):\n env = env.__name__\n identifier = \"{}_{}\".format(self.trainable_name, env)\n else:\n identifier = self.trainable_name\n if include_trial_id:\n identifier += \"_\" + self.trial_id\n return identifier.replace(\"/\", \"_\")\n\n def _generate_dirname(self):\n if self.custom_dirname:\n generated_dirname = self.custom_dirname\n else:\n MAX_LEN_IDENTIFIER = int(os.environ.get(\"TUNE_MAX_LEN_IDENTIFIER\", \"130\"))\n generated_dirname = f\"{str(self)}_{self.experiment_tag}\"\n generated_dirname = generated_dirname[:MAX_LEN_IDENTIFIER]\n generated_dirname += f\"_{date_str()}\"\n # This is the file path used by rsync. ['/', '(', ')'] are not allowed.\n return re.sub(\"[/()]\", \"_\", generated_dirname)\n\n def invalidate_json_state(self):\n self._state_json = None\n\n def get_json_state(self) -> Tuple[str, str]:\n if self._state_json is None:\n state = self.__getstate__()\n state.pop(\"run_metadata\", None)\n self._state_json = json.dumps(state, indent=2, cls=TuneFunctionEncoder)\n\n runtime_metadata_json = self.run_metadata.get_json_state()\n\n return self._state_json, runtime_metadata_json\n\n @classmethod\n def from_json_state(cls, json_state: str, stub: bool = False) -> \"Trial\":\n state = json.loads(json_state, cls=TuneFunctionDecoder)\n\n new_trial = Trial(\n state[\"trainable_name\"],\n stub=stub,\n _setup_default_resource=False,\n )\n\n new_trial.__setstate__(state)\n\n return new_trial\n\n def restore_run_metadata(self, run_metadata: str):\n self.run_metadata = _TrainingRunMetadata.from_json_state(run_metadata)\n\n @classmethod\n def from_directory(\n cls, path: Union[str, os.PathLike], stub: bool = False\n ) -> \"Trial\":\n metadata_path = os.path.join(path, TRIAL_STATE_FILENAME)\n if not os.path.exists(metadata_path):\n raise FileNotFoundError(\n f\"Can't restore trial from path: File `{metadata_path}` not found.\"\n )\n\n json_state = Path(metadata_path).read_text()\n return cls.from_json_state(json_state, stub=stub)\n\n def __getstate__(self):\n \"\"\"Memento generator for Trial.\n\n Sets RUNNING trials to PENDING.\n Note this can only occur if the trial holds a PERSISTENT checkpoint.\n \"\"\"\n state = self.__dict__.copy()\n\n for key in self._nonjson_fields:\n state[key] = binary_to_hex(cloudpickle.dumps(state.get(key)))\n\n state.pop(\"temporary_state\", None)\n\n state[\"_state_json\"] = None\n state[\"_default_result_or_future\"] = None\n\n return state\n\n def __setstate__(self, state):\n if state[\"status\"] == Trial.RUNNING:\n state[\"status\"] = Trial.PENDING\n for key in self._nonjson_fields:\n if key in state:\n state[key] = cloudpickle.loads(hex_to_binary(state[key]))\n\n # Ensure that stub doesn't get overriden\n stub = state.pop(\"stub\", True)\n self.__dict__.update(state)\n self.stub = stub or getattr(self, \"stub\", False)\n\n if not self.stub:\n validate_trainable(self.trainable_name)\n\n self.temporary_state = _TemporaryTrialState()\n\n assert self.placement_group_factory\n","sub_path":"python/ray/tune/experiment/trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":47209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"316921468","text":"def format_comments(fstream):\n lines = fstream.readlines()\n for i, line in enumerate(lines):\n if line.endswith('$$\\n'):\n continue\n elif line.count('//'):\n lines[i] = ''.join([lines[i][:-1], ' $$', lines[i][-1]])\n fstream.seek(0)\n for line in lines:\n fstream.write(line)\n","sub_path":"tc/format_comments.py","file_name":"format_comments.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"223722839","text":"from rest_framework import serializers\n\nfrom django.conf import settings as app_settings\nfrom pymongo import MongoClient\nfrom .models import Table\nfrom .utils import connect_to_mongo\n\n\nclass TableSerializer(serializers.HyperlinkedModelSerializer):\n table_uuid = serializers.ReadOnlyField()\n owner = serializers.ReadOnlyField()\n url = serializers.HyperlinkedIdentityField(\n view_name='table-detail',\n lookup_field='table_uuid'\n )\n data = serializers.SerializerMethodField(read_only=True)\n\n class Meta:\n model = Table\n fields = '__all__'\n\n def get_data(self, obj):\n mongo_client = connect_to_mongo()\n connection = mongo_client[obj.name.replace(' ', '_')]\n data = connection.find_one({'table_uuid': str(obj.table_uuid)})\n # temporarily delete _id property\n if data is not None:\n del data['_id']\n return data\n","sub_path":"tables/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"503507906","text":"from pandas import read_csv\nfrom numpy import float64\nimport json\nfrom copy import deepcopy\n\nclass FrequencyTable:\n \"\"\"Represents a frequency table (frequencies of markers vs. alleles). This\n class contains only the metadata associated to the frequency table by default. The\n actual frequency data can be loaded if desired.\n\n Frequency data should follow the following format:\n\n +----------+-----+-----+\n | | A | B |\n +==========+=====+=====+\n | Allele 1 | 0.2 | 0.3 |\n +----------+-----+-----+\n | Allele 2 | 0.3 | 0.2 |\n +----------+-----+-----+\n | ... | ... | ... |\n +----------+-----+-----+\n\n To load a CSV with frequency data for which there is no metadata::\n\n f = FrequencyData('path/to/csv_without_extension', True, total_sample_size=n)\n\n Metadata will be calculated from the metadata arguments you provide and\n from the csv file itself. To persist this metadata to a JSON file::\n\n # saves metadata to filename.json\n f.persist_to()\n\n The following metadata options are supported:\n\n Args:\n name(str): the name of the file sans extension where frequency data is stored\n load_data(str): whether to load actual frequency data or not. Defaults to False. Data may be loaded later with load_data.\n title(str): a descriptive yet short title for the frequency data\n abstract(str): a longer description detailing the source and other characteristics of the data\n total_sample_size(int): The number of people sampled to obtain the relative frequencies of each allele for all the markers. Frequency Table does not support different sample sizes for different markers.\n male_sample_size(int): The number of males sampled to obtain relative frequencies.\n female_sample_size(int): The number of females sampled to obtain relative frequencies.\n \"\"\"\n\n default_metadata = {\n 'name': '',\n 'abstract': '',\n 'total_sample_size': 0,\n 'male_sample_size': 0,\n 'female_sample_size': 0,\n 'frequencies_add_up_to_one': False,\n 'markers': [],\n }\n\n def __init__(self, name, load_data=False, **metadata):\n self.filename = name + '.csv'\n self.file_metadata_extracted = False\n\n\n self._update_metadata(metadata)\n self.metadata['name'] = name\n\n if load_data:\n self.load_data()\n if not self.file_metadata_extracted:\n self.extract_metadata_from_data()\n\n def _update_metadata(self, metadata):\n \"\"\"Replaces default values in the metadata dictionary with the ones\n provided by the user. Additionally, it computes total sample size as\n the sum of male and females sample sizes if provided.\"\"\"\n self.metadata = deepcopy(self.default_metadata)\n for key in self.default_metadata:\n if key in metadata:\n self.metadata[key] = metadata[key]\n\n # procesing for special metadata keys\n if self.metadata['male_sample_size'] > 0 or self.metadata['female_sample_size'] > 0:\n self.metadata['total_sample_size'] = self.metadata['male_sample_size'] + self.metadata['female_sample_size']\n\n if self.metadata['markers']:\n self.file_metadata_extracted = True\n\n def load_data(self, filename=False):\n \"\"\"Loads frequency data from the file asociated with the FrequencyTable\n or from the filename given.\n\n Args:\n filename(str): where to load frequency data from. Defaults to the filename provided on the creation of the object.\"\"\"\n if not filename:\n filename = self.filename\n self.data = read_csv(filename, index_col = 0)\n\n def save_data(self, filename=False):\n \"\"\"Saves frequency data to the CSV file associated with the object or\n to the filename given.\n\n Args:\n filename(str): where to save frequency data to. Defaults to the filename provided on the creation of the object.\"\"\"\n if not filename:\n filename = self.filename\n self.data.to_csv(self.filename)\n\n def extract_metadata_from_data(self):\n \"\"\"Extracts metadata from the frequency file and stores in this\n object. Metadata extracted from the frequency file includes the list of\n analysed markers and wether all allele frequencies add up to one for\n each marker.\"\"\"\n self.metadata['markers'] = list(self.data.columns)\n\n self.metadata['frequencies_add_up_to_one'] = True\n for s in self.data.sum():\n if s != 1.0:\n self.metadata['frequencies_add_up_to_one'] = False\n break\n\n self.file_metadata_extracted = True\n\n def combine(self, other):\n \"\"\"Combines this FrequencyTable with another one. Returns a new\n frequency table with only the common markers. The frequencies in the\n new table are the sum of the frequencies of each combined table,\n weighed by the sample size of each table. Metadata not directly related\n to the frequencies is combined by concatenation.\"\"\"\n if not hasattr(self, 'data'):\n self.load_data()\n\n if not hasattr(other, 'data'):\n other.load_data()\n\n # merge frequency data\n common_markers = self.data.columns & other.data.columns\n new = FrequencyTable(self.metadata['name'] + '+' + other.metadata['name'], load_data=False)\n new.data = (self.data.loc[:, common_markers] * self.metadata['total_sample_size'] \\\n + other.data.loc[:, common_markers] * other.metadata['total_sample_size']).dropna(how=\"all\") \\\n / (new.metadata['total_sample_size'] + other.metadata['total_sample_size'])\n\n # update metadata\n new.extract_metadata_from_data()\n for key in ['total_sample_size', 'male_sample_size', 'female_sample_size']:\n new.metadata[key] = self.metadata[key] + other.metadata[key]\n\n new.metadata['abstract'] = f\"Population data combined from {new.metadata['name']}. Abstracts for each of the sources follow:\" \\\n + \"\\n\" + self.metadata['abstract'] \\\n + \"\\n\" + other.metadata['abstract']\n return new\n\n def to_json(self):\n \"\"\"Returns a JSON string of the metadata of this object.\"\"\"\n return json.dumps(self.metadata)\n\n @classmethod\n def load_from(cls, filename):\n \"\"\"Loads metadata from the given filename. Metadata shall be stored as\n a JSON object akin to the one produced by persist_to().\"\"\"\n with open(filename, 'r') as f:\n read_data = f.read()\n\n metadata = json.loads(read_data)\n print(metadata)\n return cls(**metadata)\n\n def persist_to(self, filename):\n \"\"\"Saves sufficient metadata to rebuild an object (provided the\n frequency file is available) as a json object in the given filename.\"\"\"\n with open(filename, 'w') as f:\n f.write(self.to_json())\n\n def __repr__(self):\n return f\"Frequency table in file {self.filename}\"\n\n def __add__(self, other):\n \"\"\"this + other is an alias for this.combine(other).\"\"\"\n if isinstance(other, FrequencyTable):\n return self.combine(other)\n else:\n return NotImplemented\n","sub_path":"ffreqs/frequency_table.py","file_name":"frequency_table.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203794977","text":"from injector import inject\n\nfrom domain.connection.services.ConnectionSecretService import ConnectionSecretService\nfrom domain.connection.services.ConnectionServerService import ConnectionServerService\nfrom infrastructor.connection.queue.connectors.KafkaConnector import KafkaConnector\nfrom infrastructor.connection.queue.QueueContext import QueueContext\nfrom infrastructor.connection.queue.connectors.QueueConnector import QueueConnector\nfrom infrastructor.dependency.scopes import IScoped\nfrom infrastructor.logging.SqlLogger import SqlLogger\nfrom models.dao.connection import Connection\nfrom models.enums import ConnectionTypes, ConnectorTypes\n\n\nclass QueueProvider(IScoped):\n @inject\n def __init__(self,\n sql_logger: SqlLogger,\n connection_secret_service: ConnectionSecretService,\n connection_server_service: ConnectionServerService,\n ):\n self.connection_server_service = connection_server_service\n self.connection_secret_service = connection_secret_service\n self.sql_logger = sql_logger\n\n def get_context(self, connection: Connection) -> QueueContext:\n \"\"\"\n Creating Connection\n \"\"\"\n if connection.ConnectionType.Name == ConnectionTypes.Queue.name:\n connection_basic_authentication = self.operation_cache_service.get_connection_basic_authentication_by_connection_id(\n connection_id=connection.Id)\n connection_servers = self.operation_cache_service.get_connection_servers_by_connection_id(\n connection_id=connection.Id)\n connector: QueueConnector = None\n if connection.Queue.ConnectorType.Name == ConnectorTypes.Kafka.name:\n servers = []\n for connection_server in connection_servers:\n server = f\"{connection_server.Host}:{connection_server.Port}\"\n servers.append(server)\n auth = None\n if ((connection.Queue.Protocol is not None and connection.Queue.Protocol != '') and (\n connection.Queue.Mechanism is not None and connection.Queue.Mechanism != '') and (\n connection_basic_authentication.User is not None and connection_basic_authentication.User != '') and (\n connection_basic_authentication.Password is not None and connection_basic_authentication.Password != '')):\n auth = {\n 'security_protocol': connection.Queue.Protocol,\n 'sasl_mechanism': connection.Queue.Mechanism,\n 'sasl_plain_username': connection_basic_authentication.User,\n 'sasl_plain_password': connection_basic_authentication.Password\n }\n connector = KafkaConnector(servers=servers, auth=auth)\n if connector is not None:\n queue_context: QueueContext = QueueContext(connector=connector)\n return queue_context\n else:\n raise Exception(f\"{connection.Queue.ConnectorType.Name} connector type not supported\")\n\n else:\n raise Exception(f\"{connection.ConnectionType.Name} connection type not supported\")\n","sub_path":"src/process/infrastructor/connection/queue/QueueProvider.py","file_name":"QueueProvider.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"153094969","text":"# -*- coding:utf-8 -*-\n\n\n#\n# Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The integer B denotes that from any place (suppose the index is i) in the array A, you can jump to any one of the place in the array A indexed i+1, i+2, …, i+B if this place can be jumped to. Also, if you step on the index i, you have to pay Ai coins. If Ai is -1, it means you can’t jump to the place indexed i in the array.\r\n#\n#\n#\n# Now, you start from the place indexed 1 in the array A, and your aim is to reach the place indexed N using the minimum coins. You need to return the path of indexes (starting from 1 to N) in the array you should take to get to the place indexed N using minimum coins.\r\n#\n#\n#\n# If there are multiple paths with the same cost, return the lexicographically smallest such path.\r\n#\n#\n# If it's not possible to reach the place indexed N then you need to return an empty array.\r\n#\n#\n# Example 1:\r\n#\n# Input: [1,2,4,-1,2], 2\r\n# Output: [1,3,5]\r\n#\n#\n#\n# Example 2:\r\n#\n# Input: [1,2,4,-1,2], 1\r\n# Output: []\r\n#\n#\n#\n# Note:\r\n#\n# Path Pa1, Pa2, ..., Pan is lexicographically smaller than Pb1, Pb2, ..., Pbm, if and only if at the first i where Pai and Pbi differ, Pai < Pbi; when no such i exists, then n < m.\r\n# A1 >= 0. A2, ..., AN (if exist) will in the range of [-1, 100]. \r\n# Length of A is in the range of [1, 1000].\r\n# B is in the range of [1, 100].\r\n#\n#\n\n\nclass Solution(object):\n def cheapestJump(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: int\n :rtype: List[int]\n \"\"\"\n n = len(A)\n if A[n - 1] < 0: return []\n if n == 1:\n if A[0] < 0: return []\n else: return [1]\n f = [float('inf') for _ in range(n)]\n _next = [-1 for _ in range(n)]\n f[n - 1] = A[n - 1]\n for i in range(n - 1, -1, -1):\n if A[i] == -1: continue\n for k in range(1, B + 1):\n cur = i + k\n if cur >= n: continue\n if f[cur] < f[i]:\n f[i] = f[cur]\n _next[i] = cur\n f[i] += A[i]\n print(f)\n print(_next)\n res = []\n cur = 0\n if f[0] == float('inf'): return []\n while cur != -1:\n res.append(cur + 1)\n cur = _next[cur]\n return res\n \n","sub_path":"656-coin-path/coin-path.py","file_name":"coin-path.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"296463936","text":"from django.db import models\n\nfrom core.models import Authored, Titled\nfrom core.decorators import non_editable_fields\n\nfriendship = {\n 1: 'Первый друг',\n 10: 'Дружелюбный',\n 50: 'Братишка',\n 100: 'Филантроп',\n 500: 'Другоман',\n 1000: 'Другофил',\n}\n\nlikes = {\n 1: 'Первый лайк',\n 10: 'Интересный пост!',\n 50: 'Популярный',\n 100: 'Соточка',\n 500: 'Создатель мемов',\n 1000: 'Лайкодрочер',\n}\n\ncomments = {\n 1: 'Первый коммент',\n 10: 'Интересный пост!',\n 50: 'Интересное обсуждение!',\n 100: 'Срач',\n 500: 'Мегасрач',\n 1000: 'Разжигатель',\n}\n\n\n@non_editable_fields('author_id')\nclass Achievement(Authored, Titled):\n content = models.TextField(verbose_name='Содержание')\n\n class Meta:\n verbose_name = 'Достижение'\n verbose_name_plural = 'Достижения'\n unique_together = (('author', 'title'),)\n\n def __str__(self):\n return '{0}: достижение {1}'.format(self.author, self.title)\n","sub_path":"achievements/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584413906","text":"# This is a Day 2 Project!\nprint(\"Welcome to the tip calculator.\")\n\n#Total bill\ntotal_bill = input(\"What is the total bill?: $\")\nint_total_bill = float(total_bill)\n\n#Tip Percentage\ntip_percentage = input(\"What percentage tip would you like to give? \")\nint_tip_percentage = int(tip_percentage)\n\n#Total tip\ntotal_tip = int_total_bill * (int_tip_percentage / 100)\n\n#Total After Tip\ntotal_after_tip = int_total_bill + total_tip\n\n#Bill Split\nbill_split = input(\"How many people to split the bill? \")\nint_bill_split = int(bill_split)\n\n#Each Person Payment\neach_payment = total_after_tip / int_bill_split\nround_each_payment = \"{:.2f}\".format(each_payment)\n# round_each_payment = round(each_payment, 2)\n\n#Result\nend_result = f\"Each person should pay : ${round_each_payment}\"\nprint(end_result)","sub_path":"Tip Calculator - Day 2.py","file_name":"Tip Calculator - Day 2.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248647258","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[250]:\n\n\nimport csv\nimport requests\nimport json\n\n\n# In[251]:\n\n\nheaders = {\n\t'Accept': 'application/json, text/javascript, */*; q=0.01',\n\t'Accept-Encoding': 'gzip, deflate',\n\t'Accept-Language': 'zh-CN,zh;q=0.9',\n\t'Connection': 'keep-alive',\n\t'Content-Length': '44',\n\t'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n\t'Cookie': 'JSE=USd5H4MJMq; JSESSIONID=575434700FFE32E7E8BDCCF8F040A1AE',\n\t'Host': 'www.noi.cn',\n\t'Origin': 'http://www.noi.cn',\n\t'Referer': 'http://www.noi.cn/awardsearch.html',\n\t'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',\n\t'X-Requested-With': 'XMLHttpRequest'}\n\nurl = 'http://www.noi.cn/awards.AwardSearch.dt'\n\ndef data(name) : \n\treturn{\n\t'cmd': 'search',\n\t'key': 'name',\n\t'value': name}\n\n\nf = csv.reader(open('raw_data.csv'))\nout_file = open('result.csv', 'w')\nout = csv.writer(out_file)\n\n\n# In[252]:\n\n\nmatch = {\n '高一' : 1,\n '高二' : 2,\n '高三' : 3,\n '初三' : 0,\n '初二' : -1,\n '初一' : -2,\n '初中' : -10,\n '小学' : -10,\n\t'初四' : -10\n}\n\n\n# In[253]:\n\n\ndef get(str):\n a = \"\"\n for i in range(len(str)):\n if(str[i] >= '0' and str[i] <= '9'):\n a += str[i]\n return int(a)\n\n\n# In[254]:\n\n\ndef get_awards(name, grad_year):\n current_year = grad_year\n r = requests.post(url, headers = headers, data = data(name))\n a = json.loads(r.text)\n lst = []\n for i in a:\n qaq = a[i]\n if(isinstance(qaq, str)):\n break\n if (\"复赛提高组\" in qaq['compname']) or ((\"NOI20\" in qaq['compname']) and (not(\"冬令营\" in qaq['compname']))):\n name = qaq['compname']\n year = get(name)\n bias = 0\n if not (\"NOIP\" in qaq['compname']):\n bias += 1\n if(4 - bias - current_year + year != match[qaq['grade']]):\n continue\n if(\"复赛提高组\" in qaq['compname'] and qaq['award'] != '一等奖'):\n continue\n lst.append(qaq['compname'] + qaq['award'])\n return lst\n\n\n# In[255]:\n\n\nfor row in f:\n this_name = row[1]\n award = get_awards(this_name, 2016)\n if award:\n print([row[0], row[1], row[3], award])\n out.writerow([row[0], row[1], row[3], award])\n\n","sub_path":"major.py","file_name":"major.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"242799067","text":"#!/usr/local/bin/python3\n\nfrom bs4 import BeautifulSoup\nimport re\nimport urllib2\nimport requests\nfrom pprint import pprint\nimport os,sys\nimport html2markdown\n\ninvalid_tags = ['div', 'span']\n\nbaseUrl = \"https://sites.google.com\"\n\nurl = \"site/mytechnicalcollection/os\"\npage = requests.get(os.path.join(baseUrl,url))\n\nsoup = BeautifulSoup(page.content,features=\"lxml\")\nsubpages = soup.find('div',{\"class\":\"sites-subpages\"}).find_all('span')\n\ndel subpages[0]\n\nfor page in subpages:\n topicUrl = page.a['href']\n url = \"https://sites.google.com\"+topicUrl\n subpage = requests.get(url)\n soup = BeautifulSoup(subpage.content,features=\"lxml\")\n \n content = soup.find(attrs={\"role\": \"main\"}).table\n\n\n for tag in content.findAll(True):\n for attr in [attr for attr in tag.attrs]:\n print(attr)\n if not attr in ['src']:\n del tag[attr]\n\n for row in content.find_all(\"tr\"):\n for td in row.find_all(\"td\"):\n for tag in invalid_tags: \n for match in td.findAll(tag):\n match.replaceWithChildren()\n # for attribute in [\"class\", \"id\", \"name\", \"style\"]:\n # del td[attribute]\n\n\n print(html2markdown.convert(str(content)))\n sys.exit()\n \n\n #\n #print(content)\n\n\n","sub_path":"Trunk/2019_Spring/Resources/OS_Topics/grab_data.py","file_name":"grab_data.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419747621","text":"from Cell import Cell\nimport numpy as np\nimport random\nimport math\nimport fractions\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom decimal import *\n\nclass Tumor_cell(Cell):\n dr_type = 0\n @classmethod\n def receive_value(cls, AVERAGE, DISPERSION, AROUND, WEIGHT1, WEIGHT2, MTRATE, DRUGTIMES, EFFECT):\n Cell.AVERAGE = AVERAGE\n Cell.DISPERSION = DISPERSION\n Cell.AROUND = AROUND\n Cell.WEIGHT1 = WEIGHT1\n Cell.WEIGHT2 = WEIGHT2\n Cell.MTRATE = MTRATE\n Cell.K1 = Cell.AVERAGE * 8 * Cell.AROUND * (Cell.AROUND + 1)\n Cell.K2 = Cell.AVERAGE * 8 * Cell.AROUND * (Cell.AROUND + 1) * (Cell.WEIGHT1 + 1)\n Cell.KM = (2 * Cell.AROUND + 1) ** 2 - 1\n Cell.EFFECT = EFFECT\n Cell.drtime_list = DRUGTIMES.split(\",\")\n Cell.resicount = 0\n Cell.DR_STRTIME = 0\n Cell.DR_DURATION = int(Cell.drtime_list[0])\n Cell.DR_INTERVAL = int(Cell.drtime_list[1])\n\n def __init__(self, i, j):\n super().__init__(i, j)\n self.mutation_id = 1\n self.resistflag = 0\n self.enemynum = 0\n self.type = 1\n self.drdeath = 0\n self.driver_mutation = 0\n self.driverflag = 0\n self.driver_type = 0\n\n\n @classmethod\n def set_first_cell(cls, field, on, celllist):\n first_cell = Tumor_cell(on, on)\n first_cell.id = 0\n first_cell.type = 1\n first_cell.waittime = 1\n first_cell.count = 0\n first_cell.proliferation = 0\n celllist.append(first_cell)\n field[first_cell.i, first_cell.j] = first_cell.id\n\n def prolife(self, field, celllist, timedic, driver_list):\n ni = self.i + Cell.mi\n nj = self.j + Cell.mj\n cell_new = Tumor_cell(ni, nj)\n cell_new.id = len(celllist)\n cell_new.mutation_id = self.mutation_id * 2 + 1\n self.mutation_id = self.mutation_id * 2\n timedic[self.mutation_id] = self.count\n timedic[cell_new.mutation_id] = self.count\n self.count = 0\n self.proliferation = 0\n cell_new.driver_mutation = self.driver_mutation\n cell_new.type = self.type\n cell_new.driver_type = self.driver_type\n\n if self.driver_mutation == 0 and self.type == 1:\n self.driverflag = np.random.choice([1, 0], p=[Cell.MTRATE, 1 - Cell.MTRATE])\n if self.driverflag == 1:\n self.type = 2\n self.driver_mutation = 1\n driver_list.append(self.mutation_id)\n Tumor_cell.dr_type += 1\n self.driver_type = Tumor_cell.dr_type\n self.driverflag = 0\n else:\n pass\n\n if cell_new.driver_mutation == 0 and cell_new.type == 1:\n cell_new.driverflag = np.random.choice([1, 0], p=[Cell.MTRATE, 1 - Cell.MTRATE])\n if cell_new.driverflag == 1:\n cell_new.type = 2\n cell_new.driver_mutation = 1\n driver_list.append(cell_new.mutation_id)\n Tumor_cell.dr_type += 1\n cell_new.driver_type = Tumor_cell.dr_type\n cell_new.driverflag = 0\n else:\n pass\n\n cell_new.move(field, celllist)\n celllist.append(cell_new)\n\n def prolife_simple(self, field, celllist):\n ni = self.i + Cell.mi\n nj = self.j + Cell.mj\n cell_new = Tumor_cell(ni, nj)\n cell_new.id = len(celllist)\n self.count += 1\n cell_new.mutation_id = self.mutation_id * 2 + 1\n self.mutation_id = self.mutation_id * 2\n cell_new.count = self.count\n self.proliferation = 0\n cell_new.type = self.type\n\n if self.type == 1:\n self.resistflag = np.random.choice([1, 0], p=[Cell.MTRATE, 1 - Cell.MTRATE])\n if self.resistflag == 1:\n Cell.resicount += 1\n self.type = 2\n self.resistflag = 0\n\n cell_new.move(field, celllist)\n celllist.append(cell_new)\n\n @classmethod\n def radial_prolife_up(cls, field, on, func, celllist, timedic, driver_list):\n if celllist[field[on, on]].proliferation == 1:\n getattr(celllist[field[on, on]], func)(field)\n celllist[field[on, on]].prolife(field, celllist, timedic, driver_list)\n for r in range(1, on):\n a = field[on - r, on - r : on + r + 1].flatten()\n a = list(a[a != -1])\n for i in a:\n if celllist[i].proliferation == 1:\n getattr(celllist[i], func)(field)\n celllist[i].prolife(field, celllist, timedic, driver_list)\n b = field[on - r + 1 : on + r + 1, on + r].flatten()\n b = list(b[b != -1])\n for i in b:\n if celllist[i].proliferation == 1:\n getattr(celllist[i], func)(field)\n celllist[i].prolife(field, celllist, timedic, driver_list)\n c = field[on + r, on + r - 1: on - r -1 : -1].flatten()\n c = list(c[c != -1])\n for i in c:\n if celllist[i].proliferation == 1:\n getattr(celllist[i], func)(field)\n celllist[i].prolife(field, celllist, timedic, driver_list)\n d = field[on + r - 1 : on - r : -1, on - r].flatten()\n d = list(d[d != -1])\n for i in d:\n if celllist[i].proliferation == 1:\n getattr(celllist[i], func)(field)\n celllist[i].prolife(field, celllist, timedic, driver_list)\n\n def count_around(self, heatmap):\n self.num = 0\n self.enemynum = 0\n if self.dead == 0:\n arheatmap = heatmap[self.i - Cell.AROUND:self.i + Cell.AROUND + 1, self.j - Cell.AROUND:self.j + Cell.AROUND + 1].flatten()\n nozeroheat = arheatmap[arheatmap != 0]\n self.num = -1 + len(nozeroheat[nozeroheat == self.type])\n self.enemynum = len(nozeroheat[nozeroheat != self.type])\n\n def mortal1(self, field):\n if self.enemynum <= Cell.K1 and self.dead == 0:\n nE = (self.num + self.enemynum) / Cell.K1\n nE = round(nE, 3)\n self.deathflag = np.random.choice([0, 1], p=[1 - nE, nE])\n if self.deathflag == 1:\n self.dead = 1\n field[self.i, self.j] = -1\n self.deathflag = 0\n else:\n pass\n\n def mortal2(self, field):\n if self.dead == 0:\n if self.type == 1:\n nE = (self.num + self.enemynum * Cell.WEIGHT2) / Cell.K1\n nE = round(nE, 3)\n if self.type == 2:\n nE = (self.num + self.enemynum * Cell.WEIGHT1) / Cell.K1\n nE = round(nE, 3)\n self.deathflag = np.random.choice([0, 1], p=[1 - nE, nE])\n if self.deathflag == 1:\n self.dead = 1\n field[self.i, self.j] = -1\n self.deathflag = 0\n else:\n pass\n\n def drugged(self, t):\n if len(Cell.drtime_list) != 0 and self.dead == 0:\n if t >= int(Cell.drtime_list[0]) and t < int(Cell.drtime_list[1]):\n if self.type == 1:\n dens = 1 - (self.num + self.enemynum) / Cell.KM\n self.drdeath = dens * Cell.EFFECT\n if t == int(Cell.drtime_list[1]):\n if self.type == 1:\n self.drdeath = 0\n\n @classmethod\n def prepare_drug(cls, t):\n Cell.DR_STRTIME = t\n\n def drugged_infinity(self, t):\n if t >= Cell.DR_STRTIME and t < Cell.DR_STRTIME + Cell.DR_DURATION:\n if self.type == 1:\n dens = 1 - (self.num + self.enemynum) / Cell.KM\n self.drdeath = dens * Cell.EFFECT\n if t == Cell.DR_STRTIME + Cell.DR_DURATION:\n if self.type == 1:\n self.drdeath = 0\n\n def drugged_infinity_continued(self):\n if self.type == 1:\n dens = 1 - (self.num + self.enemynum) / Cell.KM\n self.drdeath = dens * Cell.EFFECT\n\n @classmethod\n def drtime_adjust(cls, t):\n if t == Cell.DR_STRTIME + Cell.DR_DURATION:\n Cell.DR_STRTIME += Cell.DR_INTERVAL + Cell.DR_DURATION\n\n @classmethod\n def drtime_list_adjust(cls, t):\n if len(Cell.drtime_list) != 0:\n if t == int(Cell.drtime_list[1]):\n del Cell.drtime_list[0:2]\n\n def mortal1_drug(self, field):\n if self.dead == 0:\n nE = (self.num + self.enemynum) / Cell.K1\n nE = round(nE, 3)\n if self.type == 1:\n nE += self.drdeath\n if nE >= 1:\n nE = 1\n self.deathflag = np.random.choice([0, 1], p=[1 - nE, nE])\n if self.deathflag == 1:\n self.dead = 1\n field[self.i, self.j] = -1\n self.deathflag = 0\n else:\n pass\n\n def mortal2_drug(self, field):\n if self.dead == 0:\n if self.type == 1:\n nE = (self.num + self.enemynum * Cell.WEIGHT2) / Cell.K1 + self.drdeath\n nE = round(nE, 3)\n if nE >= 1:\n nE = 1\n if self.type == 2:\n nE = (self.num + self.enemynum * Cell.WEIGHT1) / Cell.K1\n nE = round(nE, 3)\n self.deathflag = np.random.choice([0, 1], p=[1 - nE, nE])\n if self.deathflag == 1:\n self.dead = 1\n field[self.i, self.j] = -1\n self.deathflag = 0\n else:\n pass\n\n @classmethod\n def list_adjust(cls, driver_list):\n driver_list.sort()\n\n @classmethod\n def make_idlist(cls, field, celllist):\n Tumor_cell.idlist = []\n refid = np.random.choice(field[field > -1], 256, replace=False)\n for i in refid:\n Tumor_cell.idlist.append(celllist[i].mutation_id)\n","sub_path":"python/Tumorcell_compe.py","file_name":"Tumorcell_compe.py","file_ext":"py","file_size_in_byte":9858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626799379","text":"import connexion\nimport six\n\nfrom swagger_server import util\nimport subprocess\nfrom connexion import NoContent\n\ndef run_cmd(args_list):\n \"\"\"\n run linux commands\n \"\"\"\n temp = args_list.split(\" \")\n temp = [ i for i in temp if i!='']\n print('Running system command : {0}'.format(' '.join(temp)))\n proc = subprocess.Popen(temp, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n s_output, s_err = proc.communicate()\n s_return = proc.returncode\n if s_return == 0:\n print (\"Command executed successfully \")\n retVal=400\n else:\n print(s_output)\n retVal=401\n return retVal\n\n\ndef trigger_ingestion(feedname): # noqa: E501\n \"\"\"Trigger a data ingestion rule\n\n # noqa: E501\n\n :param feedname: Feedname for which data ingestion needs to be triggered\n :type feedname: str\n\n :rtype: None\n \"\"\"\n command = \"python3 /home/etl/ETL/Trail_code/ETL_Ingestion.py \" + feedname\n ret_val = run_cmd(command)\n return 'data ingestion completed', ret_val\n","sub_path":"ETL_Swagger_Praveen/praveen/swag3/swagger_server/controllers/trigger_controller.py","file_name":"trigger_controller.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292162574","text":"#!/usr/bin/env python\n\nimport logging\nfrom subprocess import Popen, PIPE\nimport sys\n\nfrom magi.testbed import testbed\nfrom magi.util import helpers\nfrom magi.util.agent import DispatchAgent\nfrom magi.util.processAgent import initializeProcessAgent\n\nlog = logging.getLogger()\n\nclass link_up_down(DispatchAgent):\n \n def __init__(self):\n DispatchAgent.__init__(self)\n\n #there should be a delay node between the two nodes connected by the link for this up/down to work.\n # 'timing' is in seconds - 'timing' is relative to the time the event is called \n def link_up(self, msg, dest):\n functionName = self.link_up.__name__\n helpers.entrylog(log, functionName, locals())\n \n intf = self.node2Intf(dest)\n \n cmd = \"ifconfig %s up\" %(intf)\n log.info(\"Running cmd: %s\" %(cmd))\n \n process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)\n returncode = process.wait()\n stdout, stderr = process.communicate()\n \n if returncode == 0:\n log.info(stdout)\n log.info(\"Link to node '\" + dest + \"' brought up.\")\n else:\n log.error(stderr)\n log.error(\"Error in bringing link to node '\" + dest + \"' up. Error code %d\" %(returncode))\n \n return True\n\n def link_down(self, msg, dest):\n functionName = self.link_down.__name__\n helpers.entrylog(log, functionName, locals())\n \n intf = self.node2Intf(dest)\n \n cmd = \"ifconfig %s down\" %(intf)\n log.info(\"Running cmd: %s\" %(cmd))\n \n process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)\n returncode = process.wait()\n stdout, stderr = process.communicate()\n \n if returncode == 0:\n log.info(stdout)\n log.info(\"Link to node '\" + dest + \"' put down.\")\n else:\n log.error(stderr)\n log.error(\"Error in putting link to node '\" + dest + \"' down. Returncode %d\" %(returncode))\n \n return True\n\n def node2Intf(self, dest):\n topoGraph = testbed.getTopoGraph()\n src = testbed.getNodeName()\n linkname = topoGraph[src][dest]['linkName']\n srcLinks = topoGraph.node[src]['links']\n try:\n ip = srcLinks[linkname]['ip']\n return testbed.getInterfaceInfo(ip).name\n except Exception:\n raise Exception(\"Invalid information. Mostly no direct link to destination '%s'.\" %(dest))\n \n \n def link_up_tevc(self, msg, linkName, timing):\n functionName = self.link_up.__name__\n helpers.entrylog(log, functionName, locals())\n \n if timing == 0:\n timing = \"now\"\n else:\n timing = \"+\" + str(timing)\n \n cmd = \"/usr/testbed/bin/tevc -e %s %s %s up\" %(testbed.eid, timing, linkName)\n log.info(\"Running cmd: %s\" %(cmd))\n \n process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)\n returncode = process.wait()\n stdout, stderr = process.communicate()\n \n if returncode == 0:\n log.info(stdout)\n log.info(\"Link '\" + linkName + \"' brought up.\")\n else:\n log.error(stderr)\n log.error(\"Error in bringing link '\" + linkName + \"' up. Error code %d\" %(returncode))\n \n return True\n\n def link_down_tevc(self, msg, linkName, timing):\n functionName = self.link_down.__name__\n helpers.entrylog(log, functionName, locals())\n \n if timing == 0:\n timing = \"now\"\n else:\n timing = \"+\" + str(timing)\n \n cmd = \"/usr/testbed/bin/tevc -e %s %s %s down\" %(testbed.eid, timing, linkName)\n log.info(\"Running cmd: %s\" %(cmd))\n \n process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)\n returncode = process.wait()\n stdout, stderr = process.communicate()\n \n if returncode == 0:\n log.info(stdout)\n log.info(\"Link '\" + linkName + \"' put down.\")\n else:\n log.error(stderr)\n log.error(\"Error in putting link '\" + linkName + \"' down. Returncode %d\" %(returncode))\n \n return True\n\n# the getAgent() method must be defined somewhere for all agents.\n# The Magi daemon invokes this method to get a reference to an\n# agent. It uses this reference to run and interact with an agent\n# instance.\ndef getAgent(**kwargs):\n agent = link_up_down()\n agent.setConfiguration(None, **kwargs)\n return agent\n\n# In case the agent is run as a separate process, we need to\n# create an instance of the agent, initialize the required\n# parameters based on the received arguments, and then call the\n# run method defined in DispatchAgent.\nif __name__ == \"__main__\":\n agent = link_up_down()\n kwargs = initializeProcessAgent(agent, sys.argv)\n agent.setConfiguration(None, **kwargs)\n agent.run()\n","sub_path":"link_up_down/link_up_down.py","file_name":"link_up_down.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83946814","text":"import numpy as np\nimport warnings\nfrom galaxy_ml.preprocessors import TDMScaler\n\n\nwarnings.simplefilter('ignore')\n\n\nX = [[1., -2., 2.],\n [-2., 1., 3.],\n [4., 1., -2.]]\n\n\ndef test_self_transform():\n scaler = TDMScaler()\n scaler.fit(X)\n got = scaler.transform(X)\n\n assert np.array_equal(X, got), got\n","sub_path":"galaxy_ml/tests/test_tdmscaler.py","file_name":"test_tdmscaler.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436961273","text":"import math\nimport numpy as np\nclass Frame():\n def __init__(self, img=None, list_of_persons=list(), list_of_groups=list(), list_of_vehicles=list(),\n list_of_zones=list(), image_height=1080, image_width=1920, bboxes=list()):\n self.image = img\n self.list_of_persons = list_of_persons\n self.list_of_groups = list_of_groups\n self.list__of_vehicles = list_of_vehicles\n self.time = None\n self.list_of_zones = list_of_zones\n self.image_width = image_width\n self.image_height = image_height\n self.list_of_bboxes = bboxes\n\n def filter_bbox_human(self, list_of_bboxes):\n list_of_persons = list()\n for elem in list_of_bboxes:\n if elem is not \"\" and elem[-1] is \"0\":\n list_of_persons.append(list(map(int, elem.split(\",\")[:-1])))\n self.list_of_persons = list_of_persons\n\n def filter_bbox_vehicles(self, list_of_bboxes):\n list_of_persons = list()\n for elem in list_of_bboxes:\n if elem is not \"\" and elem[-1] is \"5\":\n list_of_persons.append(list(map(int, elem.split(\",\")[:-1])))\n self.list__of_vehicles = list_of_persons\n\n def check_for_neighbours(self):\n x_min, y_min, x_max, y_max = 0, 1, 2, 3\n groups = list()\n for person_idx in range(len(self.list_of_persons)):\n person1 = self.list_of_persons[person_idx]\n for person_to_comp_idx in range(len(self.list_of_persons)):\n if person_idx is person_to_comp_idx:\n continue\n else:\n person1_range_top = person1[y_min] - int((person1[y_max] - person1[y_min]) / 2)\n person1_range_bottom = person1[y_max] + int((person1[y_max] - person1[y_min]) / 2)\n person1_range_left = int((person1[x_min] - (person1[x_max] - person1[x_min])) * 1.05)\n person1_range_right = int((person1[x_max] + (person1[x_max] - person1[x_min])) * 1.05)\n person2 = self.list_of_persons[person_to_comp_idx]\n\n # check whether the neighbour is in the near of the bottom or top point of person1\n if (person1_range_top >= 0) and person1_range_top <= person2[y_min] <= person1[y_min] or \\\n (person1_range_bottom <= self.image_height) and person1_range_bottom <= person2[y_max] <= \\\n person1[\n y_max]:\n\n # check whether the neighbour is in the near of the left or right point of person1\n if (person1_range_right <= self.image_width) and person1[x_min] <= person2[\n x_min] <= person1_range_right or \\\n (person1_range_left >= 0) and person1_range_left <= person2[2] <= person1[x_min]:\n is_already_in_group = False\n if len(groups) > 0:\n for g in groups:\n if person_idx in g.members and person_to_comp_idx not in g.members:\n g.members.append(person_to_comp_idx)\n g.update_min_max_values_of_group([self.list_of_persons[person_to_comp_idx]])\n is_already_in_group = True\n break\n if not is_already_in_group:\n new_g = Group(person_idx)\n new_g.members.append(person_idx)\n new_g.members.append(person_to_comp_idx)\n new_g.update_min_max_values_of_group(\n [self.list_of_persons[person_idx], self.list_of_persons[person_to_comp_idx]])\n groups.append(new_g)\n self.list_of_groups = groups\n\n\nclass Person():\n def __init__(self, id, bbox):\n self.id = id\n self.bbox = bbox\n self.prev_bbox = bbox\n self.path = list()\n self.avg_speed = None\n\n def is_falling(self):\n # bbox = (xmin, ymin, xmax, ymax)\n return self.bbox[2] - self.bbox[0] < self.bbox[3] - self.bbox[1]\n\n def calculate_avg_speed(self):\n speed_between_frame = list()\n if len(self.path) > 1:\n for p in range(len(self.path)):\n dist = math.hypot(self.path[p][0] - self.path[p - 1][0], self.path[p][1] - self.path[p - 1][1])\n speed_between_frame.append(dist)\n arr = np.asarray(speed_between_frame)\n self.avg_speed = arr.mean()\n\n def update_person(self,bbox,keep_bbox=False ):\n self.prev_bbox = self.bbox\n if not keep_bbox:\n self.bbox = bbox\n middle_of_foot = (bbox[0] + ((bbox[1]-bbox[0])/2), bbox[3])\n self.path.append(middle_of_foot)\n self.calculate_avg_speed()\n\n\n\nclass Car():\n def __init__(self, id, bbox):\n self.id = id\n self.bbox = bbox\n self.path = list()\n self.avg_speed = None\n\n def calculate_avg_speed(self):\n speed_between_frame = list\n for p in range(len(self.path)):\n dist = math.hypot(self.path[p+1][0] - self.path[p][0], self.path[p+1][1] - self.path[p][1])\n speed_between_frame.append(dist)\n arr = np.asarray(speed_between_frame)\n self.avg_speed = arr.mean()\n\n def update_car(self,bbox,keep_bbox=False ):\n self.prev_bbox = self.bbox\n if not keep_bbox:\n self.bbox = bbox\n middle_of_foot = (bbox[0] + ((bbox[1]-bbox[0])/2), bbox[3])\n self.path.append(middle_of_foot)\n self.calculate_avg_speed()\n\n\n \n\n\n\n\nclass Group():\n def __init__(self, id):\n self.id = id\n self.members = list()\n self.min_x = 20000\n self.min_y = 20000\n self.max_x = 0\n self.max_y = 0\n self.bbox = [self.min_x, self.min_y, self.max_x, self.max_y]\n\n def update_min_max_values_of_group(self, list_of_bboxes):\n for elem in list_of_bboxes:\n if elem[0] < self.min_x:\n self.min_x = elem[0]\n if elem[1] < self.min_y:\n self.min_y = elem[1]\n if elem[2] > self.max_x:\n self.max_x = elem[2]\n if elem[3] > self.max_y:\n self.max_y = elem[3]\n\n self.bbox = [self.min_x, self.min_y, self.max_x, self.max_y]\n","sub_path":"helpers/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"476571129","text":"\"\"\"\nCopyright 2020, Institute for Systems Biology\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nimport io\nimport json\nimport os\nimport sys\nimport time\n\nimport requests\nimport yaml\nfrom google.api_core.exceptions import NotFound\nfrom google.cloud import bigquery, storage, exceptions\n\n\n# GETTERS - YAML CONFIG\n\n\ndef get_field_groups(api_params):\n \"\"\"Get field group list from build master table yaml config for GDC.\n\n :param api_params: api param object from yaml config\n :return: list of expand field groups\n \"\"\"\n if 'FIELD_GROUPS' not in api_params:\n has_fatal_error('FIELD_GROUPS not in api_params (check yaml config file)')\n return \",\".join(list(api_params['FIELD_GROUPS']))\n\n\ndef get_required_fields(api_params, fg):\n \"\"\"Get list of required fields (used to create schema and load values into BQ table).\n\n :param api_params: api param object from yaml config\n :param fg: name of field group for which to retrieve required fields\n :return: list of required fields (currently only returns fg's id key)\n \"\"\"\n field_config = api_params['FIELD_CONFIG']\n\n if fg in field_config and 'id_key' in field_config[fg]:\n # this is a single entry list of the moment\n return [get_field_key(fg, field_config[fg]['id_key'])]\n\n return None\n\n\ndef get_column_order_one_fg(api_params, fg):\n \"\"\"Get field/column order list associated with given field group from yaml config.\n\n :param api_params: api param object from yaml config\n :param fg: field group for which to retrieve field/column order list\n :return: field group's column order list\n \"\"\"\n if fg not in api_params['FIELD_CONFIG']:\n has_fatal_error(\"'{}' not found in FIELD_CONFIG in yaml config\".format(fg))\n\n fg_params = api_params['FIELD_CONFIG'][fg]\n\n if not fg_params or 'column_order' not in fg_params:\n has_fatal_error(\"No order for field group {} in yaml.\".format(fg), KeyError)\n\n # return full field key, in order, for given field_grp\n return [get_field_key(fg, field) for field in fg_params['column_order']]\n\n\ndef get_excluded_field_groups(api_params):\n \"\"\"Get a list of field groups (via yaml config) to exclude from the final tables.\n Currently used in order to exclude fgs that would otherwise create duplicate columns\n when merging fgs into a smaller # of tables, WHILE not utilizing fg prefixes\n to create unique names (which is undesirable for web app integration, for instance).\n\n :param api_params: api param object from yaml config\n :return: list of field groups to exclude\n \"\"\"\n if 'FG_CONFIG' not in api_params or not api_params['FG_CONFIG']:\n has_fatal_error('FG_CONFIG not in api_params, or is empty', KeyError)\n if 'excluded_fgs' not in api_params['FG_CONFIG']:\n has_fatal_error('excluded_fgs not found in not in FG_CONFIG', KeyError)\n\n return api_params['FG_CONFIG']['excluded_fgs']\n\n\ndef get_excluded_fields_all_fgs(api_params, fgs, is_webapp=False):\n \"\"\"Get a list of fields for each field group to exclude from the tables\n from yaml config (api_params['FIELD_CONFIG']['excluded_fields'] or\n api_params['FIELD_CONFIG']['app_excluded_fields'] for the web app).\n\n :param api_params: api param object from yaml config\n :param fgs: list of expand field groups included from API call\n :param is_webapp: is script currently running for 'create_webapp_tables' step?\n :return: set of fields to exclude\n \"\"\"\n if 'FIELD_CONFIG' not in api_params or not api_params['FIELD_CONFIG']:\n has_fatal_error('FIELD_CONFIG not in api_params, or is empty', KeyError)\n\n excluded_list_key = 'app_excluded_fields' if is_webapp else 'excluded_fields'\n\n exclude_fields = set()\n\n for fg in fgs:\n if fg not in api_params['FIELD_CONFIG']:\n has_fatal_error('{} not found in not in FIELD_CONFIG'.format(fg), KeyError)\n elif not api_params['FIELD_CONFIG'][fg]:\n continue\n elif excluded_list_key not in api_params['FIELD_CONFIG'][fg]:\n has_fatal_error(\"One of the excluded params missing from YAML.\", KeyError)\n elif not api_params['FIELD_CONFIG'][fg][excluded_list_key]:\n continue\n\n for field in api_params['FIELD_CONFIG'][fg][excluded_list_key]:\n exclude_fields.add(get_field_key(fg, field))\n\n return exclude_fields\n\n\ndef get_excluded_fields_one_fg(api_params, fg, is_webapp=False):\n \"\"\"Get excluded fields for given field group (pulled from yaml config file).\n\n :param api_params: api param object from yaml config\n :param fg: field group for which to retrieve excluded fields\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: list of excluded fields associated with field group 'fg' in yaml config\n \"\"\"\n if 'FIELD_CONFIG' not in api_params:\n has_fatal_error(\"FIELD_CONFIG not set in YAML.\", KeyError)\n elif fg not in api_params['FIELD_CONFIG']:\n has_fatal_error(\"{} not set in YAML.\".format(fg), KeyError)\n elif not api_params['FIELD_CONFIG'][fg]:\n has_fatal_error(\"api_params['FIELD_CONFIG']['{}'] not found\".format(fg), KeyError)\n\n excluded_key = 'app_excluded_fields' if is_webapp else 'excluded_fields'\n\n if excluded_key not in api_params['FIELD_CONFIG'][fg]:\n has_fatal_error(\"{}'s {} not found.\".format(fg, excluded_key))\n\n excluded_list = api_params['FIELD_CONFIG'][fg][excluded_key]\n return [get_bq_name(api_params, f, is_webapp, fg) for f in excluded_list]\n\n\ndef get_rel_prefix(bq_params):\n \"\"\"Get current release number/date (set in yaml config).\n\n :param bq_params: bq param object from yaml config\n :return: release abbreviation\n \"\"\"\n rel_prefix = ''\n\n if 'REL_PREFIX' in bq_params and bq_params['REL_PREFIX']:\n rel_prefix += bq_params['REL_PREFIX']\n if 'RELEASE' in bq_params and bq_params['RELEASE']:\n rel_prefix += bq_params['RELEASE']\n\n return rel_prefix\n\n\ndef get_fg_prefix(api_params, fg):\n \"\"\"Get field group abbreviations from yaml config, used to create field prefixes\n in order to prevent BQ column name duplication.\n\n :param api_params: api param object from yaml config\n :param fg: specific field group for which to retrieve prefix\n :return: str containing the prefix designated in yaml config for given fg\n \"\"\"\n if 'FIELD_CONFIG' not in api_params or not api_params['FIELD_CONFIG']:\n has_fatal_error('FIELD_CONFIG not in api_params, or is empty', KeyError)\n\n elif fg not in api_params['FIELD_CONFIG']:\n has_fatal_error('{} not found in not in FIELD_CONFIG'.format(fg), KeyError)\n\n elif 'prefix' not in api_params['FIELD_CONFIG'][fg]:\n has_fatal_error(\"prefix not found in FIELD_CONFIG for {}\".format(fg), KeyError)\n\n return api_params['FIELD_CONFIG'][fg]['prefix']\n\n\ndef get_table_suffixes(api_params):\n \"\"\"Get abbreviations for field groups as designated in yaml config.\n\n :param api_params: api param object from yaml config\n :return: dict of {field_group: abbreviation_suffix}\n \"\"\"\n suffixes = dict()\n\n for table, metadata in api_params['FIELD_CONFIG'].items():\n suffixes[table] = metadata['table_suffix'] if metadata['table_suffix'] else ''\n\n return suffixes\n\n\ndef build_master_table_name_from_params(bq_params):\n \"\"\"Get master table name from yaml config.\n\n :param bq_params: bq param object from yaml config\n :return: master table name\n \"\"\"\n return \"_\".join([get_rel_prefix(bq_params), bq_params['MASTER_TABLE']])\n\n\n# GETTERS - MISC\n#\n\n\n# Project and Program Getters\n\n\ndef get_program_list(bq_params):\n \"\"\"Get list of the programs which have contributed data to GDC's research program.\n\n :param bq_params: bq param object from yaml config\n :return: list of research programs participating in GDC data sharing\n \"\"\"\n programs_query = (\"\"\"\n SELECT DISTINCT(proj) \n FROM (\n SELECT SPLIT(\n (SELECT project_id\n FROM UNNEST(project)), '-')[OFFSET(0)] AS proj\n FROM `{}`)\n ORDER BY proj\n \"\"\").format(get_working_table_id(bq_params))\n\n return {prog.proj for prog in get_query_results(programs_query)}\n\n\ndef get_project_name(table_id):\n \"\"\"Get the BQ project name for a given table id.\n\n :param table_id: id in standard SQL format: '{project_id}.{dataset_id}.{table_name}'\n :return: GDC project to which the BQ table belongs\n \"\"\"\n split_table = table_id.split('.')\n\n if len(split_table) != 3:\n has_fatal_error(\"Incorrect naming for table_id: {}\".format(table_id))\n\n return split_table[0]\n\n\n# Table Getters\n\n\ndef get_one_to_many_tables(api_params, record_counts):\n \"\"\"Get one-to-many tables for program.\n\n :param api_params: api param object from yaml config\n :param record_counts: dict max field group record counts for program\n :return: set of table names (representing field groups which cannot be flattened)\n \"\"\"\n table_keys = {get_base_fg(api_params)}\n\n for table in record_counts:\n if record_counts[table] > 1:\n table_keys.add(table)\n\n return table_keys\n\n\ndef build_table_name(str_list):\n \"\"\"Constructs a table name (str) from list<str>.\n\n :param str_list: a list<str> of table name segments\n :return: composed table name string\n \"\"\"\n table_name = \"_\".join(str_list)\n\n # replace '.' with '_' so that the name is valid\n # ('.' chars not allowed -- issue with BEATAML1.0, for instance)\n return table_name.replace('.', '_')\n\n\ndef convert_json_to_table_name(bq_params, json_file):\n \"\"\"Convert json filename (from BQEcosystem repo) into BQ table name.\n json schema files match table ID of BQ table.\n\n :param bq_params: bq param object from yaml config\n :param json_file: json file from BQEcosystem repo containing table schema\n data and metadata; json file naming matches table ID of corresponding BQ table\n :return: BQ table name for which the json acts as a configuration file\n \"\"\"\n # handles naming for *webapp* tables\n split_name = json_file.split('.')\n program_name = split_name[1]\n split_table = split_name[2].split('_')\n table_name = '_'.join(split_table[:-2])\n rel = get_rel_prefix(bq_params)\n\n return '_'.join([rel, program_name, table_name])\n\n\ndef build_table_id(project, dataset, table):\n \"\"\" Build table_id in {project_id}.{dataset_id}.{table_name} format.\n\n :param project: project id\n :param dataset: dataset id\n :param table: table name\n :return: table_id\n \"\"\"\n return '{}.{}.{}'.format(project, dataset, table)\n\n\ndef convert_json_to_table_id(bq_params, json_file):\n \"\"\"Convert json file from BQEcosystem repo into component dataset and table names.\n Naming matches table ID of corresponding production BQ clinical tables.\n\n :param bq_params: bq param object from yaml config\n :param json_file: json file from BQEcosystem repo, storing table metadata\n :return: names of datasets and tables for production current and versioned\n repositories\n \"\"\"\n split_json = json_file.split('.')\n dest_table = \"_\".join(split_json[2].split('_')[:-1])\n\n dev_project = bq_params['DEV_PROJECT']\n prod_project = bq_params['PROD_PROJECT']\n\n dev_dataset = bq_params['DEV_DATASET']\n curr_dataset = split_json[1]\n versioned_dataset = \"_\".join([curr_dataset, bq_params['VERSIONED_SUFFIX']])\n\n src_table = \"_\".join(split_json[2].split('_')[:-2])\n src_table = \"_\".join([get_rel_prefix(bq_params), split_json[1], src_table])\n curr_table = \"_\".join([dest_table, bq_params['CURRENT_SUFFIX']])\n vers_table = \"_\".join([dest_table, get_rel_prefix(bq_params)])\n\n src_table_id = build_table_id(dev_project, dev_dataset, src_table)\n curr_table_id = build_table_id(prod_project, curr_dataset, curr_table)\n vers_table_id = build_table_id(prod_project, versioned_dataset, vers_table)\n\n return src_table_id, curr_table_id, vers_table_id\n\n\ndef get_biospecimen_table_id(bq_params, program):\n \"\"\"Builds and retrieves a table ID for the biospecimen stub tables.\n\n :param bq_params: bq param object from yaml config\n :param program: the program from which the cases originate\n :return: biospecimen table_id\n \"\"\"\n table_name = build_table_name([get_rel_prefix(bq_params),\n str(program),\n bq_params['BIOSPECIMEN_SUFFIX']])\n\n return build_table_id(bq_params['DEV_PROJECT'], bq_params['APP_DATASET'], table_name)\n\n\ndef get_working_table_id(bq_params, table_name=None):\n \"\"\"Get table id for development version of the db table.\n\n :param bq_params: bq param object from yaml config\n :param table_name: name of the bq table\n :return: table id\n \"\"\"\n if not table_name:\n table_name = build_master_table_name_from_params(bq_params)\n\n return build_table_id(bq_params[\"DEV_PROJECT\"], bq_params[\"DEV_DATASET\"], table_name)\n\n\ndef get_webapp_table_id(bq_params, table_name):\n \"\"\"Get table id for webapp db table.\n\n :param bq_params: bq param object from yaml config\n :param table_name: name of the bq table\n :return: table id\n \"\"\"\n return build_table_id(bq_params['DEV_PROJECT'], bq_params['APP_DATASET'], table_name)\n\n\n# Field and Field Group Getters\n\n\ndef get_base_fg(api_params):\n \"\"\"Get the first-level field group, of which all other field groups are descendents.\n\n :param api_params: api param object from yaml config\n :return: base field group name\n \"\"\"\n if 'FG_CONFIG' not in api_params:\n has_fatal_error(\"FG_CONFIG not set (in api_params) in YAML.\", KeyError)\n if 'base_fg' not in api_params['FG_CONFIG'] or not api_params['FG_CONFIG']['base_fg']:\n has_fatal_error(\"base_fg not set (in api_params['FG_CONFIG']) in YAML.\", KeyError)\n\n return api_params['FG_CONFIG']['base_fg']\n\n\ndef get_parent_fg(tables, field_name):\n \"\"\"\n Get field's parent table name.\n :param tables: list of table names for program\n :param field_name: full field name for which to retrieve parent table\n :return: parent table name\n \"\"\"\n parent_table = get_field_group(field_name)\n\n while parent_table and parent_table not in tables:\n parent_table = get_field_group(parent_table)\n\n if parent_table:\n return parent_table\n return has_fatal_error(\"No parent fg found for {}\".format(field_name))\n\n\ndef get_field_group(field_name):\n \"\"\"Gets parent field group (might not be the parent *table*, as the ancestor fg\n could be flattened).\n\n :param field_name: field name for which to retrieve ancestor field group\n :return: ancestor field group\n \"\"\"\n return \".\".join(field_name.split('.')[:-1])\n\n\ndef get_field_group_id_key(api_params, field_group, is_webapp=False, return_field_only=False):\n \"\"\"Retrieves the id key used to uniquely identify a table record.\n\n :param api_params: api param object from yaml config\n :param field_group: table for which to determine the id key\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: str representing table key\n \"\"\"\n\n split_fg = field_group.split('.')\n if split_fg[0] != api_params['FG_CONFIG']['base_fg']:\n split_fg.insert(0, api_params['FG_CONFIG']['base_fg'])\n field_group = \".\".join(split_fg)\n\n if field_group not in api_params['FIELD_CONFIG']:\n console_out(\"field group {} not in API_PARAMS['FIELD_CONFIG']\".format(field_group))\n return None\n if 'id_key' not in api_params['FIELD_CONFIG'][field_group]:\n has_fatal_error(\"id_key not found in API_PARAMS for {}\".format(field_group))\n\n fg_id_name = api_params['FIELD_CONFIG'][field_group]['id_key']\n\n if return_field_only:\n return fg_id_name\n\n fg_id_key = get_field_key(field_group, fg_id_name)\n\n if is_webapp:\n new_fg_id_key = get_renamed_field_key(api_params, fg_id_key)\n\n if new_fg_id_key:\n return new_fg_id_key\n\n return fg_id_key\n\n\ndef get_fg_id_name(api_params, field_group, is_webapp=False):\n \"\"\"Retrieves the id key used to uniquely identify a table record.\n\n :param api_params: api param object from yaml config\n :param field_group: table for which to determine the id key\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: str representing table key\n \"\"\"\n fg_id_key = get_field_group_id_key(api_params, field_group, is_webapp)\n\n return get_field_name(fg_id_key)\n # todo this should be replaced\n\n\ndef get_field_name(field_col_key):\n \"\"\"Get short field name from full field or bq column name.\n\n :param field_col_key: full field or bq column name\n :return: short field name\n \"\"\"\n if '.' not in field_col_key and '__' not in field_col_key:\n return field_col_key\n\n split_char = '.' if '.' in field_col_key else '__'\n\n return field_col_key.split(split_char)[-1]\n\n\ndef get_field_key(field_group, field):\n \"\"\"Get full field key (\"{field_group}.{field_name}\"}.\n\n :param field_group: field group to which the field belongs\n :param field: field name\n :return: full field key string\n \"\"\"\n return '{}.{}'.format(field_group, field)\n\n\ndef get_bq_name(api_params, field, is_webapp=False, arg_fg=None):\n \"\"\"Get column name (in bq format) from full field name.\n\n :param api_params: api params from yaml config file\n :param field: if not table_path, full field name; else short field name\n :param arg_fg: field group containing field\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: bq column name for given field name\n \"\"\"\n base_fg = get_base_fg(api_params)\n\n if arg_fg:\n # field group is specified as a function argument\n fg = arg_fg\n field_key = get_field_key(fg, field)\n elif len(field.split('.')) == 1:\n # no fg delimiter found in field string: cannot be a complete field key\n fg = base_fg\n field_key = get_field_key(fg, field)\n else:\n # no fg argument, but field contains separator chars; extract the fg and name\n fg = get_field_group(field)\n field_key = field\n\n # derive the key's short field name\n field_name = get_field_name(field_key)\n\n # get id_key and prefix associated with this fg\n this_fg_id = get_fg_id_name(api_params, fg)\n prefix = get_fg_prefix(api_params, fg)\n\n # create map of {fg_names : id_keys}\n fg_to_id_key_map = get_fgs_and_id_keys(api_params)\n\n # if fg has no prefix, or\n # field is child of base_fg, or\n # function called for webapp table building: do not add prefix\n if fg == base_fg or is_webapp or not prefix:\n return field_name\n\n # if field is an id_key, but is not mapped to this fg: do not add prefix\n if field_name in fg_to_id_key_map.values() and field_name != this_fg_id:\n return field_name\n\n # if the function reaches this line, return a prefixed field:\n # - the table is user-facing, and\n # - this field isn't a foreign id key\n return \"__\".join([prefix, field_name])\n\n\ndef get_renamed_field_key(api_params, field_key):\n \"\"\"Gets the new field name for an existing field.\n Used to rename fields for web app integration.\n\n :param api_params: api param object from yaml config\n :param field_key: field key ({fg}.{field}) for which to find a alternative field key\n :return: None if no replacement field key, otherwise string containing new field key\n \"\"\"\n if 'RENAMED_FIELDS' not in api_params:\n has_fatal_error(\"RENAMED_FIELDS not found in API_PARAMS\")\n\n renamed_fields = api_params['RENAMED_FIELDS']\n\n if not renamed_fields or (renamed_fields and field_key not in renamed_fields):\n return None\n\n return renamed_fields[field_key]\n\n\ndef get_renamed_field_keys(api_params):\n \"\"\"Get renamed fields dict from yaml config.\n\n :param api_params: api param object from yaml config\n :return: renamed fields dict\n \"\"\"\n if 'RENAMED_FIELDS' not in api_params:\n has_fatal_error(\"RENAMED_FIELDS not found in API_PARAMS\")\n\n return api_params['RENAMED_FIELDS']\n\n\n# I/O Getters\n\n\ndef build_working_gs_uri(bq_params, filename):\n \"\"\"Builds an uri reference for file uploaded to Google storage bucket.\n\n :param bq_params: bq param object from yaml config\n :param filename: file uploaded to google storage bucket\n :return: uri reference for google storage bucket file\n \"\"\"\n return \"gs://{}/{}/{}\".format(bq_params['WORKING_BUCKET'],\n bq_params['WORKING_BUCKET_DIR'],\n filename)\n\n\ndef construct_table_name(bq_params, program='', suffix='', is_webapp=False):\n \"\"\"\n todo\n :param bq_params:\n :param program:\n :param suffix:\n :param is_webapp:\n :return:\n \"\"\"\n app_prefix = bq_params['APP_JSONL_PREFIX'] if is_webapp else ''\n\n name_list = [app_prefix,\n bq_params['REL_PREFIX'] + bq_params['RELEASE'],\n program,\n bq_params['MASTER_TABLE'],\n suffix]\n\n file_name = [x for x in name_list if x]\n return '_'.join(file_name)\n\n\ndef build_jsonl_output_filename(bq_params, program='', suffix='', is_webapp=False):\n \"\"\"\n todo\n :param bq_params:\n :param program:\n :param suffix:\n :param is_webapp:\n :return:\n \"\"\"\n file_name = construct_table_name(bq_params, program, suffix, is_webapp)\n\n return file_name + '.jsonl'\n\n\ndef get_suffixed_jsonl_filename(api_params, bq_params, program, table, is_webapp=False):\n \"\"\"\n todo\n :param api_params:\n :param bq_params:\n :param program:\n :param table:\n :param is_webapp:\n :return:\n \"\"\"\n suffixes = get_table_suffixes(api_params)\n suffix = suffixes[table]\n program = program.replace('.', '_')\n\n return build_jsonl_output_filename(bq_params, program, suffix, is_webapp=is_webapp)\n\n\ndef build_jsonl_name(api_params, bq_params, program, table, is_webapp=False):\n \"\"\"\n todo\n :param api_params:\n :param bq_params:\n :param program:\n :param table:\n :param is_webapp:\n :return:\n \"\"\"\n app_prefix = bq_params['APP_JSONL_PREFIX'] if is_webapp else ''\n gdc_rel = bq_params['REL_PREFIX'] + bq_params['RELEASE']\n program = program.replace('.', '_')\n base_name = bq_params['MASTER_TABLE']\n suffix = get_table_suffixes(api_params)[table]\n\n name_list = [app_prefix, gdc_rel, program, base_name, suffix]\n filtered_name_list = [x for x in name_list if x]\n file_name = '_'.join(filtered_name_list)\n\n return file_name + '.jsonl'\n\n\ndef get_filepath(dir_path, filename=None):\n \"\"\"Get file path for location on VM.\n\n :param dir_path: directory portion of the filepath (starting at user home dir)\n :param filename: name of the file\n :return: full path to file\n \"\"\"\n join_list = [os.path.expanduser('~'), dir_path]\n\n if filename:\n join_list.append(filename)\n\n return '/'.join(join_list)\n\n\ndef get_scratch_fp(bq_params, filename):\n \"\"\"Construct filepath for VM output file.\n\n :param filename: name of the file\n :param bq_params: bq param object from yaml config\n :return: output filepath for VM\n \"\"\"\n return get_filepath(bq_params['SCRATCH_DIR'], filename)\n\n\n# FILESYSTEM HELPERS\n\n\ndef get_dir(fp):\n \"\"\" Get directory component of filepath.\n\n :param fp: full filepath (dir and file name)\n :return: directory component of fp\n \"\"\"\n return '/'.join(fp.split('/')[:-1])\n\n\ndef write_list_to_jsonl(jsonl_fp, json_obj_list, mode='w'):\n \"\"\" Create a jsonl file for uploading data into BQ from a list<dict> obj.\n\n :param jsonl_fp: filepath of jsonl file to write\n :param json_obj_list: list<dict> object\n :param mode: 'a' if appending to a file that's being built iteratively\n 'w' if file data is written in a single call to the function\n (in which case any existing data is overwritten)\"\"\"\n\n with open(jsonl_fp, mode) as file_obj:\n cnt = 0\n\n for line in json_obj_list:\n json.dump(obj=line, fp=file_obj)\n file_obj.write('\\n')\n cnt += 1\n\n\ndef append_list_to_jsonl(file_obj, json_list):\n try:\n for line in json_list:\n json_str = convert_dict_to_string(line)\n json.dump(obj=json_str, fp=file_obj)\n file_obj.write('\\n')\n except IOError as err:\n print(str(err), IOError)\n\n\ndef delete_file(fp):\n if os.path.exists(fp):\n os.remove(fp)\n print(\"{} deleted successfully!\".format(fp))\n else:\n print(\"{} not found!\".format(fp))\n\n\n# REST API HELPERS (GDC, PDC, ETC)\n\n\ndef create_mapping_dict(endpoint):\n \"\"\"Creates a dict containing field mappings for given endpoint.\n Note: only differentiates the GDC API's 'long' type (called 'integer' in GDC data\n dictionary) and 'float' type (called 'number' in GDC data dictionary). All others\n typed as string.\n\n :param endpoint: API endpoint for which to retrieve mapping\n :return: dict of field maps. Each entry contains field name, type, and description\n \"\"\"\n field_mapping_dict = {}\n\n # retrieve mappings json object\n res = requests.get(endpoint + '/_mapping')\n field_mappings = res.json()['_mapping']\n\n for field in field_mappings:\n # convert data types from GDC format to formats used in BQ\n if field_mappings[field]['type'] == 'long':\n field_type = 'INTEGER'\n elif field_mappings[field]['type'] == 'float':\n field_type = 'FLOAT'\n else:\n field_type = 'STRING'\n\n # create json object of field mapping data\n field_mapping_dict[field] = {\n 'name': field.split('.')[-1],\n 'type': field_type,\n 'description': field_mappings[field]['description']\n }\n\n return field_mapping_dict\n\n\ndef create_schema_dict(api_params, bq_params, is_webapp=False):\n \"\"\"Creates schema dict using master table's bigquery.table.Table.schema attribute.\n\n :param api_params: api param object from yaml config\n :param bq_params: bq params from yaml config file\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: flattened schema dict in format:\n {full field name: {name: 'name', type: 'field_type', description: 'description'}}\n \"\"\"\n client = bigquery.Client()\n bq_table = client.get_table(get_working_table_id(bq_params))\n\n schema_list = []\n\n for schema_field in bq_table.schema:\n schema_list.append(schema_field.to_api_repr())\n\n schema = dict()\n\n parse_bq_schema_obj(api_params=api_params,\n schema=schema,\n fg=get_base_fg(api_params),\n schema_list=schema_list,\n is_webapp=is_webapp)\n\n return schema\n\n\ndef get_cases_by_program(bq_params, program):\n \"\"\"Get a dict obj containing all the cases associated with a given program.\n\n :param bq_params: bq param object from yaml config\n :param program: the program from which the cases originate\n :return: cases dict\n \"\"\"\n start_time = time.time()\n cases = []\n\n sample_table_id = get_biospecimen_table_id(bq_params, program)\n\n query = \"\"\"\n SELECT * \n FROM `{}` \n WHERE case_id IN (\n SELECT DISTINCT(case_gdc_id) \n FROM `{}`\n WHERE project_name = '{}')\n \"\"\".format(get_working_table_id(bq_params), sample_table_id, program)\n\n for case_row in get_query_results(query):\n case_items = dict(case_row.items())\n case_items.pop('project')\n cases.append(case_items)\n\n end_time = time.time() - start_time\n\n return cases\n\n\ndef get_graphql_api_response(api_params, query, fail_on_error=True):\n max_retries = 4\n\n headers = {'Content-Type': 'application/json'}\n endpoint = api_params['ENDPOINT']\n\n if not query:\n has_fatal_error(\"Must specify query for get_graphql_api_response.\", SyntaxError)\n\n req_body = {'query': query}\n api_res = requests.post(endpoint, headers=headers, json=req_body)\n tries = 0\n\n while not api_res.ok and tries < max_retries:\n console_out(\"API response status code {}: {};\\nRetry {} of {}...\",\n (api_res.status_code, api_res.reason, tries, max_retries))\n time.sleep(3)\n\n api_res = requests.post(endpoint, headers=headers, json=req_body)\n\n tries += 1\n\n if tries > max_retries:\n # give up!\n api_res.raise_for_status()\n\n json_res = api_res.json()\n\n if 'errors' in json_res and json_res['errors']:\n if fail_on_error:\n has_fatal_error(\"Errors returned by {}.\\nError json:\\n{}\".format(endpoint, json_res['errors']))\n return None\n\n return json_res\n\n\n# BIGQUERY API HELPERS\n\n\ndef get_last_fields_in_table(api_params):\n \"\"\" Get list of fields to always include at the end of merged tables,\n via the yaml config.\n\n :param api_params: api param object from yaml config\n :return: fields to include at the end of the table\n \"\"\"\n if 'FG_CONFIG' not in api_params:\n has_fatal_error(\"Missing FG_CONFIG in YAML\", KeyError)\n elif 'last_keys_in_table' not in api_params['FG_CONFIG']:\n has_fatal_error(\"Missing last_keys_in_table in FG_CONFIG in YAML\", KeyError)\n\n return api_params['FG_CONFIG']['last_keys_in_table']\n\n\ndef parse_bq_schema_obj(api_params, schema, fg, schema_list=None, is_webapp=False):\n \"\"\"Recursively construct schema using existing metadata in main clinical table.\n\n :param api_params: api param object from yaml config\n :param schema: dict of flattened schema entries\n :param fg: current field group name\n :param schema_list: schema field entries for field_group\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n \"\"\"\n\n if fg not in api_params['FIELD_CONFIG']:\n return\n\n for i, schema_field in enumerate(schema_list):\n\n field_key = get_field_key(fg, schema_field['name'])\n\n # if has 'fields', then the current obj contains nested objs\n if schema_field['type'] == 'RECORD':\n # if nested, recurse down to the next level\n parse_bq_schema_obj(api_params, schema, field_key, schema_field['fields'], is_webapp)\n\n required_field_list = get_required_fields(api_params, fg)\n\n for field_name in required_field_list:\n schema[field_name]['mode'] = 'REQUIRED'\n else:\n # not a nested field entry--do we need to prefix the schema field name?\n schema_field['name'] = get_bq_name(api_params, field_key, is_webapp)\n schema[field_key] = schema_field\n\n\ndef get_fgs_and_id_keys(api_params):\n \"\"\" Create a dictionary of type { 'field_group' : 'id_key_field'}.\n\n :param api_params: api param object from yaml config\n :return: mapping dict, field group -> id_key_field\n \"\"\"\n id_key_dict = dict()\n\n fg_config_entries = api_params['FIELD_CONFIG']\n\n for fg in fg_config_entries:\n id_key_dict[fg] = fg_config_entries[fg]['id_key']\n\n return id_key_dict\n\n\ndef copy_bq_table(bq_params, src_table, dest_table, replace_table=False):\n \"\"\"Copy an existing BQ table into a new location.\n\n :param bq_params: bq param object from yaml config\n :param src_table: Table to copy\n :param dest_table: Table to be created\n \"\"\"\n client = bigquery.Client()\n\n job_config = bigquery.CopyJobConfig()\n\n if replace_table:\n delete_bq_table(dest_table)\n\n bq_job = client.copy_table(src_table, dest_table, job_config=job_config)\n\n if await_job(bq_params, client, bq_job):\n console_out(\"Successfully copied table:\")\n console_out(\"src: {0}\\n dest: {1}\\n\", (src_table, dest_table))\n\n\ndef create_and_load_table(bq_params, jsonl_file, schema, table_id):\n \"\"\"Creates BQ table and inserts case data from jsonl file.\n\n :param bq_params: bq param obj from yaml config\n :param jsonl_file: file containing case records in jsonl format\n :param schema: list of SchemaFields representing desired BQ table schema\n :param table_id: id of table to create\n \"\"\"\n client = bigquery.Client()\n job_config = bigquery.LoadJobConfig()\n job_config.schema = schema\n job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON\n job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE\n\n gs_uri = build_working_gs_uri(bq_params, jsonl_file)\n\n try:\n load_job = client.load_table_from_uri(gs_uri, table_id, job_config=job_config)\n console_out(' - Inserting into {0}... ', (table_id,), end=\"\")\n await_insert_job(bq_params, client, table_id, load_job)\n except TypeError as err:\n has_fatal_error(err)\n\n\ndef create_and_load_tsv_table(bq_params, tsv_file, schema, table_id, null_marker=''):\n \"\"\"Creates BQ table and inserts case data from jsonl file.\n\n :param bq_params: bq param obj from yaml config\n :param tsv_file: file containing case records in tsv format\n :param schema: list of SchemaFields representing desired BQ table schema\n :param table_id: id of table to create\n \"\"\"\n client = bigquery.Client()\n job_config = bigquery.LoadJobConfig()\n job_config.schema = schema\n job_config.source_format = bigquery.SourceFormat.CSV\n job_config.field_delimiter = '\\t'\n job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE\n job_config.skip_leading_rows = 1\n job_config.null_marker = null_marker # todo added this back, is that ok?\n\n gs_uri = build_working_gs_uri(bq_params, tsv_file)\n\n try:\n load_job = client.load_table_from_uri(gs_uri, table_id, job_config=job_config)\n\n console_out(' - Inserting into {0}... ', (table_id,), end=\"\")\n await_insert_job(bq_params, client, table_id, load_job)\n except TypeError as err:\n has_fatal_error(err)\n\n\ndef delete_bq_table(table_id):\n \"\"\"Permanently delete BQ table located by table_id.\n\n :param table_id: table id in standard SQL format\n \"\"\"\n client = bigquery.Client()\n client.delete_table(table_id, not_found_ok=True)\n\n console_out(\"deleted table: {0}\", (table_id,))\n\n\ndef exists_bq_table(table_id):\n \"\"\"Determine whether bq_table exists.\n\n :param table_id: table id in standard SQL format\n :return: True if exists, False otherwise\n \"\"\"\n client = bigquery.Client()\n\n try:\n client.get_table(table_id)\n except NotFound:\n return False\n return True\n\n\ndef load_table_from_query(bq_params, table_id, query):\n \"\"\"Create a new BQ table from the returned results of querying an existing BQ db.\n\n :param bq_params: bq params from yaml config file\n :param table_id: table id in standard SQL format\n :param query: query which returns data to populate a new BQ table.\n \"\"\"\n client = bigquery.Client()\n job_config = bigquery.QueryJobConfig(destination=table_id)\n job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE\n\n try:\n query_job = client.query(query, job_config=job_config)\n console_out(' - Inserting into {0}... ', (table_id,), end=\"\")\n await_insert_job(bq_params, client, table_id, query_job)\n except TypeError as err:\n has_fatal_error(err)\n\n\ndef get_bq_table_obj(table_id):\n \"\"\"Get the bq table referenced by table_id.\n\n :param table_id: table id in standard SQL format\n :return: bq Table object\n \"\"\"\n if not exists_bq_table(table_id):\n return None\n\n client = bigquery.Client()\n return client.get_table(table_id)\n\n\ndef get_query_results(query):\n \"\"\"Returns BigQuery query result object.\n\n :param query: query string\n :return: result object\n \"\"\"\n client = bigquery.Client()\n query_job = client.query(query)\n return query_job.result()\n\n\ndef await_insert_job(bq_params, client, table_id, bq_job):\n \"\"\"Monitor the completion of BQ Job which does produce some result\n (usually data insertion).\n\n :param bq_params: bq params from yaml config file\n :param client: BQ api object, allowing for execution of bq lib functions\n :param table_id: table id in standard SQL format\n :param bq_job: A Job object, responsible for executing bq function calls\n \"\"\"\n last_report_time = time.time()\n location = bq_params['LOCATION']\n job_state = \"NOT_STARTED\"\n\n while job_state != 'DONE':\n bq_job = client.get_job(bq_job.job_id, location=location)\n\n if time.time() - last_report_time > 30:\n console_out('\\tcurrent job state: {0}...\\t', (bq_job.state,), end='')\n last_report_time = time.time()\n\n job_state = bq_job.state\n\n if job_state != 'DONE':\n time.sleep(2)\n\n bq_job = client.get_job(bq_job.job_id, location=location)\n\n if bq_job.error_result is not None:\n has_fatal_error(\n 'While running BQ job: {}\\n{}'.format(bq_job.error_result, bq_job.errors),\n ValueError)\n\n table = client.get_table(table_id)\n console_out(\" done. {0} rows inserted.\", (table.num_rows,))\n\n\ndef await_job(bq_params, client, bq_job):\n \"\"\"Monitor the completion of BQ Job which doesn't return a result.\n\n :param bq_params: bq params from yaml config file\n :param client: BQ api object, allowing for execution of bq lib functions\n :param bq_job: A Job object, responsible for executing bq function calls\n \"\"\"\n location = bq_params['LOCATION']\n job_state = \"NOT_STARTED\"\n\n while job_state != 'DONE':\n bq_job = client.get_job(bq_job.job_id, location=location)\n\n job_state = bq_job.state\n\n if job_state != 'DONE':\n time.sleep(2)\n\n bq_job = client.get_job(bq_job.job_id, location=location)\n\n if bq_job.error_result is not None:\n err_res = bq_job.error_result\n errs = bq_job.errors\n has_fatal_error(\"While running BQ job: {}\\n{}\".format(err_res, errs))\n\n\ndef from_schema_file_to_obj(bq_params, filename):\n \"\"\"\n Open table schema file and convert to python dict, in order to pass the data to\n BigQuery for table insertion.\n\n :param bq_params: bq param object from yaml config\n :param filename: name of the schema file\n :return: schema list, table metadata dict\n \"\"\"\n\n fp = get_filepath(bq_params['SCHEMA_DIR'], filename)\n # todo changed this, does it work?\n\n if not os.path.exists(fp):\n return None, None\n\n with open(fp, 'r') as schema_file:\n try:\n schema_file = json.load(schema_file)\n\n schema = schema_file['schema']['fields']\n\n table_metadata = {\n 'description': schema_file['description'],\n 'friendlyName': schema_file['friendlyName'],\n 'labels': schema_file['labels']\n }\n except FileNotFoundError:\n return None, None\n\n return schema, table_metadata\n\n\ndef to_bq_schema_obj(schema_field_dict):\n \"\"\"Convert schema entry dict to SchemaField object.\n\n :param schema_field_dict: dict containing schema field keys\n (name, field_type, mode, fields, description)\n :return: bigquery.SchemaField object\n \"\"\"\n return bigquery.SchemaField.from_api_repr(schema_field_dict)\n\n\ndef generate_bq_schema(schema_dict, record_type, expand_fields_list):\n \"\"\"Generates BigQuery SchemaField list for insertion of case records.\n\n :param schema_dict: dict of schema fields\n :param record_type: type of field/field group\n :param expand_fields_list: list of field groups included in API request\n :return: list of SchemaFields for case record insertion\n \"\"\"\n # add fields to a list in order to generate a dict representing nested fields\n field_group_names = [record_type]\n nested_depth = 0\n\n for field_group in expand_fields_list.split(','):\n nested_field_name = record_type + '.' + field_group\n nested_depth = max(nested_depth, len(nested_field_name.split('.')))\n field_group_names.append(nested_field_name)\n\n record_lists_dict = {field_grp_name: [] for field_grp_name in field_group_names}\n # add field to correct field grouping list based on full field name\n for field in schema_dict:\n # record_lists_dict key is equal to the parent field components of\n # full field name\n record_lists_dict[get_field_group(field)].append(schema_dict[field])\n\n temp_schema_field_dict = {}\n\n while nested_depth >= 1:\n for field_group_name in record_lists_dict:\n split_group_name = field_group_name.split('.')\n\n # builds from max depth inward to avoid iterating through entire schema obj\n # in order to append child field groups. Skip any shallower field groups.\n if len(split_group_name) != nested_depth:\n continue\n\n schema_field_sublist = []\n\n for record in record_lists_dict[field_group_name]:\n schema_field_sublist.append(\n bigquery.SchemaField(name=record['name'],\n field_type=record['type'],\n mode='NULLABLE',\n description=record['description'],\n fields=()))\n\n parent_name = get_field_group(field_group_name)\n\n if field_group_name in temp_schema_field_dict:\n schema_field_sublist += temp_schema_field_dict[field_group_name]\n\n if parent_name:\n if parent_name not in temp_schema_field_dict:\n temp_schema_field_dict[parent_name] = list()\n\n temp_schema_field_dict[parent_name].append(\n bigquery.SchemaField(name=get_field_name(field_group_name),\n field_type='RECORD',\n mode='REPEATED',\n description='',\n fields=tuple(schema_field_sublist)))\n else:\n if nested_depth > 1:\n has_fatal_error(\"Empty parent_name at level {}\"\n .format(nested_depth), ValueError)\n return schema_field_sublist\n\n nested_depth -= 1\n return None\n\n\ndef update_table_metadata(table_id, metadata):\n \"\"\"Modify an existing BQ table with additional metadata.\n\n :param table_id: table id in standard SQL format\n :param metadata: metadata containing new field and table attributes\n \"\"\"\n client = bigquery.Client()\n table = get_bq_table_obj(table_id)\n\n table.labels = metadata['labels']\n table.friendly_name = metadata['friendlyName']\n table.description = metadata['description']\n client.update_table(table, [\"labels\", \"friendly_name\", \"description\"])\n\n assert table.labels == metadata['labels']\n assert table.friendly_name == metadata['friendlyName']\n assert table.description == metadata['description']\n\n\ndef update_friendly_name(bq_params, table_id, custom_name=None):\n \"\"\"Modify a table's friendly name metadata.\n\n :param bq_params: bq param object from yaml config\n :param table_id: table id in standard SQL format\n :param custom_name: By default, appends \"'REL' + bq_params['RELEASE'] + ' VERSIONED'\"\n onto the existing friendly name. If custom_name is specified, this behavior is\n overridden, and the table's friendly name is replaced entirely.\n \"\"\"\n client = bigquery.Client()\n table = get_bq_table_obj(table_id)\n\n if custom_name:\n new_name = custom_name\n else:\n new_name = table.friendly_name + ' REL' + bq_params['RELEASE'] + ' VERSIONED'\n\n table.friendly_name = new_name\n client.update_table(table, [\"friendly_name\"])\n\n assert table.friendly_name == new_name\n\n\ndef update_schema(table_id, new_descriptions):\n \"\"\"Modify an existing table's field descriptions.\n\n :param table_id: table id in standard SQL format\n :param new_descriptions: dict of field names and new description strings\n \"\"\"\n client = bigquery.Client()\n table = get_bq_table_obj(table_id)\n\n new_schema = []\n\n for schema_field in table.schema:\n field = schema_field.to_api_repr()\n\n if field['name'] in new_descriptions.keys():\n name = field['name']\n field['description'] = new_descriptions[name]\n elif field['description'] == '':\n console_out(\"Still no description for field: {0}\", (field['name']))\n\n mod_field = bigquery.SchemaField.from_api_repr(field)\n new_schema.append(mod_field)\n\n table.schema = new_schema\n\n client.update_table(table, ['schema'])\n\n\n# (NON-BQ) GOOGLE CLOUD API HELPERS\n\n\ndef upload_file_to_bucket(project, bucket, blob_dir, fp):\n \"\"\"\n todo\n :param project:\n :param bucket:\n :param blob_dir:\n :param fp:\n :return:\n \"\"\"\n try:\n client = storage.Client(project=project)\n bucket = client.get_bucket(bucket)\n blob = bucket.blob(blob_dir)\n\n blob.upload_from_file(fp)\n except exceptions.GoogleCloudError as err:\n has_fatal_error(\"Failed to upload to bucket.\\n{}\".format(err))\n\n\ndef upload_to_bucket(bq_params, scratch_fp):\n \"\"\"Uploads file to a google storage bucket (location specified in yaml config).\n\n :param bq_params: bq param object from yaml config\n :param scratch_fp: name of file to upload to bucket\n \"\"\"\n\n try:\n storage_client = storage.Client(project=\"\")\n\n jsonl_output_file = scratch_fp.split('/')[-1]\n blob_name = \"{}/{}\".format(bq_params['WORKING_BUCKET_DIR'], jsonl_output_file)\n bucket = storage_client.bucket(bq_params['WORKING_BUCKET'])\n blob = bucket.blob(blob_name)\n\n blob.upload_from_filename(scratch_fp)\n except exceptions.GoogleCloudError as err:\n has_fatal_error(\"Failed to upload to bucket.\\n{}\".format(err))\n\n\ndef download_from_bucket(bq_params, filename):\n storage_client = storage.Client(project=\"\")\n blob_name = \"{}/{}\".format(bq_params['WORKING_BUCKET_DIR'], filename)\n bucket = storage_client.bucket(bq_params['WORKING_BUCKET'])\n blob = bucket.blob(blob_name)\n\n scratch_fp = get_scratch_fp(bq_params, filename)\n with open(scratch_fp, 'wb') as file_obj:\n blob.download_to_file(file_obj)\n\n\n# ANALYZE DATA\n\n\ndef check_value_type(value):\n \"\"\"Checks value for type (possibilities are string, float and integers).\n\n :param value: value to type check\n :return: type in BQ column format\n \"\"\"\n # if has leading zero, then should be considered a string, even if only\n # composed of digits\n val_is_none = value in ('NA', 'null', 'None') or not value\n val_is_bool = value in ('True', 'False', True, False)\n val_is_decimal = value.startswith('0.')\n val_is_id = value.startswith('0') and not val_is_decimal and len(value) > 1\n\n try:\n float(value)\n val_is_num = True\n # Changing this because google won't accept loss of precision in the\n # data insert job\n # (won't cast 1.0 as 1)\n val_is_float = not value.isdigit()\n # If this is used, a field with only trivial floats will be cast as\n # Integer. However, BQ errors due to loss\n # of precision.\n # val_is_float = True if int(float(value)) != float(value) else False\n except ValueError:\n val_is_num = False\n val_is_float = False\n\n if val_is_none:\n return None\n if val_is_id:\n return 'STRING'\n if val_is_decimal or val_is_float:\n return 'FLOAT'\n if val_is_num:\n return 'INTEGER'\n if val_is_bool:\n return 'BOOLEAN'\n\n return 'STRING'\n\n\ndef collect_values(fields, field, parent, field_grp_prefix):\n \"\"\"Recursively inserts sets of values for a given field into return dict (\n used to infer field data type).\n\n :param fields: A dict of key:value pairs -- {field_name: set(field_values)}\n :param field: field name\n :param parent: dict containing field and it's values\n :param field_grp_prefix: string representation of current location in field hierarchy\n :return: field_dict containing field names and a set of its values\n \"\"\"\n # If the value of parent_dict[key] is a list at this level, and a dict at the next\n # (or a dict at this level, as seen in second conditional statement),\n # iterate over each list element's dictionary entries. (Sometimes lists are composed\n # of strings rather than dicts, and those are later converted to strings.)\n field_name = field_grp_prefix + field\n new_prefix = field_name + '.'\n\n if isinstance(parent[field], list) \\\n and len(parent[field]) > 0 and isinstance(parent[field][0], dict):\n for dict_item in parent[field]:\n for dict_key in dict_item:\n fields = collect_values(fields, dict_key, dict_item, new_prefix)\n elif isinstance(parent[field], dict):\n for dict_key in parent[field]:\n fields = collect_values(fields, dict_key, parent[field], new_prefix)\n else:\n if field_name not in fields:\n fields[field_name] = set()\n\n # This type of list can be converted to a comma-separated value string\n if isinstance(parent[field], list):\n value = \", \".join(parent[field])\n else:\n value = parent[field]\n\n fields[field_name].add(value)\n\n return fields\n\n\ndef infer_data_types(flattened_json):\n \"\"\"Infer data type of fields based on values contained in dataset.\n\n :param flattened_json: file containing dict of {field name: set of field values}\n :return: dict of field names and inferred type (None if no data in value set)\n \"\"\"\n data_types = dict()\n\n for column in flattened_json:\n data_types[column] = None\n\n for value in flattened_json[column]:\n if data_types[column] == 'STRING':\n break\n\n # adding this change because organoid submitter_ids look like\n # ints, but they should be str for uniformity\n if column[-2:] == 'id':\n data_types[column] = 'STRING'\n break\n\n val_type = check_value_type(str(value))\n\n if not val_type:\n continue\n if val_type in ('FLOAT', 'STRING') or (\n val_type in ('INTEGER', 'BOOLEAN') and not data_types[column]):\n data_types[column] = val_type\n\n return data_types\n\n\ndef get_sorted_fg_depths(record_counts, reverse=False):\n \"\"\"Returns a sorted dict of field groups: depths.\n\n :param record_counts: dict containing field groups and associated record counts\n :param reverse: if True, sort in DESC order, otherwise sort in ASC order\n :return: tuples composed of field group names and record counts\n \"\"\"\n table_depths = {table: len(table.split('.')) for table in record_counts}\n\n return sorted(table_depths.items(), key=lambda item: item[1], reverse=reverse)\n\n\n# MISC UTILITIES\n\n\ndef format_seconds(seconds):\n if seconds > 3600:\n return time.strftime(\"%-H hours, %-M minutes, %-S seconds\", time.gmtime(seconds))\n if seconds > 60:\n return time.strftime(\"%-M minutes, %-S seconds\", time.gmtime(seconds))\n\n return time.strftime(\"%-S seconds\", time.gmtime(seconds))\n\n\ndef convert_dict_to_string(obj):\n \"\"\"Converts dict/list of primitives or strings to a comma-separated string. Used\n to write data to file.\n\n :param obj: object to converts\n :return: modified object\n \"\"\"\n if isinstance(obj, list):\n if not isinstance(obj[0], dict):\n str_list = ', '.join(obj)\n obj = str_list\n else:\n for idx, value in enumerate(obj.copy()):\n obj[idx] = convert_dict_to_string(value)\n elif isinstance(obj, dict):\n for key in obj:\n obj[key] = convert_dict_to_string(obj[key])\n return obj\n\n\ndef load_config(args, yaml_dict_keys):\n \"\"\"Opens yaml file and retrieves configuration parameters.\n\n :param args: args param from python bash cli\n :param yaml_dict_keys: tuple of strings representing a subset of the yaml file's\n top-level dict keys\n :return: tuple of dicts from yaml file (as requested in yaml_dict_keys)\n \"\"\"\n if len(args) != 2:\n has_fatal_error('Usage: {} <configuration_yaml>\".format(args[0])', ValueError)\n\n yaml_file_arg = args[1]\n\n with open(yaml_file_arg, mode='r') as yaml_file_arg:\n\n yaml_dict = None\n\n config_stream = io.StringIO(yaml_file_arg.read())\n\n try:\n yaml_dict = yaml.load(config_stream, Loader=yaml.FullLoader)\n except yaml.YAMLError as ex:\n has_fatal_error(ex, str(yaml.YAMLError))\n if yaml_dict is None:\n has_fatal_error(\"Bad YAML load, exiting.\", ValueError)\n\n # Dynamically generate a list of dictionaries for the return statement,\n # since tuples are immutable\n return_dicts = [yaml_dict[key] for key in yaml_dict_keys]\n\n return tuple(return_dicts)\n\n\ndef has_fatal_error(err, exception=None):\n \"\"\"Error handling function--outputs error str or list<str>;\n optionally throws Exception as well.\n\n :param err: error message str or list<str>\n :param exception: Exception type for error (defaults to None)\n \"\"\"\n err_str_prefix = '[ERROR] '\n err_str = ''\n\n if isinstance(err, list):\n for item in err:\n err_str += err_str_prefix + str(item) + '\\n'\n else:\n err_str = err_str_prefix + err\n\n console_out(err_str)\n\n if exception:\n raise exception\n\n sys.exit(1)\n\n\ndef console_out(output_str, print_vars=None, end='\\n'):\n \"\"\"\n todo\n :param output_str:\n :param print_vars:\n :param end:\n :return:\n \"\"\"\n if print_vars:\n print(str(output_str).format(*print_vars), end=end)\n else:\n print(output_str, end=end)\n\n\ndef modify_fields_for_app(api_params, schema, column_order_dict, columns):\n \"\"\"Alter field naming conventions so that they're compatible with those in the\n web app.\n\n :param api_params: api param object from yaml config\n :param schema: dict containing schema records\n :param column_order_dict: dict of {field_groups: column_order set()}\n :param columns: dict containing table column keys\n \"\"\"\n renamed_fields = dict(api_params['RENAMED_FIELDS'])\n fgs = column_order_dict.keys()\n\n excluded_fgs = get_excluded_field_groups(api_params)\n excluded_fields = get_excluded_fields_all_fgs(api_params, fgs, is_webapp=True)\n\n for fg in fgs:\n # rename case_id no matter which fg it's in\n for renamed_field in renamed_fields.keys():\n if renamed_field in column_order_dict[fg]:\n new_field = renamed_fields[renamed_field]\n column_order_dict[fg][new_field] = column_order_dict[fg][renamed_field]\n column_order_dict[fg].pop(renamed_field)\n if fg in columns and renamed_field in columns[fg]:\n columns[fg].add(renamed_fields[renamed_field])\n columns[fg].remove(renamed_field)\n\n # field is fully associated name\n for field in {k for k in schema.keys()}:\n base_fg = \".\".join(field.split('.')[:-1])\n field_name = field.split('.')[-1]\n\n # substitute base field name for prefixed\n schema[field]['name'] = field_name\n\n # exclude any field groups or fields explicitly excluded in yaml\n if field in excluded_fields or base_fg in excluded_fgs:\n schema.pop(field)\n # field exists in renamed_fields, change its name\n elif field in renamed_fields:\n new_field = renamed_fields[field]\n\n schema[field]['name'] = new_field.split('.')[-1]\n schema[new_field] = schema[field]\n schema.pop(field)\n\n # change the field name in the column order dict\n if base_fg in column_order_dict and field in column_order_dict[base_fg]:\n column_order_dict[base_fg][new_field] = column_order_dict[base_fg][field]\n column_order_dict[base_fg].pop(field)\n\n if field in excluded_fields and base_fg in column_order_dict:\n # remove excluded field from column order lists\n if field in column_order_dict[base_fg]:\n column_order_dict[base_fg].pop(field)\n\n\ndef create_tsv_row(row_list, null_marker=\"None\"):\n print_str = ''\n last_idx = len(row_list) - 1\n\n for i, column in enumerate(row_list):\n if not column:\n column = null_marker\n\n delimiter = \"\\t\" if i < last_idx else \"\\n\"\n print_str += column + delimiter\n\n return print_str\n","sub_path":"common_etl/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":57502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"324269613","text":"# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, include, url\n\nfrom . import views\nfrom django.views.decorators.csrf import csrf_exempt\n\nurlpatterns = patterns('',\n url('^initiatives/(?P<pk>\\d+)/$', views.InitiativeDetailView.as_view(),\n name='initiative_detail'),\n\n url('^initiatives/(?P<pk>\\d+)/edit/$', views.InitiativeEditView.as_view(),\n name='initiative_edit'),\n\n url('^api/v1/municipalities$', views.MunicipalityListApiView.as_view(),\n name='municipalities_list'),\n\n url('^services/nua/1.0/create$', csrf_exempt(views.CreateInitivateApiView.as_view()),\n name='create_initiative')\n)","sub_path":"kuaapi/simulation/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"140719470","text":"import PresetModel\nfrom tkinter import messagebox\nimport tkinter\nimport os\nimport InventorySlot\nimport UserWarnings\n\nclass PresetHandler:\n def __init__(self):\n self.targetModel = PresetModel.PresetModel()\n self.model = None\n self.f = None\n self.basicData = dict()\n \"\"\"self.filename = \"default.preset\"\n self.filepath = \".\"\n self.defaultKey = True\n self.key = 'q'\n self.afkmessage = \"afk\"\n self.inventoryData = dict()\"\"\"\n\n def __str__(self):\n return str(self.inventoryData)\n\n def loadFile(self, filepath, filename, combined=False):\n try: \n if combined:\n constr = filepath\n tmp = filepath.split(\"/\")\n self.filename = tmp[-1]\n '/'.join(tmp[:-1])\n else:\n self.filename = filename\n self.filepath = filepath\n constr = self.filepath + \"/\" + self.filename\n for line in open(constr):\n sep = line.split(' ')\n if sep[0][-1]!=':':\n print(\"[E] Fehler beim Laden der Vorlagenzeile:\", line)\n raise ValueError\n firstWord = sep[0][:-1]\n if firstWord==\"data\":\n slot = self.readInventoryLine(sep)\n self.targetModel.addSlot(slot)\n else:\n rest = ' '.join(sep[1:])\n if rest[-1]=='\\n':\n self.basicData[firstWord] = rest[:-1]\n else:\n self.basicData[firstWord] = rest\n\n print(self.basicData)\n\n for ele in self.basicData:\n self.targetModel.set(ele, self.basicData[ele])\n\n return self.targetModel\n except:\n UserWarnings.showBrokenPresetError()\n return \"Error occurred\"\n\n\n def readInventoryLine(self, lineToRead):\n #Error Handling muss in Aufruffunktion gemacht werden!\n #data: 1 32 500 bea con\n #data: slot Anzahl Preis Material\n #lineToRead = ['data:', '1', '32', '500', 'bea', con']\n newSlot = InventorySlot.InventorySlot()\n newSlot.setPosition(int(lineToRead[1]))\n newSlot.setCount(int(lineToRead[2]))\n newSlot.setPrice(int(lineToRead[3]))\n newSlot.setItem(' '.join(lineToRead[4:]))\n return newSlot\n\n\n def get(self, what):\n pass\n \"\"\"if self.data[what]==None:\n print(\"[E] Angeforderten Datenwert in der aktuellen Config nicht gefunden:\", what)\n return\n return self.data[what]\"\"\"\n\n def setModel(self, model):\n self.model = model\n\n def deleteFile(self, model):\n strin = model.get(\"filepath\") + \"/\" + model.get(\"filename\")\n os.remove(strin)\n\n def saveToFile(self, model=None):\n if model != None:\n self.model = model\n print(self.model)\n \n composed = self.model.get(\"filepath\") + \"/\" + self.model.get(\"filename\")\n self.f = open(composed, \"w+\")\n for element in self.model.data:\n appen = str(element) + \": \" + str(self.model.get(element)) + \"\\n\"\n self.f.write(appen)\n for slott in self.model.getASlotlist():\n if slott != None:\n appen = \"data: \" + str(slott.getPosition()) + \" \" + str(slott.getCount()) + \" \" + str(slott.getPrice()) + \" \" + str(slott.getItem())\n self.f.write(appen)\n self.f.close()","sub_path":"release/GrieferBOT2_01/PresetHandler.py","file_name":"PresetHandler.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"271528252","text":"#coding:utf8\n\nfrom flask import Flask\nfrom functions import loadClass\napp=Flask(__name__)\n\n@app.route('/<version>/<method>/<controller>/',\n methods=['GET','POST','PUT','DELETE'])\ndef index(version,method,controller):\n getClass=loadClass(version, controller)\n do=getattr(getClass(),'do') \n return do()\n\n@app.after_request\ndef add_headers(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response\n\n\napp.run(\"10.10.10.13\", 9090, debug=True)\n\n","sub_path":"api/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"401764032","text":"from django.shortcuts import render, get_object_or_404\n\nfrom .models import Post, Categoria\n\n\ndef lista_posts(request):\n # Ordenar los post por fecha descendentemente order_by('')\n posts = Post.objects.all().order_by('-fecha')\n # Tambien devolver los post destacados en otra variable\n posts_destacados = Post.objects.filter(destacado=True)\n # Tambien devolver las categorias\n categorias = Categoria.objects.all()\n return render(request, 'blog/lista_posts.html',\n {'posts': posts,\n 'posts_destacados': posts_destacados,\n 'categorias': categorias})\n\n\ndef detalle_post(request, pk):\n post = get_object_or_404(Post, pk=pk)\n return render(request, 'blog/detalle_post.html',\n {'post': post})\n\n\ndef posts_categoria(request, pk):\n categoria = get_object_or_404(Categoria, pk=pk)\n posts = Post.objects.filter(categoria=categoria).order_by('-fecha')\n posts_destacados = Post.objects.filter(destacado=True)\n categorias = Categoria.objects.all()\n return render(request, 'blog/lista_posts.html',\n {'posts': posts,\n 'posts_destacados': posts_destacados,\n 'categorias': categorias})\n","sub_path":"devdiary/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"99489052","text":"print('api包的init文件')\r\n__all__=['x','y','policy','versions']\r\nfrom . import policy\r\nx=1\r\ny=2\r\n# policy=123123123123\r\n# versions='123123123'\r\n\r\n\r\n#import policy#以test.py的sys.path为准,不能在包内导入自己的模块\r\n\r\n#绝对导入\r\n#from glance.api import policy\r\n# from glance.api import versions\r\n\r\n#相对导入\r\n#\r\n# from . import policy,versions #推荐\r\n#\r\n#from ..cmd.manage import main #导入上一级目录的\r\n\r\n\r\n# /home/zzl/PycharmProjects/py_fullstack_s4/day35/packeage/glance/api","sub_path":"py_fullstack_s4/day35/aaa/glance/api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"480609318","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(r'C:\\Users\\HP\\PycharmProjects\\Learn1\\input.jpg',0)\nheight,width = img.shape\n\n#Extract sobel edges\nsobel_x = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)\nsobel_y = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)\n\n\ncv2.imshow('original',img)\ncv2.waitKey()\ncv2.imshow('sobel_x',sobel_x)\ncv2.waitKey()\ncv2.imshow('sobel_y',sobel_y)\ncv2.waitKey()\n\nsobel_or = cv2.bitwise_or(sobel_x,sobel_y)\ncv2.imshow('sobel_or',sobel_or)\ncv2.waitKey()\n\nimg_laplacian = cv2.Laplacian(img,cv2.CV_64F)\ncv2.imshow('Laplacian',img_laplacian)\ncv2.waitKey()\n\nimg_canny = cv2.Canny(img,20,130)\ncv2.imshow('Canny',img_canny)\ncv2.waitKey()\ncv2.destroyAllWindows()\n","sub_path":"edge_detect.py","file_name":"edge_detect.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"249759133","text":"from flask import Flask, request\nfrom flask_cors import CORS\nimport records \nimport sqlite3\nimport os \nimport time \n\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\n\ndef connDB(): \n return records.Database('mysql://root:5DH9awkIaNralLnd@127.0.0.1/bquest')\n\n\n\ndef getStatus( deedID ): \n db = connDB()\n\n q = \"SELECT status from Deeds where deedID = %d \" % deedID\n res = db.query(q).scalar()\n\n return res\n\n\n\ndef saveImg( deedID, image ): \n status = getStatus( deedID )\n if status == 1: \n path = \"./request-%d.png\" % deedID\n else: \n path = \"./deed-%d.png\" % deedID\n \n f = open( path, \"wb\")\n\n f.write( bytes(image) ) \n f.close()\n\ndef getImg( deedID ): \n status = getStatus( deedID )\n if status == 1: \n path = \"./request-%d.png\" % deedID\n else: \n path = \"./deed-%d.png\" % deedID\n f = open( path, \"rb\")\n img = f.read()\n f.close()\n return img \n\n\n@app.route('/')\ndef info():\n return \"beneQuest API written by Tyler Beverley, And Brandon Tran.\"\n\n@app.route('/addRequest', methods = ['POST'])\ndef addRequest():\n db = connDB()\n\n content = request.get_json(force=True)\n \n #Create a new request\n UserID = content['userID']\n Description = content['description']\n Lat = float(content['lat'])\n Long = float(content['long'])\n Img = content['image']\n Timestamp = time.time() \n q = \"\"\"INSERT INTO Deeds(requesterID, description, latitude, longitude, timestamp, upvotes, status) \n VALUES(\"%s\",\"%s\",%f,%f,%d,1,0);\"\"\" % (UserID, Description, Lat, Long, Timestamp)\n db.query(q)\n print(\"hello there\")\n\n last = \"SELECT MAX(deedID) from Deeds;\"\n res = db.query(last).scalar()\n\n saveImg( res, Img )\n return { \n \"deedID\": res\n }\n \n\n@app.route('/addDeed', methods = ['POST'])\ndef addDeed():\n db = connDB()\n\n content = request.get_json(force=True)\n print(content)\n\n #Create new request\n\n DeedID = int(content['deedID'])\n UserID = content['userID']\n Img = bytes(content['image'])\n q = \"\"\"INSERT INTO Done(userID,deedID) VALUES (%s,%d)\"\"\" % (UserID, DeedID)\n q2 = \"\"\"UPDATE Deed SET status=1 WHERE deedID = %d\"\"\" % DeedID\n\n check = \"SELECT status FROM Deeds WHERE deedID = (%d)\" % (DeedID)\n row = db.query(check)\n\n #There is no deed\n if( row.status == 1):\n print(\"Error: DeedID %d does not exist\" % (DeedID)) \n #There is a deed to complete\n else:\n db.query(q)\n db.query(q2)\n\n return \"200\"\n\n@app.route('/newUser', methods = ['GET'])\ndef newUser(): \n db = connDB()\n q = \"SELECT MAX(userID) +1 from Users\"\n newID = db.query(q).scalar()\n\n return str(newID)\n\n\n@app.route('/addUser', methods = ['POST'])\ndef addUser():\n db = connDB()\n\n content = request.get_json(force=True)\n print(content)\n\n UserID = content['userID']\n qcheck = \"SELECT * FROM Users WHERE userID = %s\" % (UserID)\n check = db.query(qcheck)\n if(check):\n print(\"Error: userID %s already exists\" % userID)\n else:\n #Need to have a default emoji set\n q = \"\"\" INSERT INTO User(userID,emoji) VALUES (%s,128512)\"\"\" % (UserID)\n db.query(q)\n\n return \"200\"\n\n\n@app.route('/upvote', methods = ['UPDATE'])\ndef upvote():\n db = connDB()\n content = request.get_json(force=True)\n\n DeedID = int(content['deedID'])\n UserID = content['userID']\n\n row = db.query(\"SELECT * FROM Upvote WHERE deedID = %d AND userID = %s\" % (DeedID,UserID))\n #Already Exists\n if(row):\n error = \"User %s has already upvoted Deed %d\" % (UserID, DeedID)\n #Create new entry\n else:\n db.query(\"INSERT INTO Upvote(userID, deedID) VALUES(%s,%d)\" % (UserID, DeedID))\n prev = db.query(\"SELECT upvotes FROM Deeds WHERE deedID = %d\" % (DeedID)).scalar()\n db.query(\"UPDATE Deeds SET upvotes = %d WHERE deedID = %d\" % (prev +1 ,DeedID))\n return \"200\"\n\n@app.route('/updateUser', methods = ['UPDATE'])\ndef updateUser():\n db = connDB()\n content = request.get_json(force=True)\n\n UserID = content['userID']\n Emoji = content['emoji']\n\n qcheck = \"SELECT * FROM Users WHERE userID = (%s)\" % (UserID)\n q = \"UPDATE Users SET emoji = %s WHERE userID = %s\" % (Emoji,UserID)\n\n\n check = db.query(qcheck)\n if(not check):\n print(\"Error: UserID %s does not exist\" % (UserID))\n else:\n db.query(q)\n\n return \"200\" \n\n@app.route('/requestsNear', methods = ['POST'])\ndef requestsNear():\n db = connDB()\n content = request.get_json(force=True)\n\n\n Lat = float(content['lat'])\n Long = float(content['long'])\n radius = 5.0\n\n q = \"\"\" SELECT * FROM Deed WHERE lat > %f\n AND lat < %f AND long > $f AND\n long < %f AND status = 0 \"\"\" % (Lat-radius,Lat+radius,Long-radius,Long+radius)\n #Not sure what we want as near\n\n row = db.query(q)\n requests = list(map (lambda r: r.deedID), record.row.all())\n return {\n \"numOfRequests\": len( requests ),\n \"deeds\": requests\n }\n\n@app.route('/allRequestsNear', methods = ['POST'])\ndef allRequestsNear():\n content = request.get_json(force=True)\n db = connDB()\n\n UserID = content['userID']\n\n rows = db.query(\"SELECT * FROM Deeds where status = 0;\")\n requests = list(map( (lambda r: r.as_dict()), rows.all() ))\n return { \n \"numRecords\": len(requests),\n \"records\": requests\n }\n\n@app.route(\"/weeklyHeros\", methods = ['POST'])\ndef weeklyHeros():\n db = connDB()\n q = \"\"\" SELECT sum(upvotes) as exp, userID, emoji FROM (\n SELECT *\n FROM Deeds\n NATURAL JOIN Done\n NATURAL JOIN Users\n ) GROUP BY userID\n ORDER BY exp\n LIMIT 10;\n \"\"\"\n row = db.query(q)\n heros = list(map( (lambda r: r.userID), record.row.all()))\n return {\n \"numOfHeros\": len( heros ),\n \"users\": heros\n }\n\n\n\n@app.route('/<userID>/upvotes', methods =['POST'])\ndef upvotes( userID ): \n db = connDB()\n q = \"SELECT deedID FROM Upvote where userID = %d\" % (userID)\n row = db.query(q)\n deeds = list(map( (lambda r: r.deedID), record.row.all() ))\n return { \n \"numOfUpvotes\": len( deeds ), \n \"deeds\": deeds\n }\n\n@app.route(\"/<userID>/doneDeeds\", methods = ['GET'])\ndef doneDeeds( userID ):\n db = connDB()\n\n q = \"SELECT deedID FROM Done WHERE userID = %d\" % (userID)\n row = db.query(q)\n deeds = list(map((lambda r: r.deedID), record.row.all()))\n return {\n \"numOfDeeds\": len( deeds ),\n \"deeds\": deeds\n }\n \n","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82868335","text":"#!/usr/bin/env python3\nimport math\nfrom io import StringIO\nimport numpy as np\nimport pandas as pd\nimport re\nimport cv2\nimport pytesseract\n\n\ndef preprocessing_pipeline(img):\n # Double image size\n image_resized = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)\n # Turn to grayscale\n gray = cv2.cvtColor(image_resized, cv2.COLOR_BGR2GRAY)\n # Turn to black/white\n _, thresh = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY_INV)\n\n return thresh\n\n\ndef extract_pars(block_frame):\n pars = block_frame.par_num.unique()\n par_list = []\n for par in pars:\n par_list.append(block_frame[block_frame.par_num == par])\n return par_list\n\n\ndef extract_lines(par_frame):\n lines = par_frame.line_num.unique()\n line_list = []\n for line in lines:\n line_list.append(par_frame[par_frame.line_num == line])\n return line_list\n\n\ndef line_to_text(line_frame):\n return \" \".join(line_frame.text)\n\n\ndef postprocess_text(text):\n processed = text.lower()\n processed = re.sub(r\"[^A-Za-z0-9 ]+\", \"\", processed)\n return processed\n\n\ndef get_block(dframe, num):\n return dframe[dframe.block_num == num]\n\n\ndef rows_to_rect(frame, img_width, img_height):\n if len(frame) <= 0:\n return (0, 0, 0, 0)\n min_left = np.inf\n min_top = np.inf\n max_left = 0\n max_top = 0\n for _, row in frame.iterrows():\n start_point = (row.left, row.top)\n end_point = (start_point[0] + row.width, start_point[1] + row.height)\n if row.width > 0.5 * img_width or row.height > 0.5 * img_height:\n continue\n min_left = min(min_left, start_point[0])\n max_left = max(max_left, end_point[0])\n min_top = min(min_top, start_point[1])\n max_top = max(max_top, end_point[1])\n if min_left == np.inf or min_top == np.inf or max_left == 0 or max_top == 0:\n return (0, 0, 0, 0)\n return (min_left, min_top, max_left, max_top)\n\n\ndef add_2_blocks_func(dframe, img_width, img_height, line):\n block_num = line.block_num.iloc[0]\n block_1 = get_block(dframe, block_num + 1)\n block_2 = get_block(dframe, block_num + 2)\n return [\n rows_to_rect(block_1, img_width, img_height),\n rows_to_rect(block_2, img_width, img_height),\n ]\n\n\ndef add_1_blocks_func(dframe, img_width, img_height, line):\n block_num = line.block_num.iloc[0]\n block_1 = get_block(dframe, block_num + 1)\n return [rows_to_rect(block_1, img_width, img_height)]\n\n\ndef add_cur_block_func(dframe, img_width, img_height, line):\n block_num = line.block_num.iloc[0]\n block = get_block(dframe, block_num)\n rect = rows_to_rect(block, img_width, img_height)\n return [rect]\n\n\ndef add_cur_par_func(dframe, img_width, img_height, line):\n block_num = line.block_num.iloc[0]\n par_num = line.par_num.iloc[0]\n block = get_block(dframe, block_num)\n par = block[block.par_num == par_num]\n return [rows_to_rect(par, img_width, img_height)]\n\n\ndef add_cur_line_func(dframe, img_width, img_height, line_frame):\n return [rows_to_rect(line_frame, img_width, img_height)]\n\n\ndef add_form_rect(dframe, img_width, img_height, line):\n h_line = line.h_line_idx.iloc[0]\n v_line = line.v_line_idx.iloc[0]\n if not h_line or not v_line:\n return []\n rect_rows = dframe[(dframe.h_line_idx == h_line) & (dframe.v_line_idx == v_line)]\n return [rows_to_rect(rect_rows, img_width, img_height)]\n\n\ndef keyword_substr(text, keyword):\n return keyword in text\n\n\ndef keyword_isword(text, keyword):\n if keyword in text.split():\n print(\"found keyword \" + keyword)\n return keyword in text.split()\n\n\ndef get_blacken_rects(dframe, img_width, img_height):\n blacken_rects = []\n par_rects = []\n keyword_funcs = [\n (\"kunde\", keyword_substr, add_2_blocks_func),\n (\"telefon\", keyword_isword, add_cur_line_func),\n (\"telefax\", keyword_isword, add_cur_line_func),\n (\"fax\", keyword_isword, add_cur_line_func),\n (\"tel\", keyword_isword, add_cur_line_func),\n (\"fahrzeug\", keyword_isword, add_1_blocks_func),\n (\"gmbh\", keyword_isword, add_cur_block_func),\n ]\n block_nums = dframe.block_num.unique()\n for block_num in block_nums:\n cur_block = get_block(dframe, block_num)\n pars = extract_pars(cur_block)\n for par in pars:\n par_rects.append(rows_to_rect(par))\n lines = extract_lines(par)\n for line in lines:\n line = line[line.text.notna()]\n text = line_to_text(line)\n text = postprocess_text(text)\n for keyword, keyword_check, func in keyword_funcs:\n if keyword_check(text, keyword):\n blacken_rects += func(dframe, img_width, img_height, line)\n return blacken_rects, par_rects\n\n\ndef extractLines(img):\n # Preprocessing: Grayscale + Otsu\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\n\n # Detect long horizontal lines\n horizontal_lines = []\n horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1))\n detect_horizontal = cv2.morphologyEx(\n thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2\n )\n cnts = cv2.findContours(\n detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE\n )\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for c in cnts:\n x_min = np.inf\n x_max = 0\n y_avg = 0\n for point in c:\n x = point[0][0]\n y = point[0][1]\n x_min = min(x_min, x)\n x_max = max(x_max, x)\n y_avg += y\n y_avg /= len(c)\n y_avg = int(y_avg)\n start = (x_min, y_avg)\n end = (x_max, y_avg)\n horizontal_lines.append((start, end))\n\n # Detect long vertical lines\n vertical_lines = []\n vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 40))\n detect_vertical = cv2.morphologyEx(\n thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2\n )\n cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for c in cnts:\n y_min = np.inf\n y_max = 0\n x_avg = 0\n for point in c:\n y = point[0][1]\n x = point[0][0]\n y_min = min(y_min, y)\n y_max = max(y_max, y)\n x_avg += x\n x_avg /= len(c)\n x_avg = int(x_avg)\n start = (x_avg, y_min)\n end = (x_avg, y_max)\n vertical_lines.append((start, end))\n\n return horizontal_lines, vertical_lines\n\n\ndef contained_horizontal(line, rect):\n return rect[0][0] < line[1][0] and rect[1][0] > line[0][0]\n\n\ndef contained_vertical(line, rect):\n return rect[0][1] < line[1][1] and rect[1][1] > line[0][1]\n\n\ndef scale_rect(rect):\n return (int(rect[0] / 2), int(rect[1] / 2), int(rect[2] / 2), int(rect[3] / 2))\n\n\ndef classify_rects(df, horizontal_lines, vertical_lines):\n h_line_idxs = []\n v_line_idxs = []\n for _, row in df.iterrows():\n rect_start = (int(row.left / 2), int(row.top) / 2)\n rect_end = (int((row.left + row.width) / 2), int((row.top + row.height) / 2))\n rect = (rect_start, rect_end)\n h_y_max = 0\n h_line_max_idx = None\n for i, line in enumerate(horizontal_lines):\n y = line[0][1]\n if contained_horizontal(line, rect) and y < rect_end[1] and y > h_y_max:\n h_y_max = y\n h_line_max_idx = i\n h_line_idxs.append(h_line_max_idx)\n\n v_x_max = 0\n v_line_max_idx = None\n for i, line in enumerate(vertical_lines):\n x = line[0][0]\n if contained_vertical(line, rect) and x < rect_end[0] and x > v_x_max:\n v_x_max = x\n v_line_max_idx = i\n v_line_idxs.append(v_line_max_idx)\n df[\"h_line_idx\"] = h_line_idxs\n df[\"v_line_idx\"] = v_line_idxs\n return df\n\n\ndef get_blacken_rects_new(dframe, img_width, img_height):\n blacken_rects = []\n keyword_funcs = [\n (\"tel\", keyword_isword, add_form_rect),\n (\"kunde\", keyword_isword, add_form_rect),\n (\"gmbh\", keyword_isword, add_cur_block_func),\n (\"tel\", keyword_isword, add_cur_line_func),\n (\"fax\", keyword_isword, add_cur_line_func),\n (\"email\", keyword_isword, add_cur_line_func),\n (\"emall\", keyword_isword, add_cur_line_func),\n (\"www\", keyword_substr, add_cur_line_func),\n (\"werksbeauftragter\", keyword_isword, add_form_rect),\n (\"abholer\", keyword_isword, add_form_rect),\n (\"baustellennummer\", keyword_substr, add_form_rect),\n (\"webseite\", keyword_isword, add_cur_line_func),\n (\"website\", keyword_isword, add_cur_line_func),\n ]\n block_nums = dframe.block_num.unique()\n for block_num in block_nums:\n cur_block = get_block(dframe, block_num)\n pars = extract_pars(cur_block)\n for par in pars:\n lines = extract_lines(par)\n for line in lines:\n line = line[line.text.notna()]\n text = line_to_text(line)\n text = postprocess_text(text)\n for keyword, keyword_check, func in keyword_funcs:\n if keyword_check(text, keyword):\n blacken_rects += func(dframe, img_width, img_height, line)\n return blacken_rects\n\n\ndef detect_text(img):\n horizontal_lines, vertical_lines = extractLines(img)\n\n pipelined_img = preprocessing_pipeline(img)\n\n img_rgb = cv2.cvtColor(pipelined_img, cv2.COLOR_BGR2RGB)\n img_height, img_width, _ = img_rgb.shape\n\n # Run Tesseract OCR over the document and read result into pandas frame\n tess_data = StringIO(pytesseract.image_to_data(img_rgb))\n df = pd.read_csv(tess_data, sep=\"\\t\")\n\n # Cleanup\n df = df.replace(r\"^\\s*$\", np.nan, regex=True)\n block_counts = df.groupby(\"block_num\")[\"text\"].count()\n non_empty_blocks = block_counts[block_counts > 0].index\n df_filled_blocks = df[df.block_num.isin(non_empty_blocks)]\n\n df_postprocessed = classify_rects(\n df_filled_blocks, horizontal_lines, vertical_lines\n )\n\n rects = get_blacken_rects_new(df_postprocessed, img_width, img_height)\n rects = list(map(scale_rect, rects))\n\n return rects\n","sub_path":"src/text_detection.py","file_name":"text_detection.py","file_ext":"py","file_size_in_byte":10326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"576484987","text":"# Create your views here.\nfrom django.core.context_processors import csrf\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom WebPenetration.models import Tutorials, Exercises\n\n\ndef managertutorials(request):\n if request.user.is_authenticated():\n tutorials = Tutorials.objects.filter(ispublic=0)\n try:\n activeId = tutorials[0].id\n content = render_to_response(\n 'ESC', {'content': tutorials.filter(id=activeId)[0].content}).content\n except:\n activeId = -1\n content = ''\n currenturl = 'managertutorials'\n data = {\n 'currenturl': currenturl,\n 'activeid': activeId,\n 'tutorials': tutorials,\n 'content': content,\n }\n data.update(csrf(request))\n return render_to_response('managertutorials.html', data)\n else:\n return HttpResponse(status=404)\n\n\ndef managerexercise(request):\n if request.user.is_authenticated():\n exercises = Exercises.objects.filter(ispublic=0)\n typeList = []\n exerciseList = []\n for exercise in exercises:\n if exercise.type not in typeList:\n typeList.append(exercise.type)\n\n for type in typeList:\n sameTypeList = []\n for exercise in exercises:\n if exercise.type == type:\n sameTypeList.append(exercise)\n exerciseList.append(sameTypeList)\n currenturl = 'managerexercise'\n data = {\n 'currenturl': currenturl,\n 'exercises': exerciseList,\n }\n data.update(csrf(request))\n return render_to_response('managerexercise.html', data)\n else:\n return HttpResponse(status=404)\n\n\ndef managerlogin(request):\n return render_to_response('login.html')\n\n\ndef postmanagertutor(request):\n if request.user.is_authenticated():\n if request.method == 'POST':\n id = request.POST.get('id')\n pb = request.POST.get('pb')\n try:\n if pb == u'tutor' or pb == u'joyful' or pb == u'tutordelete':\n tutorial = Tutorials.objects.get(id=id)\n if pb == u'tutordelete' and tutorial.ispublic == 0:\n tutorial.delete()\n return HttpResponse('success')\n elif pb == u'tutor' and tutorial.ispublic == 0:\n tutorial.ispublic = 1\n tutorial.save()\n return HttpResponse('success')\n elif pb == u'joyful'and tutorial.ispublic == 0:\n tutorial.ispublic = 2\n tutorial.save()\n return HttpResponse('success')\n elif pb == u'exerc' or pb == u'exercdelete':\n exercise = Exercises.objects.get(id=id)\n if pb == u'exerc'and exercise.ispublic == 0:\n exercise.ispublic = 1\n exercise.save()\n return HttpResponse('success')\n elif pb == u'exercdelete' and exercise.ispublic == 0:\n exercise.delete()\n return HttpResponse('success')\n except:\n pass\n return HttpResponse('')\n else:\n return HttpResponse(status=404)\n","sub_path":"adminmanager/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403508915","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'ipetrash'\n\n\n# TODO: обоюдное выделеление текста в полях ввода\n# TODO: конвертирование в обе стороны\n\n\nif __name__ == '__main__':\n from os.path import split as path_split\n import traceback\n import sys\n\n from PySide.QtGui import *\n from PySide.QtCore import *\n\n import hex2str\n\n app = QApplication(sys.argv)\n\n mainWidget = QWidget()\n mainWidget.setWindowTitle(path_split(__file__)[1])\n\n layout = QVBoxLayout()\n\n text_edit_input = QPlainTextEdit()\n text_edit_output = QPlainTextEdit()\n\n last_select_start, last_select_end = None, None\n\n# def selection_changed():\n# \"\"\"Обновляем выделение у текстовых редакторов\"\"\"\n#\n# # text_edit_input -- hex значения\n# # text_edit_output -- строковые значения, каждые два hex представляютсяодним символом\n#\n#\n# # cursor.selectionEnd()\n# #\n# # QTextCursor::MoveAnchor\t0\tMoves the anchor to the same position as the cursor itself.\n# # QTextCursor::KeepAnchor\t1\tKeeps the anchor where it is.\n# #\n# # void QTextCursor::setPosition ( int pos, MoveMode m = MoveAnchor )\n# # bool QTextCursor::movePosition ( MoveOperation operation, MoveMode mode = MoveAnchor, int n = 1 )\n#\n# global last_select_start, last_select_end\n#\n# if text_edit_input.hasFocus():\n# cursor = QTextCursor(text_edit_input.textCursor())\n# start, end = cursor.selectionStart(), cursor.selectionEnd()\n# selection_len = len(cursor.selectedText())\n#\n# if selection_len == 0:\n# last_select_start, last_select_end = start, end\n# return\n#\n# if last_select_start == start and last_select_end == end:\n# return\n#\n# print('start={} end={} len={}'.format(start, end, selection_len)\n# + ' | ' + 'last_start={} last_end={}'.format(last_select_start, last_select_end))\n#\n# if last_select_end is not None and end >= last_select_end:\n# # if True:\n# n = selection_len\n# # # if n % 2 == 1 and n > 1:\n# # # n -= 1\n# # # elif n == 1:\n# # # n = 2\n#\n# cursor.setPosition(start, QTextCursor.MoveAnchor)\n#\n# # if n % 2 == 1 and start < last_select_start and last_select_start is not None:\n# # n += 1\n# # cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, n)\n#\n# # cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, n)\n#\n# # if n % 2 == 1 and start < last_select_start and last_select_start is not None:\n# # n += 1\n# if n % 2 == 1:\n# n += 1\n#\n# # print('r', selection_len, n)\n#\n# cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, n)\n# text_edit_input.setTextCursor(cursor)\n#\n# # elif last_select_start is not None and last_select_start < start:\n# elif last_select_start is not None and start < last_select_start:\n# n = selection_len\n# # # if n % 2 == 1 and n > 1:\n# # # n -= 1\n# # # elif n == 1:\n# # # n = 2\n#\n# cursor.setPosition(end, QTextCursor.MoveAnchor)\n#\n# # if n % 2 == 1 and start < last_select_start and last_select_start is not None:\n# # n += 1\n# # cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, n)\n#\n# # cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, n)\n#\n# # # if n % 2 == 1 and start < last_select_start and last_select_start is not None:\n# # # n += 1\n# # if n % 2 == 1:\n# # n -= 1\n#\n# cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, n)\n# text_edit_input.setTextCursor(cursor)\n#\n# last_select_start, last_select_end = start, end\n#\n# # if text_edit_input.hasFocus():\n# # cursor = QTextCursor(text_edit_input.textCursor())\n# #\n# # start, end = cursor.selectionStart(), cursor.selectionEnd()\n# #\n# # cursor.setPosition(start // 2, QTextCursor.MoveAnchor)\n# # cursor.movePosition(QTextCursor.Right if end > start else QTextCursor.Left, QTextCursor.KeepAnchor, (max(end, start) - min(end, start)) / 2)\n# #\n# # print(start, (max(end, start) - min(end, start)), (max(end, start) - min(end, start)) / 2)\n# #\n# # text_edit_output.setTextCursor(cursor)\n# #\n# # elif text_edit_output.hasFocus():\n# # cursor = QTextCursor(text_edit_output.textCursor())\n# # text_edit_input.setTextCursor(cursor)\n#\n# text_edit_input.selectionChanged.connect(selection_changed)\n# text_edit_output.selectionChanged.connect(selection_changed)\n\n label_error = QLabel()\n label_error.setStyleSheet(\"QLabel { color : red; }\")\n label_error.setTextInteractionFlags(Qt.TextSelectableByMouse)\n label_error.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)\n button_detail_error = QPushButton('...')\n button_detail_error.setFixedSize(20, 20)\n button_detail_error.setToolTip('Detail error')\n last_error_message = None\n last_detail_error_message = None\n\n def show_detail_error_massage():\n message = last_error_message + '\\n\\n' + last_detail_error_message\n\n mb = QErrorMessage()\n mb.setWindowTitle('Error')\n # Сообщение ошибки содержит отступы, символы-переходы на следующую строку,\n # которые поломаются при вставке через QErrorMessage.showMessage, и нет возможности\n # выбрать тип текста, то делаем такой хак.\n mb.findChild(QTextEdit).setPlainText(message)\n\n mb.exec_()\n\n button_detail_error.clicked.connect(show_detail_error_massage)\n\n def input_text_changed():\n label_error.clear()\n button_detail_error.hide()\n\n global last_error_message, last_detail_error_message\n last_error_message = None\n last_detail_error_message = None\n\n try:\n text = text_edit_input.toPlainText()\n text = hex2str.do(text)\n text_edit_output.setPlainText(text)\n except Exception as e:\n # Выводим ошибку в консоль\n traceback.print_exc()\n\n # Сохраняем в переменную\n tb = traceback.format_exc()\n\n last_error_message = str(e)\n last_detail_error_message = str(tb)\n button_detail_error.show()\n\n label_error.setText('Error: ' + last_error_message)\n\n text_edit_input.textChanged.connect(input_text_changed)\n\n text_edit_input.setPlainText('504F53542068747470733A')\n\n splitter = QSplitter()\n splitter.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n splitter.addWidget(text_edit_input)\n splitter.addWidget(text_edit_output)\n\n layout.addWidget(splitter)\n\n layout_error = QHBoxLayout()\n layout_error.addWidget(label_error)\n layout_error.addWidget(button_detail_error)\n\n layout.addLayout(layout_error)\n\n mainWidget.setLayout(layout)\n\n mainWidget.resize(650, 500)\n mainWidget.show()\n\n sys.exit(app.exec_())\n","sub_path":"hex2str/hex2str-gui.py","file_name":"hex2str-gui.py","file_ext":"py","file_size_in_byte":7746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"205247959","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2018, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n# Before you can use the jobs API, you need to set up an access token.\n# Log in to the IBM Q experience. Under \"Account\", generate a personal\n# access token. Replace 'PUT_YOUR_API_TOKEN_HERE' below with the quoted\n# token string. Uncomment the APItoken variable, and you will be ready to go.\n\nAPItoken = 'Token'\nif 'APItoken' not in locals():\n raise Exception('Please set up your access token. See Qconfig.py.')\n","sub_path":"2018-07-19_oscon_gambetta/Qconfig.py","file_name":"Qconfig.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"563133864","text":"from collections import Callable\n\nimport numpy as np\n\n\ndef linear_kernel_func(support_vec: np.ndarray, vec: np.ndarray) -> float:\n return support_vec.T * vec\n\n\ndef poly_kernel_func(support_vec: np.ndarray, vec: np.ndarray) -> float:\n return (1 + support_vec.T * vec) ** 2\n\n\ndef gauss_kernel_func(support_vec: np.ndarray, vec: np.ndarray) -> float:\n return np.exp(-(np.linalg.norm(support_vec - vec) ** 2) / 0.8)\n\n\ndef gauss_kernel_func_n(support_vec: np.ndarray, vec: np.ndarray) -> float:\n return np.exp(-(np.linalg.norm(support_vec - vec) ** 2) / 0.2)\n\n\nclass SorSvr(object):\n def __init__(self, epsilon: float = 0.1, sor_epsilon: float = 0.001,\n omega: float = 0.5, C: int = 100, kernel: Callable = gauss_kernel_func):\n \"\"\"\n Constructor\n\n :param epsilon: threshold for predicted function insensitivity\n :param sor_epsilon: threshold for SOR solver\n :param omega: magic const for SOR solver. Need to be in (0, 2)\n :param C: magic const for Lagrange function ¯\\_(ツ)_/¯\n :param kernel: kernel function for \"kernel trick\"\n \"\"\"\n self.epsilon = epsilon\n self.sor_epsilon = sor_epsilon\n self.C = C\n self.omega = omega\n self.kernel = kernel\n self.dim = 0\n self.support_vecs = []\n self.support_vecs_coeffs = []\n self.b = 0.0\n\n def _sor_solver(self, A, b, initial_guess):\n \"\"\"\n This is an implementation of the pseudo-code provided in the Wikipedia article.\n Arguments:\n A: nxn numpy matrix.\n b: n dimensional numpy vector.\n initial_guess: An initial solution guess for the solver to start with.\n Returns:\n phi: solution vector of dimension n.\n \"\"\"\n phi = initial_guess[:]\n residual = np.inf\n iter_count = 0\n while residual > self.sor_epsilon:\n iter_count += 1\n old_phi = phi.copy()\n for i in range(A.shape[0]):\n sigma = 0\n for j in range(A.shape[1]):\n if j != i:\n sigma += A[i][j] * phi[j]\n phi[i] = (1 - self.omega) * phi[i] + (self.omega / A[i][i]) * (b[i] - sigma)\n # phi[i] = phi[i] + (self.omega / A[i][i]) * (b[i] - sigma)\n if phi[i] < 0:\n phi[i] = 0\n elif phi[i] > self.C:\n phi[i] = self.C\n residual = np.linalg.norm(phi - old_phi)\n print('Residual: {0:10.6g}'.format(residual))\n print(\"\\n~~~~~~ Iters count: {} ~~~~~~\\n\".format(iter_count))\n return phi\n\n def train(self, x_train: np.ndarray, y_train: np.ndarray):\n self.dim = len(x_train)\n # Create matrices from article yong2004\n x = x_train.reshape((self.dim, 1))\n y = y_train.reshape((self.dim, 1))\n d = np.ones((2 * self.dim, 1))\n d[self.dim:] *= -1\n c = np.full(shape=(2 * self.dim, 1), fill_value=-self.epsilon, dtype=np.float)\n c[:self.dim] += y\n c[self.dim:] += -y\n H = d * d.T\n for i in range(H.shape[0]):\n for j in range(H.shape[1]):\n x1 = x[i] if i < self.dim else x[i - self.dim]\n x2 = x[j] if j < self.dim else x[j - self.dim]\n H[i][j] *= self.kernel(x1, x2)\n E = d * d.T\n A = H + E\n # Find Lagrange multipliers by SOR algorithm\n a = self._sor_solver(A, c.reshape((2 * self.dim)), np.zeros(2 * self.dim))\n # Get support vectors and their coeffs (a_i - a*_i)\n self.support_vecs = []\n self.support_vecs_coeffs = []\n for i in range(0, self.dim):\n if not np.isclose(a[i], 0) or not np.isclose(a[self.dim + i], 0):\n self.support_vecs.append(x[i])\n self.support_vecs_coeffs.append(a[i] - a[self.dim + i])\n self.b = sum(self.support_vecs_coeffs)\n\n def predict(self, x: np.ndarray) -> float:\n res = 0.0\n for i in range(0, len(self.support_vecs)):\n res += self.support_vecs_coeffs[i] * self.kernel(self.support_vecs[i], x)\n return res + self.b\n\n def get_support_vecs(self):\n return self.support_vecs\n","sub_path":"sor_svr.py","file_name":"sor_svr.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"420212238","text":"\"\"\"\nModule holds selenium stuff\n\"\"\"\nfrom abc import abstractmethod\n\nimport os\nimport time\nimport shutil\nimport sys\nimport subprocess\nimport urwid\n\nfrom collections import Counter\nfrom bzt.engine import ScenarioExecutor, Scenario\nfrom bzt.utils import RequiredTool, shell_exec, shutdown_process, BetterDict, JavaVM\nfrom bzt.moves import string_types, text_type\nfrom bzt.modules.aggregator import ConsolidatingAggregator, ResultsReader\nfrom bzt.modules.console import WidgetProvider\n\n\nclass SeleniumExecutor(ScenarioExecutor, WidgetProvider):\n \"\"\"\n Selenium executor\n \"\"\"\n SELENIUM_DOWNLOAD_LINK = \"http://selenium-release.storage.googleapis.com/{version}/\" \\\n \"selenium-server-standalone-{version}.0.jar\"\n SELENIUM_VERSION = \"2.46\"\n\n JUNIT_DOWNLOAD_LINK = \"http://search.maven.org/remotecontent?filepath=junit/junit/{version}/junit-{version}.jar\"\n JUNIT_VERSION = \"4.12\"\n\n SUPPORTED_TYPES = [\".py\", \".jar\", \".java\"]\n\n def __init__(self):\n super(SeleniumExecutor, self).__init__()\n self.start_time = None\n self.end_time = None\n self.runner = None\n self.widget = None\n self.reader = None\n self.kpi_file = None\n\n def prepare(self):\n \"\"\"\n 1) Locate script or folder\n 2) detect script type\n 3) create runner instance, prepare runner\n \"\"\"\n scenario = self.get_scenario()\n self.kpi_file = self.engine.create_artifact(\"selenium_tests_report\", \".txt\")\n script_type, script_is_folder = self.detect_script_type(scenario.get(\"script\"))\n runner_config = BetterDict()\n\n if script_type == \".py\":\n self.runner = NoseTester\n runner_config = self.settings.get(\"selenium-tools\").get(\"nose\")\n\n elif script_type == \".jar\" or script_type == \".java\":\n self.runner = JunitTester\n runner_config = self.settings.get(\"selenium-tools\").get(\"junit\")\n\n runner_config[\"script-type\"] = script_type\n runner_working_dir = self.engine.create_artifact(runner_config.get(\"working-dir\", \"classes\"), \"\")\n runner_config[\"working-dir\"] = runner_working_dir\n runner_config.get(\"artifacts-dir\", self.engine.artifacts_dir)\n runner_config.get(\"working-dir\", runner_working_dir)\n runner_config.get(\"report-file\", self.kpi_file)\n\n if Scenario.SCRIPT in scenario:\n if script_is_folder:\n shutil.copytree(scenario.get(\"script\"), runner_working_dir)\n else:\n os.makedirs(runner_working_dir)\n shutil.copy2(scenario.get(\"script\"), runner_working_dir)\n\n self.runner = self.runner(runner_config, scenario, self.log)\n self.runner.prepare()\n self.reader = SeleniumDataReader(self.kpi_file, self.log)\n if isinstance(self.engine.aggregator, ConsolidatingAggregator):\n self.engine.aggregator.add_underling(self.reader)\n\n def detect_script_type(self, script_path):\n \"\"\"\n checks if script is java or python\n if it's folder or single script\n :return:\n \"\"\"\n if not isinstance(script_path, string_types) and not isinstance(script_path, text_type):\n raise RuntimeError(\"Nothing to test, no files were provided in scenario\")\n script_path_is_directory = False\n test_files = []\n for dir_entry in os.walk(script_path):\n if dir_entry[2]:\n for test_file in dir_entry[2]:\n if os.path.splitext(test_file)[1].lower() in SeleniumExecutor.SUPPORTED_TYPES:\n test_files.append(test_file)\n\n if os.path.isdir(script_path):\n file_ext = os.path.splitext(test_files[0])[1].lower()\n script_path_is_directory = True\n else:\n file_ext = os.path.splitext(script_path)[1]\n\n if file_ext not in SeleniumExecutor.SUPPORTED_TYPES:\n raise RuntimeError(\"Supported tests types %s was not found\" % SeleniumExecutor.SUPPORTED_TYPES)\n return file_ext, script_path_is_directory\n\n def startup(self):\n \"\"\"\n Start runner\n :return:\n \"\"\"\n self.start_time = time.time()\n self.runner.run_tests()\n\n def check(self):\n \"\"\"\n check if test completed\n :return:\n \"\"\"\n if self.widget:\n cur_state = self.reader.get_state()\n self.widget.update(cur_state, self.reader.summary)\n\n return self.runner.is_finished()\n\n def shutdown(self):\n \"\"\"\n shutdown test_runner\n :return:\n \"\"\"\n self.runner.shutdown()\n\n if self.start_time:\n self.end_time = time.time()\n self.log.debug(\"Selenium tests ran for %s seconds\", self.end_time - self.start_time)\n\n if self.kpi_file:\n if (not os.path.exists(self.kpi_file) or not os.path.getsize(self.kpi_file)) and not self.runner.is_failed:\n msg = \"Empty runner report, most likely runner failed: %s\"\n raise RuntimeWarning(msg % self.kpi_file)\n\n def get_widget(self):\n if not self.widget:\n self.widget = SeleniumWidget(self.get_scenario().get(\"script\"))\n return self.widget\n\n\nclass AbstractTestRunner(object):\n \"\"\"\n Abstract test runner\n \"\"\"\n\n def __init__(self, settings, scenario):\n self.process = None\n self.settings = settings\n self.required_tools = []\n self.scenario = scenario\n self.report_file = self.settings.get(\"report-file\")\n self.artifacts_dir = self.settings.get(\"artifacts-dir\")\n self.working_dir = self.settings.get(\"working-dir\")\n self.log = None\n self.opened_descriptors = {\"std_err\": None, \"std_out\": None}\n self.is_failed = False\n\n @abstractmethod\n def prepare(self):\n pass\n\n @abstractmethod\n def run_checklist(self):\n pass\n\n @abstractmethod\n def run_tests(self):\n pass\n\n def is_finished(self):\n ret_code = self.process.poll()\n if ret_code is not None:\n if ret_code != 0:\n self.log.debug(\"Test runner exit code: %s\", ret_code)\n with open(self.opened_descriptors[\"std_err\"].name) as fds:\n std_err = fds.read()\n self.is_failed = True\n raise RuntimeError(\"Test runner %s has failed: %s\" % (self.__class__.__name__, std_err.strip()))\n return True\n return False\n\n def check_tools(self):\n for tool in self.required_tools:\n if not tool.check_if_installed():\n self.log.info(\"Installing %s\", tool.tool_name)\n tool.install()\n\n def shutdown(self):\n shutdown_process(self.process, self.log)\n for desc in self.opened_descriptors.values():\n desc.close()\n self.opened_descriptors = {}\n\n\nclass JunitTester(AbstractTestRunner):\n \"\"\"\n Allows to test java and jar files\n \"\"\"\n\n def __init__(self, junit_config, scenario, parent_logger):\n super(JunitTester, self).__init__(junit_config, scenario)\n self.log = parent_logger.getChild(self.__class__.__name__)\n path_lambda = lambda key, val: os.path.abspath(os.path.expanduser(self.settings.get(key, val)))\n\n self.junit_path = path_lambda(\"path\", \"~/.bzt/selenium-taurus/tools/junit/junit.jar\")\n self.selenium_server_jar_path = path_lambda(\"selenium-server\", \"~/.bzt/selenium-taurus/selenium-server.jar\")\n self.junit_listener_path = os.path.join(os.path.dirname(__file__), \"resources\", \"taurus_junit.jar\")\n\n self.base_class_path = [self.selenium_server_jar_path, self.junit_path, self.junit_listener_path]\n self.base_class_path.extend(self.scenario.get(\"additional-classpath\", []))\n\n def prepare(self):\n \"\"\"\n run checklist, make jar.\n \"\"\"\n self.run_checklist()\n\n if self.settings.get(\"script-type\", None) == \".java\":\n self.compile_scripts()\n\n def run_checklist(self):\n \"\"\"\n java\n javac\n selenium-server.jar\n junit.jar\n junit_listener.jar\n \"\"\"\n\n if self.settings.get(\"script_type\", None) == \".java\":\n self.required_tools.append(JavaC(\"\", \"\", self.log))\n self.required_tools.append(JavaVM(\"\", \"\", self.log))\n self.required_tools.append(SeleniumServerJar(self.selenium_server_jar_path,\n SeleniumExecutor.SELENIUM_DOWNLOAD_LINK.format(\n version=SeleniumExecutor.SELENIUM_VERSION), self.log))\n self.required_tools.append(JUnitJar(self.junit_path, SeleniumExecutor.JUNIT_DOWNLOAD_LINK.format(\n version=SeleniumExecutor.JUNIT_VERSION)))\n self.required_tools.append(JUnitListenerJar(self.junit_listener_path, \"\"))\n\n self.check_tools()\n\n def compile_scripts(self):\n \"\"\"\n Compile .java files\n \"\"\"\n self.log.debug(\"Compiling .java files started\")\n java_files = []\n\n for dir_entry in os.walk(self.working_dir):\n if dir_entry[2]:\n for test_file in dir_entry[2]:\n if os.path.splitext(test_file)[1].lower() == \".java\":\n java_files.append(os.path.join(dir_entry[0], test_file))\n\n compile_cl = [\"javac\", \"-cp\", os.pathsep.join(self.base_class_path)]\n compile_cl.extend(java_files)\n\n with open(os.path.join(self.artifacts_dir, \"javac_out\"), 'ab') as javac_out:\n with open(os.path.join(self.artifacts_dir, \"javac_err\"), 'ab') as javac_err:\n self.process = shell_exec(compile_cl, cwd=self.working_dir, stdout=javac_out, stderr=javac_err)\n ret_code = self.process.poll()\n\n while ret_code is None:\n self.log.debug(\"Compiling .java files...\")\n time.sleep(1)\n ret_code = self.process.poll()\n\n if ret_code != 0:\n self.log.debug(\"javac exit code: %s\", ret_code)\n with open(javac_err.name) as err_file:\n out = err_file.read()\n raise RuntimeError(\"Javac exited with error:\\n %s\" % out.strip())\n\n self.log.info(\"Compiling .java files completed\")\n\n self.make_jar()\n\n def make_jar(self):\n \"\"\"\n move all .class files to compiled.jar\n \"\"\"\n self.log.debug(\"Making .jar started\")\n\n with open(os.path.join(self.artifacts_dir, \"jar_out\"), 'ab') as jar_out:\n with open(os.path.join(self.artifacts_dir, \"jar_err\"), 'ab') as jar_err:\n class_files = [java_file for java_file in os.listdir(self.working_dir) if java_file.endswith(\".class\")]\n jar_name = self.settings.get(\"jar-name\", \"compiled.jar\")\n if class_files:\n compile_jar_cl = [\"jar\", \"-cf\", jar_name]\n compile_jar_cl.extend(class_files)\n else:\n package_dir = os.listdir(self.working_dir)[0]\n compile_jar_cl = [\"jar\", \"-cf\", jar_name, \"-C\", package_dir, \".\"]\n\n self.process = shell_exec(compile_jar_cl, cwd=self.working_dir, stdout=jar_out, stderr=jar_err)\n ret_code = self.process.poll()\n\n while ret_code is None:\n self.log.debug(\"Making jar file...\")\n time.sleep(1)\n ret_code = self.process.poll()\n\n if ret_code != 0:\n with open(jar_err.name) as err_file:\n out = err_file.read()\n self.log.info(\"Making jar failed with code %s\", ret_code)\n self.log.info(\"jar output: %s\", out)\n raise RuntimeError(\"Jar exited with non-zero code\")\n\n self.log.info(\"Making .jar file completed\")\n\n def run_tests(self):\n # java -cp junit.jar:selenium-test-small.jar:\n # selenium-2.46.0/selenium-java-2.46.0.jar:./../selenium-server.jar\n # org.junit.runner.JUnitCore TestBlazemeterPass\n\n jar_list = [os.path.join(self.working_dir, jar) for jar in os.listdir(self.working_dir) if jar.endswith(\".jar\")]\n self.base_class_path.extend(jar_list)\n\n junit_command_line = [\"java\", \"-cp\", os.pathsep.join(self.base_class_path),\n \"taurus_junit_listener.CustomRunner\"]\n junit_command_line.extend(jar_list)\n junit_command_line.extend([self.report_file])\n\n junit_out_path = os.path.join(self.artifacts_dir, \"junit_out\")\n junit_err_path = os.path.join(self.artifacts_dir, \"junit_err\")\n\n junit_out = open(junit_out_path, 'ab')\n junit_err = open(junit_err_path, 'ab')\n\n self.opened_descriptors[\"std_out\"] = junit_out\n self.opened_descriptors[\"std_err\"] = junit_err\n\n self.process = shell_exec(junit_command_line, cwd=self.artifacts_dir,\n stdout=junit_out,\n stderr=junit_err)\n\n\nclass NoseTester(AbstractTestRunner):\n \"\"\"\n Python selenium tests runner\n \"\"\"\n\n def __init__(self, nose_config, scenario, parent_logger):\n super(NoseTester, self).__init__(nose_config, scenario)\n self.log = parent_logger.getChild(self.__class__.__name__)\n self.plugin_path = os.path.join(os.path.dirname(__file__), \"resources\", \"nose_plugin.py\")\n\n def prepare(self):\n self.run_checklist()\n\n def run_checklist(self):\n \"\"\"\n we need installed nose plugin\n \"\"\"\n if sys.version >= '3':\n self.log.warn(\"You are using python3, make sure that your scripts are able to run in python3!\")\n\n self.required_tools.append(\n TaurusNosePlugin(self.plugin_path, \"\"))\n\n self.check_tools()\n\n def run_tests(self):\n \"\"\"\n run python tests\n \"\"\"\n executable = self.settings.get(\"interpreter\", sys.executable)\n nose_command_line = [executable, self.plugin_path, self.report_file, self.working_dir]\n nose_out = open(os.path.join(self.artifacts_dir, \"nose_out\"), 'ab')\n nose_err = open(os.path.join(self.artifacts_dir, \"nose_err\"), 'ab')\n\n self.opened_descriptors[\"std_out\"] = nose_out\n self.opened_descriptors[\"std_err\"] = nose_err\n\n self.process = shell_exec(nose_command_line, cwd=self.artifacts_dir,\n stdout=nose_out,\n stderr=nose_err)\n\n\nclass SeleniumDataReader(ResultsReader):\n \"\"\"\n Read KPI from data log\n \"\"\"\n\n def __init__(self, filename, parent_logger):\n super(SeleniumDataReader, self).__init__()\n self.log = parent_logger.getChild(self.__class__.__name__)\n self.filename = filename\n self.fds = None\n self.partial_buffer = \"\"\n self.test_buffer = TestSample()\n self.offset = 0\n self.trace_buff = \"\"\n self.err_message_buff = \"\"\n self.err_codes = {\"OK\": \"200\", \"SKIPPED\": \"300\", \"FAILED\": \"404\", \"ERROR\": \"500\"}\n self.summary = Counter({\"total\": 0, \"pass\": 0, \"fail\": 0})\n\n def _read(self, last_pass=False):\n \"\"\"\n :param last_pass:\n \"\"\"\n\n while not self.fds and not self.__open_fds():\n self.log.debug(\"No data to start reading yet...\")\n yield None\n\n self.log.debug(\"Reading selenium results\")\n self.fds.seek(self.offset) # without this we have a stuck reads on Mac\n if last_pass:\n lines = self.fds.readlines() # unlimited\n else:\n lines = self.fds.readlines(1024 * 1024) # 1MB limit to read\n self.offset = self.fds.tell()\n for line in lines:\n if not line.endswith(\"\\n\"):\n self.partial_buffer += line\n continue\n\n line = \"%s%s\" % (self.partial_buffer, line)\n self.partial_buffer = \"\"\n line = line.strip(\"\\n\")\n # TODO: Optimise it\n if line.startswith(\"--TIMESTAMP:\"):\n self.test_buffer = TestSample()\n self.trace_buff = \"\"\n self.err_message_buff = \"\"\n self.test_buffer.t_stamp = line[12:]\n elif line.startswith(\"--MODULE:\"):\n self.test_buffer.module = line[9:]\n elif line.startswith(\"--RUN:\"):\n self.test_buffer.test_name = line[6:]\n elif line.startswith(\"--RESULT:\"):\n self.test_buffer.result = line[10:]\n elif line.startswith(\"--TRACE:\"):\n self.trace_buff = line[8:]\n elif line.startswith(\"--MESSAGE:\"):\n self.err_message_buff = line[9:]\n elif line.startswith(\"--TIME:\"):\n self.summary['total'] += 1\n self.test_buffer.time = line[7:]\n self.test_buffer.trace = self.trace_buff\n self.test_buffer.message = self.err_message_buff\n\n r_code = self.err_codes[self.test_buffer.result]\n concur = 1\n conn_time = 0\n latency = 0\n\n if self.test_buffer.trace or self.test_buffer.message:\n self.summary[\"fail\"] += 1\n if not self.test_buffer.message:\n error = self.test_buffer.trace\n else:\n error = self.test_buffer.message + \"\\n\" + self.test_buffer.trace\n else:\n self.summary[\"pass\"] += 1\n error = None\n yield int(self.test_buffer.t_stamp) / 1000.0, self.test_buffer.test_name, concur, \\\n int(self.test_buffer.time) / 1000.0, conn_time, latency, r_code, error, self.test_buffer.module\n else:\n if not self.err_message_buff:\n self.trace_buff += line\n else:\n self.err_message_buff += line\n\n def get_state(self):\n return self.test_buffer.test_name\n\n def __open_fds(self):\n \"\"\"\n opens results.txt\n \"\"\"\n if not os.path.isfile(self.filename):\n self.log.debug(\"File not appeared yet\")\n return False\n\n if not os.path.getsize(self.filename):\n self.log.debug(\"File is empty: %s\", self.filename)\n return False\n\n self.fds = open(self.filename)\n return True\n\n def __del__(self):\n if self.fds:\n self.fds.close()\n\n\nclass TestSample(object):\n def __init__(self):\n self.t_stamp = \"\"\n self.module = \"\"\n self.test_name = \"\"\n self.result = \"\"\n self.trace = \"\"\n self.message = \"\"\n self.time = \"\"\n\n\nclass SeleniumWidget(urwid.Pile):\n def __init__(self, script):\n widgets = []\n self.script_name = urwid.Text(\"Tests: %s\" % script)\n self.summary_stats = urwid.Text(\"\")\n self.current_test = urwid.Text(\"\")\n widgets.append(self.script_name)\n widgets.append(self.summary_stats)\n widgets.append(self.current_test)\n super(SeleniumWidget, self).__init__(widgets)\n\n def update(self, cur_test, reader_summary):\n self.current_test.set_text(cur_test)\n self.summary_stats.set_text(\n \"Total:%d Pass:%d Fail:%d\" % (reader_summary['total'], reader_summary['pass'], reader_summary['fail']))\n self._invalidate()\n\n\nclass SeleniumServerJar(RequiredTool):\n def __init__(self, tool_path, download_link, parent_logger):\n super(SeleniumServerJar, self).__init__(\"Selenium server\", tool_path, download_link)\n self.log = parent_logger.getChild(self.__class__.__name__)\n\n def check_if_installed(self):\n self.log.debug(\"%s path: %s\", self.tool_name, self.tool_path)\n selenium_launch_command = [\"java\", \"-jar\", self.tool_path, \"-help\"]\n selenium_subproc = shell_exec(selenium_launch_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output = selenium_subproc.communicate()\n self.log.debug(\"%s output: %s\", self.tool_name, output)\n if selenium_subproc.returncode == 0:\n self.already_installed = True\n return True\n else:\n return False\n\n\nclass JUnitJar(RequiredTool):\n def __init__(self, tool_path, download_link):\n super(JUnitJar, self).__init__(\"JUnit\", tool_path, download_link)\n\nclass JavaC(RequiredTool):\n def __init__(self, tool_path, download_link, parent_logger):\n super(JavaC, self).__init__(\"JavaC\", tool_path, download_link)\n self.log = parent_logger.getChild(self.__class__.__name__)\n\n def check_if_installed(self):\n try:\n output = subprocess.check_output([\"javac\", '-version'], stderr=subprocess.STDOUT)\n self.log.debug(\"%s output: %s\", self.tool_name, output)\n return True\n except BaseException:\n raise RuntimeError(\"The %s is not operable or not available. Consider installing it\" % self.tool_name)\n\n def install(self):\n raise NotImplementedError()\n\n\nclass JUnitListenerJar(RequiredTool):\n def __init__(self, tool_path, download_link):\n super(JUnitListenerJar, self).__init__(\"JUnitListener\", tool_path, download_link)\n\n def install(self):\n raise NotImplementedError()\n\n\nclass TaurusNosePlugin(RequiredTool):\n def __init__(self, tool_path, download_link):\n super(TaurusNosePlugin, self).__init__(\"TaurusNosePlugin\", tool_path, download_link)\n\n def install(self):\n raise NotImplementedError()\n","sub_path":"bzt/modules/selenium.py","file_name":"selenium.py","file_ext":"py","file_size_in_byte":21508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"596014574","text":"\n\nclass fileNotFoundException( Exception ): \n \"\"\" Exception when a file is not found\"\"\"\n filePath = None\n message = None\n \n def __init__( self, filePath ):\n Exception.__init__( self, filePath ) \n self.filePath = filePath\n self.message = 'Parameter file not found: ' + self.filePath + '\\n\\n'\n \n # Exceptions\nclass directoryNotEmpty( Exception ): \n \"\"\" Directory not empty exception \"\"\"\n def __init__( self, directoryPath ):\n Exception.__init__( self, directoryPath )\n self.directoryPath = directoryPath\n self.message = 'The directory is not empty: ' + self.directoryPath + '\\n\\nChoose a different one\\n'\n \n \n \n \nclass fatalError( Exception ): \n \"\"\" Fatal error exception \"\"\"\n \n def __init__( self, mainErrorMessage ,*detailsMessages):\n \"\"\" Constructor \"\"\"\n \n super(fatalError,self).__init__( self, mainErrorMessage ,*detailsMessages)\n \n self.mainErrorMessage = mainErrorMessage\n \n self.message = \" \" + mainErrorMessage + '\\n\\n'\n \n if len(detailsMessages) > 0:\n self.message += \"Details:\" + \"\\n\"\n for message in detailsMessages:\n self.message += message + '\\n'\n \n self.message +='\\n'\n \n \n def __str__(self):\n return self.message \n \n def __repr__(self): \n return self.message \n","sub_path":"pyWAT/core/errorHandling.py","file_name":"errorHandling.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"92530483","text":"# Copyright 2015 Mirantis Inc.\n# Copyright 2014 Symantec Corporation\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 magnetodb.openstack.common import log as logging\nfrom magnetodb import storage\nfrom magnetodb.common import exception\n\nLOG = logging.getLogger(__name__)\n\n\nclass ProjectUsageController():\n \"\"\"Returns metrics.\n \"\"\"\n\n def project_usage_details(self, req, project_id):\n req.context.tenant = project_id\n\n if 'metrics' not in req.GET:\n keys = ['size', 'item_count']\n else:\n keys = req.GET['metrics'].split(',')\n\n table_names = storage.list_tables(req.context)\n\n result = []\n for table_name in table_names:\n try:\n result.append({\n \"table_name\": table_name,\n \"usage_detailes\": storage.get_table_statistics(req.context,\n table_name,\n keys)\n })\n except exception.ValidationError:\n pass\n\n return result\n","sub_path":"magnetodb/api/openstack/v1/monitoring/project_usage_details.py","file_name":"project_usage_details.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"206860216","text":"import unittest\nimport torch\nfrom pytorch_metric_learning.losses import LargeMarginSoftmaxLoss, SphereFaceLoss\nfrom pytorch_metric_learning.utils import common_functions as c_f\nimport math\nimport scipy\nimport numpy as np\n\nclass TestLargeMarginSoftmaxLoss(unittest.TestCase):\n def test_large_margin_softmax_and_sphereface_loss(self):\n margin = 10\n scale = 2\n loss_funcA = LargeMarginSoftmaxLoss(margin=margin, scale=scale, num_classes=10, embedding_size=2, normalize_embeddings=False)\n loss_funcB = SphereFaceLoss(margin=margin, scale=scale, num_classes=10, embedding_size=2, normalize_embeddings=False)\n\n embedding_angles = torch.arange(0, 180)\n # multiply by 10 to make the embeddings unnormalized\n embeddings = torch.tensor(np.array([c_f.angle_to_coord(a) for a in embedding_angles])*10, requires_grad=True, dtype=torch.float) #2D embeddings\n labels = torch.randint(low=0, high=10, size=(180,))\n\n lossA = loss_funcA(embeddings, labels)\n lossB = loss_funcB(embeddings, labels)\n lossA.backward()\n lossB.backward()\n\n weightsA = loss_funcA.W\n weightsB = torch.nn.functional.normalize(loss_funcB.W, dim=0)\n\n product_of_magnitudesA = torch.norm(weightsA, p=2, dim=0).unsqueeze(0) * torch.norm(embeddings, p=2, dim=1).unsqueeze(1)\n product_of_magnitudesB = torch.norm(embeddings, p=2, dim=1).unsqueeze(1)\n cosinesA = torch.matmul(embeddings, weightsA) / (product_of_magnitudesA)\n cosinesB = torch.matmul(embeddings, weightsB) / (product_of_magnitudesB)\n coefficients = [scipy.special.binom(margin, 2*n) for n in range((margin // 2) + 1)]\n\n for i, j in enumerate(labels):\n curr_cosineA = cosinesA[i, j]\n curr_cosineB = cosinesB[i, j]\n cos_with_marginA = torch.zeros(len(coefficients))\n cos_with_marginB = torch.zeros(len(coefficients))\n for z, c in enumerate(coefficients):\n curr_valA = c*(curr_cosineA**(margin - (2*z)))*((1-curr_cosineA**2)**z)\n curr_valB = c*(curr_cosineB**(margin - (2*z)))*((1-curr_cosineB**2)**z)\n if z % 2 == 1:\n curr_valA *= -1\n curr_valB *= -1\n cos_with_marginA[z] = curr_valA\n cos_with_marginB[z] = curr_valB\n \n cos_with_marginA = torch.sum(cos_with_marginA)\n cos_with_marginB = torch.sum(cos_with_marginB)\n angleA = torch.acos(torch.clamp(curr_cosineA, -1 + 1e-7, 1 - 1e-7))\n angleB = torch.acos(torch.clamp(curr_cosineB, -1 + 1e-7, 1 - 1e-7))\n kA = (angleA / (math.pi / margin)).floor() # Equation 6: angles needs to be between [k*pi/m and (k+1)*pi/m]\n kB = (angleB / (math.pi / margin)).floor() # Equation 6: angles needs to be between [k*pi/m and (k+1)*pi/m]\n cosinesA[i, j] = ((-1)**kA)*cos_with_marginA - (2*kA)\n cosinesB[i, j] = ((-1)**kB)*cos_with_marginB - (2*kB)\n \n cosinesA *= product_of_magnitudesA\n cosinesB *= product_of_magnitudesB\n\n correct_lossA = torch.nn.functional.cross_entropy(cosinesA*scale, labels)\n correct_lossB = torch.nn.functional.cross_entropy(cosinesB*scale, labels)\n\n self.assertTrue(torch.isclose(lossA, correct_lossA))\n self.assertTrue(torch.isclose(lossB, correct_lossB))","sub_path":"tests/losses/test_large_margin_softmax_loss.py","file_name":"test_large_margin_softmax_loss.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513818056","text":"'''\nThis program will print three form letters asking for votes in the past election.\nIt uses hardcoded tuples to insert into a constant letter format\n\nPranav Eranki - 10/1/2018\n'''\n\nUNCHANGING = \"Dear %s, \\nI would like you to vote for %s \\nbecause I think %s is best for \\nthis country. \\nSincerely, \\n%s\"\n\n# format = addressee, candidate, sender\nletter_1 = \"Steven\", \"Hillary Clinton\", \"Hillary Clinton\", \"Pranav\"\nletter_2 = \"Rahul\", \"Donald Trump\", \"Donald Trump\", \"Pranav\"\nletter_3 = \"Bhargav\", \"Bernie Sanders\", \"Bernie Sanders\", \"Pranav\"\n#Defining the array\nletters = [letter_1, letter_2, letter_3]\n\n#Prints the unchanging value with the letter values replaced in for the 'placeholders'\nfor letter in letters:\n print(UNCHANGING % letter)\n\n\n# For this code, the output is:\n\"\"\"\nDear Steven,\nI would like you to vote for Hillary Clinton\nbecause I think Hillary Clinton is best for\nthis country.\nSincerely,\nPranav\n\nDear Rahul,\nI would like you to vote for Donald Trump\nbecause I think Donald Trump is best for\nthis country.\nSincerely,\nPranav\n\nDear Bhargav,\nI would like you to vote for Bernie Sanders\nbecause I think Bernie Sanders is best for\nthis country.\nSincerely,\nPranav\n\"\"\"","sub_path":"assignment2_formletters.py","file_name":"assignment2_formletters.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496114097","text":"# coding: utf-8\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom jedi.libs.db.store import db\nfrom jedi.libs.utils.dt import UTC_TZ\nfrom jedi.libs.utils.dt import localized_datetime\nfrom jedi.libs.utils.dt import datetime_to_timestamp\nfrom jedi.libs.utils.dt import timestamp_to_datetime\nfrom jedi.libs.cache.redis import mc\nfrom jedi.libs.cache.redis import cache\nfrom jedi.libs.cache.listed import ListCache\nfrom jedi.libs.sentry.client import client\n\nfrom jedi.models.props import Props\nfrom jedi.models.consts import ClassType\nfrom jedi.models.timeslot import Timeslot\nfrom jedi.models.timeslot.cached import CachedTimeslotNode\nfrom jedi.models.timeslot.cached import StudentCachedTimeslot\nfrom jedi.models.exception import LockError\nfrom jedi.models.exception import ClassStatusInfoError\nfrom jedi.models.exception import ClassStatusError, ClassTypeError\nfrom jedi.models.exception import TimeslotStatusError\nfrom jedi.models.exception import CachedTimeslotDuplicateError\n\nfrom .base import ClassBase\nfrom .consts import ClassStatus as Status\nfrom .consts import ClassStatusInfo as StatusInfo\nfrom .consts import ClassroomProvider as Provider\nfrom .consts import validate_reason\n\n_ONLINE_CLASS_CACHE_KEY_PREFIX = 'onlineclass:'\nONLINE_CLASS_CACHE_KEY = _ONLINE_CLASS_CACHE_KEY_PREFIX + 'id:%s'\nONLINE_CLASS_PB_CACHE_KEY = ONLINE_CLASS_CACHE_KEY + ':pb'\n\n_PB_ONLINE_CLASS_PREFIX = 'pb:oc:'\nPB_ONLINE_CLASS_LIST_BY_TEACHER = _PB_ONLINE_CLASS_PREFIX + 'list:by:teacher:{teacher_id}'\nPB_ONLINE_CLASS_LIST_BY_STUDENT = _PB_ONLINE_CLASS_PREFIX + 'list:by:student:{student_id}'\n\nMAX_UNDO_COUNT = 5 # change_finish_status_info max time\n\n\nclass OnlineClass(ClassBase):\n _tablename = 'onlineclass'\n\n PRODUCT = 'online_class'\n props = Props(product=PRODUCT)\n\n title = props.item('title', '')\n docs = props.item('docs', {'xuedianyun': [], 'duobeiyun': []})\n student_entering_time = props.item('student_entering_time', None)\n teacher_entering_time = props.item('teacher_entering_time', None)\n undo_count = props.item('undo_count', 0)\n _end_timestamp = props.item('_end_timestamp', None)\n\n @props.uuidgetter\n def uuid(self):\n return self.id\n\n @property\n def _start_timestamp(self):\n return self.schedule_timestamp\n\n def __init__(self, id, course_id, lesson_id, period,\n teacher_id, student_id, timeslot_id, schedule_timestamp,\n type, status, status_info, provider, create_time, update_time):\n self.id = str(id)\n self.course_id = str(course_id)\n self.lesson_id = str(lesson_id)\n self.period = int(period)\n self.teacher_id = str(teacher_id)\n self.student_id = str(student_id)\n self.timeslot_id = str(timeslot_id) if timeslot_id else None\n self.schedule_timestamp = int(schedule_timestamp)\n schedule_time = timestamp_to_datetime(schedule_timestamp)\n self.schedule_time = localized_datetime(schedule_time)\n self.type = ClassType(type)\n self.status = Status(status)\n self.status_info = StatusInfo(status_info)\n self.provider = Provider(provider)\n self.create_time = localized_datetime(create_time)\n self.update_time = localized_datetime(update_time)\n\n def __repr__(self):\n return '<OnlineClass id=%s>' % self.id\n\n @classmethod\n @cache(ONLINE_CLASS_CACHE_KEY % '{id}')\n def get(cls, id):\n sql = ('select id, course_id, lesson_id, period, teacher_id, student_id, timeslot_id, '\n 'schedule_timestamp, type, status, status_info, provider, create_time, update_time '\n 'from {table} where id=:id').format(table=cls._tablename)\n params = dict(id=id)\n r = db.execute(sql, params=params).fetchone()\n db.commit()\n return cls(*r) if r else None\n\n @classmethod\n def get_multi(cls, ids):\n cached = mc.get_multi([ONLINE_CLASS_CACHE_KEY % id for id in ids])\n return [cached.get(ONLINE_CLASS_CACHE_KEY % id) or\n cls.get(id) for id in ids]\n\n @classmethod\n def get_all_by_student_and_course_and_status(cls, student_id, course_id, status, start, limit):\n total, ids = cls.get_ids_by_student_and_course_and_status(\n student_id, course_id, status, start, limit)\n return total, cls.get_multi(ids)\n\n @classmethod\n def get_ids_by_student_and_course_and_status(cls, student_id, course_id, status, start, limit):\n ids = []\n info = cls._get_info_by_student(student_id, [], [status.value])\n for (id_, schedule_timestamp, cid, lid,\n type_, status_value, status_info_, provider_, _) in info:\n if str(cid) == str(course_id) and (int(status_value) == int(status.value)):\n ids.append(str(id_))\n total = len(ids)\n return total, ids[start: start + limit]\n\n @classmethod\n def get_last_scheduled_class_id(cls, student_id, course_id):\n sql = ('select id from {table} '\n 'where student_id=:student_id and course_id=:course_id '\n 'and status=:status and status_info=:status_info '\n 'order by schedule_timestamp desc limit 1').format(table=cls._tablename)\n params = dict(\n student_id=student_id,\n course_id=course_id,\n status=Status.finished.value,\n status_info=StatusInfo.finished_as_as_scheduled.value\n )\n r = db.execute(sql, params).fetchone()\n db.commit()\n if r:\n return str(r[0])\n\n @classmethod\n def gets_by_student_and_lesson_and_status(cls, student_id, lesson_id, status, start, limit):\n total, ids = cls.get_ids_by_student_and_lesson_and_status(\n student_id, lesson_id, status, start, limit)\n return total, cls.get_multi(ids)\n\n @classmethod\n def gets_by_time_with_fitler(cls, start_timestamp, end_timestamp, start, limit,\n teacher_id=None, student_id=None,\n types=[], statuses=[], status_infos=[],\n providers=[], course_ids=[]):\n rs = cls._get_info_by_time_with_filter(\n start_timestamp,\n end_timestamp,\n teacher_id=teacher_id,\n student_id=student_id,\n types=types,\n statuses=statuses,\n status_infos=status_infos,\n providers=providers,\n course_ids=course_ids\n )\n ids = [str(r[0]) for r in rs]\n return len(ids), cls.get_multi(ids[start:start + limit])\n\n @classmethod\n def gets_by_students_with_filter(cls, start_timestamp, end_timestamp, start, limit,\n student_ids, teacher_id=None,\n types=[], statuses=[], status_infos=[],\n providers=[], course_ids=[]):\n if not student_ids:\n raise ValueError\n rs = cls._get_info_by_time_with_filter(\n start_timestamp,\n end_timestamp,\n teacher_id=teacher_id,\n types=types,\n statuses=statuses,\n status_infos=status_infos,\n providers=providers,\n course_ids=course_ids\n )\n ids = [str(r[0]) for r in rs if str(r[8]) in student_ids]\n return len(ids), cls.get_multi(ids[start:start + limit])\n\n @classmethod\n def _get_info_by_time_with_filter(\n cls, start_timestamp, end_timestamp,\n teacher_id=None, student_id=None,\n types=[], statuses=[],\n status_infos=[], providers=[],\n course_ids=[]):\n rs = cls._get_info_by_time(start_timestamp, end_timestamp, teacher_id, student_id)\n return cls._online_class_filter(\n rs, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n @classmethod\n def _get_info_by_time(cls, start_timestamp, end_timestamp, teacher_id=None, student_id=None):\n student_id_sql = 'student_id=:student_id and ' if student_id else ''\n teacher_id_sql = 'teacher_id=:teacher_id and ' if teacher_id else ''\n\n sql = ('select id, schedule_timestamp, course_id, lesson_id, type, '\n 'status, status_info, provider, student_id from {table} '\n 'where ' + student_id_sql + teacher_id_sql +\n 'schedule_timestamp >= :start_timestamp '\n 'and schedule_timestamp < :end_timestamp '\n 'order by schedule_timestamp desc'\n ).format(table=cls._tablename)\n params = dict(\n start_timestamp=start_timestamp,\n end_timestamp=end_timestamp,\n teacher_id=teacher_id,\n student_id=student_id\n )\n rs = db.execute(sql, params).fetchall()\n db.commit()\n return rs\n\n @classmethod\n def get_ids_by_student_and_lesson_and_status(cls, student_id, lesson_id, status, start, limit):\n ids = []\n info = cls._get_info_by_student(student_id, [], [status.value])\n for (id_, schedule_timestamp, cid, lid,\n type_, status_value, status_info_, provider_, _) in info:\n if str(lid) == str(lesson_id) and (int(status_value) == int(status.value)):\n ids.append(str(id_))\n total = len(ids)\n return total, ids[start: start + limit]\n\n @classmethod\n def gets_by_student_with_filter(\n cls, student_id, start, limit, types=[], statuses=[],\n status_infos=[], providers=[], start_timestamp=None,\n end_timestamp=None, course_ids=[]):\n\n rs = cls.get_info_by_student_with_filter(\n student_id, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n if start_timestamp:\n rs = [r for r in rs if r[1] >= start_timestamp]\n if end_timestamp:\n rs = [r for r in rs if r[1] < end_timestamp]\n ids = [str(r[0]) for r in rs]\n total = len(ids)\n return total, cls.get_multi(ids[start: start + limit])\n\n @classmethod\n def gets_by_teacher_with_filter(\n cls, teacher_id, start, limit, types=[], statuses=[],\n status_infos=[], providers=[], start_timestamp=None,\n end_timestamp=None, course_ids=[]):\n\n rs = cls.get_info_by_teacher_with_filter(\n teacher_id, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n if start_timestamp:\n rs = [r for r in rs if r[1] >= start_timestamp]\n if end_timestamp:\n rs = [r for r in rs if r[1] < end_timestamp]\n ids = [str(r[0]) for r in rs]\n total = len(ids)\n return total, cls.get_multi(ids[start: start + limit])\n\n @classmethod\n def get_info_by_student_with_filter(\n cls, student_id, types=[], statuses=[],\n status_infos=[], providers=[], course_ids=[]):\n rs = cls._get_info_by_student(student_id, types, statuses)\n return cls._online_class_filter(\n rs, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n @classmethod\n def get_info_by_teacher_with_filter(\n cls, teacher_id, types=[], statuses=[],\n status_infos=[], providers=[], course_ids=[]):\n rs = cls._get_info_by_teacher(teacher_id, types, statuses)\n return cls._online_class_filter(\n rs, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n @classmethod\n def _online_class_filter(\n cls, rs, types=[], statuses=[], status_infos=[],\n providers=[], course_ids=[]):\n t = []\n if not types and not statuses and not status_infos and not providers and not course_ids:\n return rs\n # 这块逻辑有点复杂, status or status_info,但是 status_info 不能把其他的 status 给过滤掉\n status_infos_statuses = set()\n for status_info in status_infos:\n status_infos_statuses.add(StatusInfo.get_status_from_status_info(status_info))\n statuses = set(statuses) - status_infos_statuses\n for r in rs:\n (id_, schedule_timestamp, course_id_, lesson_id,\n type_, status_, status_info_, provider_, student_id) = r\n if statuses and status_infos:\n if (status_ not in statuses and status_info_ not in status_infos):\n continue\n elif statuses:\n if status_ not in statuses:\n continue\n elif status_infos:\n if status_info_ not in status_infos:\n continue\n if providers and provider_ not in providers:\n continue\n if course_ids and int(course_id_) not in course_ids:\n continue\n if types and type_ not in types:\n continue\n\n t.append(r)\n return t\n\n @classmethod\n def _get_info_by_student(cls, student_id, types, statuses):\n type_sql = ''\n status_sql = ''\n\n if types:\n type_sql = 'and ' + cls.build_args('type', types) + ' '\n\n if statuses:\n status_sql = 'and ' + cls.build_args('status', statuses) + ' '\n\n sql = ('select id, schedule_timestamp, course_id, lesson_id, type, '\n 'status, status_info, provider, student_id from {table} '\n 'where student_id=:student_id '\n '{type_sql}'\n '{status_sql}'\n ).format(table=cls._tablename,\n type_sql=type_sql,\n status_sql=status_sql)\n params = dict(student_id=student_id)\n rs = db.execute(sql, params).fetchall()\n rs = sorted(rs, key=lambda x: -x[1])\n db.commit()\n return rs\n\n @classmethod\n def build_args(cls, name, args):\n args = [str(arg) for arg in args]\n return '%s in (%s)' % (name, ','.join(args))\n\n @classmethod\n def _get_info_by_teacher(cls, teacher_id, types, statuses):\n type_sql = ''\n status_sql = ''\n\n if types:\n type_sql = 'and ' + cls.build_args('type', types) + ' '\n\n if statuses:\n status_sql = 'and ' + cls.build_args('status', statuses) + ' '\n\n sql = ('select id, schedule_timestamp, course_id, lesson_id, type, '\n 'status, status_info, provider, student_id from {table} '\n 'where teacher_id=:teacher_id '\n '{type_sql}'\n '{status_sql}'\n ).format(table=cls._tablename,\n type_sql=type_sql,\n status_sql=status_sql)\n params = dict(teacher_id=teacher_id)\n rs = db.execute(sql, params).fetchall()\n db.commit()\n rs = sorted(rs, key=lambda x: -x[1])\n return rs\n\n @classmethod\n def add(cls, course_id, lesson_id, student_id, timeslot_id, period, provider, type):\n if type in (ClassType.none, ClassType.open_class):\n raise ClassTypeError('class type does not match!')\n\n timeslot = Timeslot.get(timeslot_id)\n if not timeslot.can_be_booked():\n raise TimeslotStatusError\n\n if timeslot.type != ClassType.none and timeslot.type != type:\n raise ClassTypeError('class type does not match')\n\n timeslot.locker.aquire()\n try:\n student_timeslot = StudentCachedTimeslot.get(student_id)\n\n node = CachedTimeslotNode(\n timeslot.start_timestamp,\n timeslot.end_timestamp)\n\n if student_timeslot.exist(node):\n raise CachedTimeslotDuplicateError\n\n sql = ('insert into {table} (course_id, lesson_id, period, '\n 'teacher_id, student_id, timeslot_id, '\n 'schedule_timestamp, type, status, status_info, provider ) '\n 'values (:course_id, :lesson_id, :period, :teacher_id, '\n ':student_id, :timeslot_id, '\n ':schedule_timestamp, :type, :status, :status_info, :provider '\n ')').format(table=cls._tablename)\n\n params = dict(\n course_id=course_id,\n lesson_id=lesson_id,\n period=period,\n teacher_id=timeslot.user_id,\n student_id=student_id,\n timeslot_id=timeslot_id,\n schedule_timestamp=timeslot.start_timestamp,\n type=type.value,\n status=Status.created.value,\n status_info=StatusInfo.none.value,\n provider=provider.value,\n )\n\n r = db.execute(sql, params=params)\n\n if r.lastrowid:\n try:\n student_timeslot.insert(node)\n except (CachedTimeslotDuplicateError, LockError):\n db.rollback()\n raise\n id = str(r.lastrowid)\n db.commit()\n oc = cls.get(id)\n timeslot.bind(oc)\n oc._end_timestamp = timeslot.end_timestamp\n return oc\n db.rollback()\n finally:\n timeslot.locker.release()\n\n def _change_teacher_or_student_check(self, status_info, **kwargs):\n scheduler = kwargs.get('scheduler')\n if not scheduler:\n raise Exception('need scheduler')\n status = StatusInfo.get_status_from_status_info(status_info)\n now = datetime.now(tz=UTC_TZ)\n if self.schedule_time > now:\n if status != Status.canceled:\n raise ClassStatusInfoError\n if not self.can_be_canceled():\n raise ClassStatusError('can not cancel IN_CLASS class')\n else:\n if status != Status.finished:\n raise ClassStatusInfoError\n if not self.can_be_finished():\n raise ClassStatusError('Only IN_CLASS class can be finished')\n self._check_end_class_reason(status_info)\n return scheduler, status\n\n def change_teacher(self, timeslot_id, status_info, **kwargs):\n scheduler, status = self._change_teacher_or_student_check(status_info, **kwargs)\n if not status_info.is_change_teacher_reason():\n raise ClassStatusInfoError\n return self._change_teacher(timeslot_id, status, status_info, scheduler)\n\n def _change_teacher(self, timeslot_id, status, status_info, scheduler):\n timeslot = Timeslot.get(timeslot_id)\n timeslot.locker.aquire()\n try:\n if not timeslot.can_be_booked():\n raise TimeslotStatusError\n if timeslot.type != ClassType.none and timeslot.type != self.type:\n raise ClassTypeError('class type does not match')\n # cancel or finish old onlineclass\n update_oc_sql = ('update {table} set status=:status, status_info=:status_info '\n 'where id=:id').format(table=self._tablename)\n update_oc_params = dict(status=status.value,\n status_info=status_info.value,\n id=self.id)\n db.execute(update_oc_sql, params=update_oc_params)\n # add new onlineclass\n add_sql = ('insert into {table} (course_id, lesson_id, period, teacher_id, '\n 'student_id, timeslot_id, schedule_timestamp, type, '\n 'status, status_info, provider ) values '\n '(:course_id, :lesson_id, :period, :teacher_id, :student_id, :timeslot_id, '\n ':schedule_timestamp, :type, :status, :status_info, :provider '\n ')').format(table=self._tablename)\n\n add_params = dict(\n course_id=self.course_id,\n lesson_id=self.lesson_id,\n period=self.period,\n teacher_id=timeslot.user_id,\n student_id=self.student_id,\n timeslot_id=timeslot.id,\n schedule_timestamp=timeslot.start_timestamp,\n type=self.type.value,\n status=self.status.value,\n status_info=self.status_info.value,\n provider=self.provider.value,\n )\n r = db.execute(add_sql, params=add_params)\n\n if r.lastrowid:\n id = str(r.lastrowid)\n db.commit()\n # bind new timeslot\n oc = self.get(id)\n timeslot.bind(oc)\n # available old timeslot\n self._update_timeslot_status_by_status_changed(status_info, scheduler)\n oc._end_timestamp = timeslot.end_timestamp\n self.clear_cache()\n # to clear pb cache\n oc.clear_cache()\n return oc\n\n db.rollback()\n finally:\n timeslot.locker.release()\n\n def change_student(self, student_id, status_info, **kwargs):\n scheduler, status = self._change_teacher_or_student_check(status_info, **kwargs)\n if not status_info.is_change_student_reason():\n raise ClassStatusInfoError\n return self._change_student(student_id, status, status_info)\n\n def _change_student(self, student_id, status, status_info):\n self.teacher_timeslot.locker.aquire()\n try:\n new_student_timeslot = StudentCachedTimeslot.get(student_id)\n node = CachedTimeslotNode(self._start_timestamp, self._end_timestamp)\n if new_student_timeslot.exist(node):\n raise CachedTimeslotDuplicateError\n\n # cancel or finish old onlineclass\n update_oc_sql = ('update {table} set status=:status, status_info=:status_info '\n 'where id=:id').format(table=self._tablename)\n update_oc_params = dict(status=status.value,\n status_info=status_info.value,\n id=self.id)\n db.execute(update_oc_sql, params=update_oc_params)\n # add new onlineclass\n add_sql = ('insert into {table} (course_id, lesson_id, period, teacher_id, '\n 'student_id, timeslot_id, schedule_timestamp, type, '\n 'status, status_info, provider ) values '\n '(:course_id, :lesson_id, :period, :teacher_id, :student_id, :timeslot_id, '\n ':schedule_timestamp, :type, :status, :status_info, :provider '\n ')').format(table=self._tablename)\n\n add_params = dict(\n course_id=self.course_id,\n lesson_id=self.lesson_id,\n period=self.period,\n teacher_id=self.teacher_id,\n student_id=student_id,\n timeslot_id=self.timeslot_id,\n schedule_timestamp=self.schedule_timestamp,\n type=self.type.value,\n status=self.status.value,\n status_info=self.status_info.value,\n provider=self.provider.value,\n )\n r = db.execute(add_sql, params=add_params)\n\n if r.lastrowid:\n try:\n new_student_timeslot.insert(node)\n except (CachedTimeslotDuplicateError, LockError):\n db.rollback()\n raise\n id = str(r.lastrowid)\n db.commit()\n # bind timeslot to new onlineclass\n oc = self.get(id)\n #\n self.teacher_timeslot.force_bind(oc)\n # remove old student timeslot\n self._remove_student_timeslot()\n self.clear_cache()\n # to clear pb cache\n oc._end_timestamp = self.teacher_timeslot.end_timestamp\n oc.clear_cache()\n return oc\n\n db.rollback()\n finally:\n self.teacher_timeslot.locker.release()\n\n @classmethod\n def get_booked_classes_by_lesson(cls, lesson_id):\n sql = ('select id from {table} '\n 'where lesson_id=:lesson_id '\n 'and status in (:created, :ready) '\n 'and schedule_timestamp > :now_ts '\n 'order by schedule_timestamp'\n ).format(table=cls._tablename)\n\n now_ts = datetime_to_timestamp(datetime.now(UTC_TZ))\n params = dict(\n lesson_id=lesson_id,\n now_ts=now_ts,\n created=Status.created.value,\n ready=Status.ready.value\n )\n\n rs = db.execute(sql, params=params).fetchall()\n db.commit()\n ids = [str(r[0]) for r in rs]\n return [cls.get(id_) for id_ in ids]\n\n def get_student_class_hour(self, **kwargs):\n return self.period\n\n def change_provider(self, provider):\n sql = ('update {table} set provider=:provider '\n 'where id=:id').format(table=self._tablename)\n params = dict(provider=provider.value, id=self.id)\n db.execute(sql, params=params)\n db.commit()\n self.clear_cache()\n\n def change_finish_status_info(self, status_info, scheduler):\n if not scheduler:\n raise Exception('need scheduler')\n self._check_change_finish_status_info(status_info)\n # NOTE: this feature is stupid\n validate_reason(self.status, status_info)\n sql = ('update {table} set status_info=:status_info '\n 'where id=:id').format(table=self._tablename)\n params = dict(status_info=status_info.value, id=self.id)\n db.execute(sql, params=params)\n db.commit()\n self.undo_count = self.undo_count + 1\n self.clear_cache()\n\n def bind(self, lesson_id):\n sql = ('update {table} set lesson_id=:lesson_id '\n 'where id=:id').format(table=self._tablename)\n params = dict(lesson_id=lesson_id, id=self.id)\n db.execute(sql, params=params)\n db.commit()\n self.clear_cache()\n\n def enroll(self, student_id, **kwargs):\n pass\n\n def has_enrolled(self, student_id):\n return student_id == self.student_id\n\n def is_canceled(self):\n return self.status == Status.canceled\n\n def is_finished(self):\n return self.status == Status.finished\n\n def to_ready(self):\n if self.status == Status.created:\n self._change_status(Status.ready)\n\n def is_ready(self):\n return self.status == Status.ready\n\n def can_be_canceled(self):\n if self.is_finished():\n return False\n if self.is_canceled():\n return False\n if not self.teacher_timeslot:\n return False\n start_ts = self.teacher_timeslot.start_timestamp\n now_ts = datetime_to_timestamp(datetime.now(tz=UTC_TZ))\n return start_ts > now_ts\n\n def can_be_finished(self):\n if self.is_canceled():\n return False\n if self.is_finished() and self.status_info != StatusInfo.finished_as_tmp:\n return False\n if not self.teacher_timeslot:\n return False\n start_ts = self.teacher_timeslot.start_timestamp\n now_ts = datetime_to_timestamp(datetime.now(tz=UTC_TZ))\n return start_ts <= now_ts\n\n def to_canceled(self, reason, **kwargs):\n scheduler = kwargs.get('scheduler')\n if not scheduler:\n raise Exception('need scheduler')\n _status = StatusInfo.get_status_from_status_info(reason)\n if _status != Status.canceled:\n raise ValueError('bad reason')\n if not self.can_be_canceled():\n raise ClassStatusError('can not cancel IN_CLASS class')\n self._change_status(Status.canceled, reason)\n self._update_timeslot_status_by_status_changed(reason, scheduler)\n self._remove_student_timeslot()\n\n def cancel_and_lock_timeslot(self, scheduler):\n \"\"\"Change student without new student will cancel class and lock timeslot\"\"\"\n if not self.can_be_canceled():\n raise ClassStatusError('can not cancel IN_CLASS class')\n now = datetime.now(tz=UTC_TZ)\n if self.schedule_time > now + timedelta(hours=24):\n reason = StatusInfo.canceled_student_no_deduction\n else:\n reason = StatusInfo.canceled_student_deduction\n self._change_status(Status.canceled, reason)\n self.teacher_timeslot.force_lock(scheduler)\n self._remove_student_timeslot()\n\n def update_user_entering_classroom_time(self, user_id, entering_ts):\n if str(user_id) == self.student_id:\n self.student_entering_time = int(entering_ts)\n self.clear_cache()\n elif str(user_id) == self.teacher_id:\n self.teacher_entering_time = int(entering_ts)\n self.clear_cache()\n else:\n raise ValueError('Cannot find user id in this class')\n\n def _remove_student_timeslot(self):\n student_timeslot = StudentCachedTimeslot.get(self.student_id)\n if self._start_timestamp and self._end_timestamp:\n node = CachedTimeslotNode(\n self._start_timestamp, self._end_timestamp)\n student_timeslot.remove(node)\n else:\n student_timeslot._clear_cache()\n\n def to_finished(self, reason, scheduler=None):\n from .mq import set_life_cycle_to_trial_finished_mq\n\n _status = StatusInfo.get_status_from_status_info(reason)\n if _status != Status.finished:\n raise ValueError('bad reason')\n if not scheduler:\n raise Exception('need scheduler')\n if not self.can_be_finished():\n raise ClassStatusError('Only IN_CLASS class can be finished')\n self._change_status(Status.finished, reason)\n self._update_timeslot_status_by_status_changed(reason, scheduler)\n self._remove_student_timeslot()\n job_body = '{id}:{type}'.format(id=self.id, type=self.type.value)\n try:\n set_life_cycle_to_trial_finished_mq.put(job_body)\n except Exception as e:\n extra = dict(error=str(e))\n client.captureMessage(\n 'set_life_cycle_to_trial_finished_mq error job_body=%s' % job_body, extra=extra)\n pass\n\n def _change_status(self, status, status_info=None):\n if status_info is None:\n status_info = StatusInfo.none\n validate_reason(status, status_info)\n if status in (Status.canceled, Status.finished):\n self._check_end_class_reason(status_info)\n sql = ('update {table} set status=:status, status_info=:status_info '\n 'where id=:id').format(table=self._tablename)\n params = dict(status=status.value, id=self.id)\n params['status_info'] = status_info.value\n db.execute(sql, params=params)\n db.commit()\n self.clear_cache()\n\n def _check_end_class_reason(self, status_info):\n now_ts = datetime_to_timestamp(datetime.now(UTC_TZ))\n if self.schedule_timestamp - now_ts >= 24 * 60 * 60:\n if not status_info.is_out_24H_reason():\n raise ClassStatusError('%s is not valid out 24H reason' % status_info.name)\n elif self.schedule_timestamp - now_ts >= 2 * 60 * 60:\n if not status_info.is_in_24H_reason():\n raise ClassStatusError('%s is not valid in 24H reason' % status_info.name)\n elif self.schedule_timestamp > now_ts:\n if not status_info.is_in_2H_reason():\n raise ClassStatusError('%s is not valid in 2H reason' % status_info.name)\n elif self.schedule_timestamp <= now_ts < self._end_timestamp:\n if not status_info.is_in_class_reason():\n raise ClassStatusError('%s is not valid in class reason' % status_info.name)\n else:\n if not status_info.is_after_class_reason():\n raise ClassStatusError('%s is not valid after class reason' % status_info.name)\n\n def _update_timeslot_status_by_status_changed(self, status_info, operator_id):\n if not self.teacher_timeslot:\n return\n if status_info.need_release_timeslot():\n self.teacher_timeslot.to_available(operator_id)\n elif status_info.need_cancel_timeslot():\n self.teacher_timeslot.to_canceled(operator_id)\n elif status_info.need_finish_timeslot():\n self.teacher_timeslot.to_finished(operator_id)\n\n def _check_change_finish_status_info(self, status_info):\n if self.undo_count >= MAX_UNDO_COUNT:\n raise ClassStatusError('cannot change finish status info more than 5 times')\n if self.status_info == StatusInfo.finished_as_tmp:\n raise ClassStatusError('finished_as_tmp cannot change status info')\n if status_info == StatusInfo.finished_as_tmp:\n raise ClassStatusError('cannot change back to finished_as_tmp')\n if self.status != Status.finished:\n raise ClassStatusError('not in finish status')\n if StatusInfo.get_status_from_status_info(status_info) != Status.finished:\n raise ClassStatusError('not in finish status')\n if status_info == StatusInfo.finished_as_as_scheduled:\n raise ClassStatusError('cannot change to finished_as_as_scheduled')\n if self.status_info == status_info:\n raise ClassStatusError('cannot change to same status info')\n now_ts = datetime_to_timestamp(datetime.now(tz=UTC_TZ))\n if self.schedule_timestamp + 7 * 24 * 60 * 60 < now_ts:\n raise ClassStatusError('cannot change status info after one week')\n\n def clear_pb_cache(self):\n mc.delete(ONLINE_CLASS_PB_CACHE_KEY % self.id)\n\n def clear_cache(self):\n mc.delete(ONLINE_CLASS_CACHE_KEY % self.id)\n ListCache(PB_ONLINE_CLASS_LIST_BY_TEACHER.format(teacher_id=self.teacher_id)).clear()\n ListCache(PB_ONLINE_CLASS_LIST_BY_STUDENT.format(student_id=self.student_id)).clear()\n self.clear_pb_cache()\n","sub_path":"jedi/jedi/models/onlineclass/onlineclass.py","file_name":"onlineclass.py","file_ext":"py","file_size_in_byte":34134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616759718","text":"from django.conf.urls import url, include\nfrom . import views\n\napp_name = 'employees'\n\nurlpatterns = [\n\n url(r'^$', views.index, name='home'),\n url(r'^create/$', views.EmployeeCRUD.create, name='create'),\n url(r'^edit/(?P<id>\\d+)/$', views.EmployeeCRUD.edit_employee, name='edit-employee'),\n url(r'^update/(?P<id>\\d+)/$', views.EmployeeCRUD.update, name='update'),\n url(r'^delete/(?P<id>\\d+)/$', views.EmployeeCRUD.delete, name='delete'),\n]\n","sub_path":"apps/employees/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219966036","text":"## Assignment 3 Solution\r\n# 3-Implement following sorting Algorithms Programmatically as well astheoretically:\r\n# \tA)\tBubble Sort.\r\n#\tB)\tQuick Sort.\r\n# \tC)\tSelection Sort.\r\n# \tD)\tMerge Sort.\r\n \r\n# NOTE* You have to submit a Document file along with your code file which contains explanation \r\n# of these Sorting Algorithms with images. Also you have to mention the Time Complexity \r\n# of each Sorting Algorithms.\r\n\r\n# Bubble sort\r\n# Worst Case Complexity O(n^2)\r\ndef bubble_sort(List):\r\n\tn = len(List)\r\n\r\n\tfor i in range(n):\r\n\t\tfor j in range(n-i-1):\r\n\t\t\tif List[j] > List[j+1]:\r\n\t\t\t\tList[j], List[j+1] = List[j+1], List[j]\r\n\t\tprint(\"After pass\",(i+1),\" :\", List)\r\n\r\n\r\n# Quick Sort\r\n# Worst Case Complexity O(n^2)\r\ndef quick_sort(List):\r\n\tdef partition(start, end):\r\n\t\tx = List[end-1]\r\n\t\ti = start - 1\r\n\r\n\t\tfor j in range(start, end-1):\r\n\t\t\tif List[j] <= x:\r\n\t\t\t\ti += 1\r\n\t\t\t\tList[i], List[j] = List[j], List[i]\r\n\r\n\t\tList[i+1], List[end-1] = List[end-1], List[i+1]\r\n\r\n\t\treturn i+1\r\n\r\n\tdef quick_sort_sub(start, end):\r\n\t\tif start < end:\r\n\t\t\tpartition_index = partition(start, end)\r\n\t\t\tquick_sort_sub(start, partition_index)\r\n\t\t\tquick_sort_sub(partition_index + 1, end)\r\n\r\n\tquick_sort_sub(0, len(List))\r\n\r\n\r\n# Selection Sort\r\n# Worst Case Complexity O(n^2)\r\ndef selection_sort(List):\r\n\tdef arg_min(i):\r\n\t\tmin_item, min_index = float('inf'), None\r\n\t\tfor j in range(i, len(List)):\r\n\t\t\tif List[j] < min_item:\r\n\t\t\t\tmin_item = List[j]\r\n\t\t\t\tmin_index = j\r\n\t\treturn min_index\r\n\r\n\t# Main sorting loop\r\n\tfor i in range(len(List)-1):\r\n\t\t# Find min element in unsorted part\r\n\t\tmin_index = arg_min(i)\r\n\r\n\t\t# Append the min_item to unsorted part\r\n\t\tList[i], List[min_index] = List[min_index], List[i]\r\n\r\n\r\n# Merge Sort\r\n# Worst Case Complexity O(n log n) \r\ndef merge_sort(List):\r\n\t# Function to sort two sorted sub arrays\r\n\tdef merge(l1, l2):\r\n\t\tl3 = []\r\n\t\ti = j = 0\r\n\r\n\t\twhile i<len(l1) and j<len(l2):\r\n\t\t\tif l1[i] < l2[j]:\r\n\t\t\t\tl3.append(l1[i])\r\n\t\t\t\ti += 1\r\n\t\t\telse:\r\n\t\t\t\tl3.append(l2[j])\r\n\t\t\t\tj += 1\r\n\r\n\t\tl3.extend(l1[i:]) if i<len(l1) else l3.extend(l2[j:])\r\n\r\n\t\treturn l3\r\n\r\n\tdef merge_sort_sub(l):\r\n\t\t# Base case\r\n\t\tif len(l) == 1:\r\n\t\t\treturn l\r\n\r\n\t\t# Call merge on sorted left and right parts\r\n\t\treturn merge(merge_sort_sub(l[:len(l)//2]), merge_sort_sub(l[len(l)//2:]))\r\n\r\n\treturn merge_sort_sub(List)\r\n\r\nif __name__ == '__main__':\r\n\tList = [7,5,4,6,2,3,9,10,1]\r\n\tprint(\"List = \", List)\r\n\tbubble_sort(List)\r\n\tprint(\"List after sorting using bubble sort :\", List)\r\n\tList = [7,5,4,6,2,3,9,10,1]\r\n\tprint(\"List = \", List)\r\n\tquick_sort(List)\r\n\tprint(\"List after sorting using quick sort :\", List)\r\n\tList = [7,5,4,6,2,3,9,10,1]\r\n\tprint(\"List = \", List)\r\n\tselection_sort(List)\r\n\tprint(\"List after sorting using selection sort :\", List)\r\n\tList = [7,5,4,6,2,3,9,10,1]\r\n\tprint(\"List = \", List)\r\n\tsorted_list = merge_sort(List)\r\n\tprint(\"Sorted list using merge sort :\", sorted_list)","sub_path":"July_23/Assignment 3 (Task 2)/Solution 2.py","file_name":"Solution 2.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50360238","text":"\"\"\"\nBase audio provider module.\n\"\"\"\n\nfrom typing import Dict, Optional\n\nfrom yt_dlp import YoutubeDL\n\nfrom spotdl.types import Song\nfrom spotdl.utils.config import get_temp_path\n\n\nclass AudioProviderError(Exception):\n \"\"\"\n Base class for all exceptions related to audio searching/downloading.\n \"\"\"\n\n\nclass YTDLLogger:\n \"\"\"\n Custom YT-dlp logger.\n \"\"\"\n\n def debug(self, msg):\n \"\"\"\n YTDL uses this to print debug messages.\n \"\"\"\n\n pass # pylint: disable=W0107\n\n def warning(self, msg):\n \"\"\"\n YTDL uses this to print warnings.\n \"\"\"\n\n pass # pylint: disable=W0107\n\n def error(self, msg):\n \"\"\"\n YTDL uses this to print errors.\n \"\"\"\n\n raise AudioProviderError(msg)\n\n\nclass AudioProvider:\n \"\"\"\n Base class for all other providers. Provides some common functionality.\n Handles the yt-dlp audio handler.\n \"\"\"\n\n def __init__(\n self,\n output_format: str = \"mp3\",\n cookie_file: Optional[str] = None,\n search_query: Optional[str] = None,\n filter_results: bool = True,\n ) -> None:\n \"\"\"\n Base class for audio providers.\n\n ### Arguments\n - output_directory: The directory to save the downloaded songs to.\n - output_format: The format to save the downloaded songs in.\n - cookie_file: The path to a file containing cookies to be used by YTDL.\n - search_query: The query to use when searching for songs.\n - filter_results: Whether to filter results.\n\n ### Errors\n - raises `NotImplementedError` if self.name is not set.\n \"\"\"\n\n self.output_format = output_format\n self.cookie_file = cookie_file\n self.search_query = search_query\n self.filter_results = filter_results\n\n if self.output_format == \"m4a\":\n ytdl_format = \"bestaudio[ext=m4a]/bestaudio/best\"\n elif self.output_format == \"opus\":\n ytdl_format = \"bestaudio[ext=webm]/bestaudio/best\"\n else:\n ytdl_format = \"bestaudio\"\n\n self.audio_handler = YoutubeDL(\n {\n \"format\": ytdl_format,\n \"quiet\": True,\n \"no_warnings\": True,\n \"encoding\": \"UTF-8\",\n \"logger\": YTDLLogger(),\n \"cookiefile\": self.cookie_file,\n \"outtmpl\": f\"{get_temp_path()}/%(id)s.%(ext)s\",\n \"retries\": 5,\n }\n )\n\n def search(self, song: Song) -> Optional[str]:\n \"\"\"\n Search for a song and return best match.\n\n ### Arguments\n - song: The song to search for.\n\n ### Returns\n - The url of the best match or None if no match was found.\n \"\"\"\n\n raise NotImplementedError\n\n def get_results(self, search_term: str, **kwargs):\n \"\"\"\n Get results from audio provider.\n\n ### Arguments\n - search_term: The search term to use.\n - kwargs: Additional arguments.\n\n ### Returns\n - A list of results.\n \"\"\"\n\n raise NotImplementedError\n\n def order_results(self, results, song: Song):\n \"\"\"\n Order results.\n\n ### Arguments\n - results: The results to order.\n - song: The song to order for.\n\n ### Returns\n - The ordered results.\n \"\"\"\n\n raise NotImplementedError\n\n def get_download_metadata(self, url: str, download: bool = False) -> Dict:\n \"\"\"\n Get metadata for a download using yt-dlp.\n\n ### Arguments\n - url: The url to get metadata for.\n\n ### Returns\n - A dictionary containing the metadata.\n \"\"\"\n\n try:\n\n data = self.audio_handler.extract_info(url, download=download)\n\n if data:\n return data\n except Exception as exception:\n raise AudioProviderError(f\"YT-DLP download error - {url}\") from exception\n\n raise AudioProviderError(f\"No metadata found for the provided url {url}\")\n\n @property\n def name(self) -> str:\n \"\"\"\n Get the name of the provider.\n\n ### Returns\n - The name of the provider.\n \"\"\"\n\n return self.__class__.__name__\n","sub_path":"spotdl/providers/audio/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"97084175","text":"import base64\nfrom functools import wraps\n\nfrom flask import Response, request\n\nfrom app.config import Config\n\n\ndef check(authorization_header):\n encoded = authorization_header.split()[-1]\n auth = Config.BASIC_AUTH_USER + \":\" + Config.BASIC_AUTH_PASSWORD\n if encoded == base64.b64encode(auth.encode(\"utf-8\")).decode(\"utf-8\"):\n return True\n\n\ndef basic_auth_required(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n try:\n authorization_header = request.headers.get('Authorization')\n if authorization_header and check(authorization_header):\n return f(*args, **kwargs)\n else:\n resp = Response()\n resp.headers['WWW-Authenticate'] = 'Basic'\n return resp, 401\n except Exception as e:\n raise e\n\n return decorated\n","sub_path":"app/middlewares/basic_authenticate.py","file_name":"basic_authenticate.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"317404821","text":"# import numpy as np\n\ndef main():\n\n arr = [35, 3, 5, 1, 10, 7, -3, 4]\n # arr = np.random.rand(200)\n arr = simple_sort(arr)\n \n print(arr)\n\ndef simple_sort(arr):\n checked_pos = 0\n length = len(arr)\n\n for i in range(length):\n # 対象とする範囲内での最小値を求める\n m = arr[i]\n min_pos = i\n for j in range(i, length):\n if arr[j] < m:\n m = arr[j]\n min_pos = j\n # print(arr, m, min_pos)\n # 入れ替える\n tmp = arr[i]\n arr[i] = arr[min_pos]\n arr[min_pos] = tmp\n \n return arr\n\nif __name__ == \"__main__\":\n main()","sub_path":"simple_sort.py","file_name":"simple_sort.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464174392","text":"# -*- coding: utf-8 -*-\n\"\"\"Application forms.\"\"\"\n\nfrom datetime import date\n\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.file import FileAllowed, FileField, FileRequired\nfrom pycountry import countries\nfrom wtforms import (BooleanField, Field, SelectField, SelectMultipleField, StringField,\n SubmitField, TextField, validators)\nfrom wtforms.fields.html5 import DateField, EmailField, URLField\nfrom wtforms.validators import UUID, DataRequired, Email, Regexp, Required, ValidationError, url\nfrom wtforms.widgets import HTMLString, TextArea, html_params\n\nfrom . import models\nfrom .config import DEFAULT_COUNTRY\n\n\ndef validate_orcid_id_field(form, field):\n \"\"\"Validate ORCID iD.\"\"\"\n if not field.data:\n return\n try:\n models.validate_orcid_id(field.data)\n except ValueError as ex:\n raise ValidationError(str(ex))\n\n\nclass PartialDate:\n \"\"\"Widget for a partical date with 3 selectors (year, month, day).\"\"\"\n\n __current_year = date.today().year\n\n def __call__(self, field, **kwargs):\n \"\"\"Render widget.\"\"\"\n kwargs.setdefault('id', field.id)\n html = [\"<!-- data: %r -->\" % (field.data, ), '<div %s>' % html_params(**kwargs)]\n html.extend(self.render_select(\"year\", field))\n html.extend(self.render_select(\"month\", field))\n html.extend(self.render_select(\"day\", field))\n html.append(\"</div>\")\n return HTMLString(''.join(html))\n\n @classmethod\n def render_select(cls, part, field):\n \"\"\"Render select for a specific part of date.\"\"\"\n yield \"<select %s>\" % html_params(name=field.name + \":\" + part)\n # If user didn't specifiy the date then the year range will start from current year + 5 years\n range_value = cls.__current_year + 5\n try:\n current_value = int(getattr(field.data, part))\n range_value = current_value + 5\n except Exception:\n current_value = None\n # TODO: localization\n yield \"<option %s>%s</option>\" % (html_params(value=\"\", selected=(current_value is None)),\n part.capitalize())\n option_format = \"<option %s>%04d</option>\" if part == \"year\" else \"<option %s>%02d</option>\"\n for v in range(range_value, 1912, -1) if part == \"year\" else range(\n 1, 13 if part == \"month\" else 32):\n yield option_format % (html_params(value=v, selected=(v == current_value)), v)\n yield \"</select>\"\n\n\nclass PartialDateField(Field):\n \"\"\"Partial date field.\"\"\"\n\n widget = PartialDate()\n\n def process(self, formdata, data=None):\n \"\"\"Process incoming data, calling process_data.\"\"\"\n self.process_errors = []\n if data is None:\n data = self.default or models.PartialDate()\n\n # self.object_data = data\n self.data = data\n\n if formdata is not None:\n new_data = {}\n for f in (\n \"year\",\n \"month\",\n \"day\",\n ):\n try:\n if (self.name + \":\" + f) in formdata:\n raw_val = formdata.get(self.name + \":\" + f)\n value = int(raw_val) if raw_val else None\n else:\n value = getattr(self.data, f)\n new_data[f] = value\n except ValueError as e:\n new_data[f] = None\n self.process_errors.append(e.args[0])\n self.data = models.PartialDate(**new_data)\n try:\n for filter in self.filters:\n self.data = filter(self.data)\n except ValueError as e:\n self.process_errors.append(e.args[0])\n\n\nclass CountrySelectField(SelectField):\n \"\"\"Country dropdown widget.\"\"\"\n\n # Order the countly list by the name and add a default (Null) value\n country_choices = [(c.alpha_2, c.name) for c in countries]\n country_choices.sort(key=lambda e: e[1])\n country_choices.insert(0, (\"\", \"Country\"))\n\n def __init__(self, *args, **kwargs):\n \"\"\"Set up the value list.\"\"\"\n if len(args) == 0 and \"label\" not in kwargs:\n kwargs[\"label\"] = \"Country\"\n super().__init__(*args, choices=self.country_choices, **kwargs)\n\n\nclass BitmapMultipleValueField(SelectMultipleField):\n \"\"\"Multiple value selection widget.\n\n No different from a normal multi select field, except this one can take (and\n validate) multiple choices and value (by defualt) can be a bitmap of\n selected choices (the choice value should be an integer).\n \"\"\"\n\n is_bitmap_value = True\n\n def iter_choices(self):\n \"\"\"Iterate through the list of choces.\"\"\"\n if self.is_bitmap_value and type(self.data) is int:\n for value, label in self.choices:\n yield (value, label, bool(self.data & value))\n else:\n yield from super().iter_choices()\n\n def process_data(self, value):\n \"\"\"Map selected value representation to the a list to internal domain value.\"\"\"\n try:\n if self.is_bitmap_value:\n self.data = [self.coerce(v) for (v, _) in self.choices if v & value]\n else:\n self.data = [self.coerce(v) for v in value]\n except (ValueError, TypeError):\n self.data = None\n\n def process_formdata(self, valuelist):\n \"\"\"Map submitted value to the domain value.\"\"\"\n try:\n if self.is_bitmap_value:\n self.data = sum(int(self.coerce(x)) for x in valuelist)\n else:\n self.data = [self.coerce(x) for x in valuelist]\n except ValueError:\n raise ValueError(\n self.gettext('Invalid choice(s): one or more data inputs could not be coerced'))\n\n def pre_validate(self, form):\n \"\"\"Pre-validate if it's not bit-map.\"\"\"\n if self.data and not self.is_bitmap_value:\n values = list(c[0] for c in self.choices)\n for d in self.data:\n if d not in values:\n raise ValueError(\n self.gettext(\"'%(value)s' is not a valid choice for this field\") %\n dict(value=d))\n\n\nclass RecordForm(FlaskForm):\n \"\"\"User/researcher employment detail form.\"\"\"\n\n org_name = StringField(\"Institution/employer\", [validators.required()])\n city = StringField(\"City\", [validators.required()])\n state = StringField(\"State/region\", filters=[lambda x: x or None])\n country = CountrySelectField(\"Country\", [validators.required()])\n department = StringField(\"Department\", filters=[lambda x: x or None])\n role = StringField(\"Role/title\", filters=[lambda x: x or None])\n start_date = PartialDateField(\"Start date\")\n end_date = PartialDateField(\"End date (leave blank if current)\")\n disambiguated_id = StringField(\"Disambiguated Organisation ID\")\n disambiguation_source = StringField(\"Disambiguation Source\")\n\n def __init__(self, *args, form_type=None, **kwargs):\n \"\"\"Create form.\"\"\"\n super().__init__(*args, **kwargs)\n if form_type == \"EDU\":\n self.org_name.name = self.org_name.label.text = \"Institution\"\n self.role.name = self.role.label.text = \"Course/Degree\"\n\n\nclass FileUploadForm(FlaskForm):\n \"\"\"Organisation info pre-loading form.\"\"\"\n\n file_ = FileField(\n validators=[FileRequired(),\n FileAllowed([\"csv\", \"tsv\"], 'CSV or TSV files only!')])\n\n\nclass JsonOrYamlFileUploadForm(FlaskForm):\n \"\"\"Funding info pre-loading form.\"\"\"\n\n file_ = FileField(\n validators=[FileRequired(),\n FileAllowed([\"json\", \"yaml\"], 'JSON or YAML file only!')])\n\n\nclass LogoForm(FlaskForm):\n \"\"\"Organisation Logo image upload form.\"\"\"\n\n logo_file = FileField(validators=[\n FileRequired(),\n FileAllowed([\"gif\", \"png\", \"jpg\"], 'Only image files allowed!')\n ])\n upload = SubmitField(\"Upload\", render_kw={\"class\": \"btn btn-primary\"})\n reset = SubmitField(\"Reset\", render_kw={\"class\": \"btn btn-danger\"})\n cancel = SubmitField(\"Cancel\", render_kw={\"class\": \"btn btn-invisible\"})\n\n\nclass EmailTemplateForm(FlaskForm):\n \"\"\"Email template form.\"\"\"\n\n email_template = TextField(\n widget=TextArea(), render_kw={\n \"style\": \"min-width: 800px;min-height: 550px;\"\n })\n email_template_enabled = BooleanField(default=False)\n prefill = SubmitField(\"Pre-fill\", render_kw={\"class\": \"btn btn-default\"})\n reset = SubmitField(\"Reset\", render_kw={\"class\": \"btn btn-danger\"})\n send = SubmitField(\"Send\", render_kw={\"class\": \"btn btn-primary\"})\n save = SubmitField(\"Save\", render_kw={\"class\": \"btn btn-success\"})\n cancel = SubmitField(\"Cancel\", render_kw={\"class\": \"btn btn-invisible\"})\n\n\nclass OnboardingTokenForm(FlaskForm):\n \"\"\"Form for requesting missing onboarding token.\"\"\"\n\n token = StringField(\"Token\", [validators.required()])\n\n\nclass RequiredIf(Required):\n \"\"\"Condition validator.\n\n A validator which makes a field required if\n another field is set and has a truthy value.\n \"\"\"\n\n def __init__(self, other_field_name, *args, **kwargs):\n \"\"\"Link the condtion field to the validator.\"\"\"\n self.other_field_name = other_field_name\n super().__init__(*args, **kwargs)\n\n def __call__(self, form, field):\n \"\"\"Validate conditionally if the linked field has a value.\"\"\"\n other_field = form._fields.get(self.other_field_name)\n if other_field is None:\n raise Exception(f'no field named \"{self.other_field_name}\" in form')\n if bool(other_field.data):\n super().__call__(form, field)\n\n\nclass OrgRegistrationForm(FlaskForm):\n \"\"\"Organisation registration/invitation form.\"\"\"\n\n org_name = StringField('Organisation Name', validators=[DataRequired()])\n org_email = EmailField('Organisation Email', validators=[DataRequired(), Email()])\n tech_contact = BooleanField(\"Technical Contact\", default=False)\n via_orcid = BooleanField(\"ORCID Authentication\", default=False)\n first_name = StringField(\n \"First Name\", validators=[\n RequiredIf(\"via_orcid\"),\n ])\n last_name = StringField(\n \"Last Name\", validators=[\n RequiredIf(\"via_orcid\"),\n ])\n orcid_id = StringField(\"ORCID iD\", [\n validate_orcid_id_field,\n ])\n city = StringField(\n \"City\", validators=[\n RequiredIf(\"via_orcid\"),\n ])\n state = StringField(\"State/Region\")\n country = CountrySelectField(\n \"Country\", default=DEFAULT_COUNTRY, validators=[\n RequiredIf(\"via_orcid\"),\n ])\n course_or_role = StringField(\"Course or Job title\")\n disambiguated_id = StringField(\"Disambiguated Id\")\n disambiguation_source = StringField(\"Disambiguation Source\")\n\n\nclass OrgConfirmationForm(FlaskForm):\n \"\"\"Registered organisation confirmation form.\"\"\"\n\n name = StringField('Organisation Name', validators=[DataRequired()])\n email = EmailField('Organisation EmailId', validators=[DataRequired(), Email()])\n show_api_credentials = BooleanField(\"Show API Credentials\", default=False)\n orcid_client_id = StringField(\n 'Organisation Orcid Client Id: ',\n validators=[\n DataRequired(),\n Regexp(r\"^\\S+$\", message=\"The value shouldn't contain any spaces\"),\n Regexp(\n r\"^APP-[A-Z0-9]+$\",\n message=(\"The Cient ID should match patter \"\n \"'APP-(sequence of digits or uppercase characters), \"\n \"for example, 'APP-FDFN3F52J3M4L34S'.\")),\n ])\n orcid_secret = StringField(\n 'Organisation Orcid Client Secret: ',\n validators=[\n DataRequired(),\n Regexp(r\"^\\S+$\", message=\"The value shouldn't contain any spaces\"),\n UUID(message=\"The secret should be a valid UUID\")\n ])\n country = CountrySelectField(\"Country\", [validators.required()], default=DEFAULT_COUNTRY)\n city = StringField(\"City\", [validators.required()])\n disambiguated_id = StringField(\"Disambiguated Id\", [validators.required()])\n disambiguation_source = StringField(\"Disambiguation Source\", [validators.required()])\n\n\nclass UserInvitationForm(FlaskForm):\n \"\"\"Single user invitation form.\"\"\"\n\n first_name = StringField(\"First Name\", [validators.required()])\n last_name = StringField(\"Last Name\", [validators.required()])\n email_address = EmailField(\"Email Address\", [validators.required(), Email()])\n orcid_id = StringField(\"ORCID iD\", [\n validate_orcid_id_field,\n ])\n department = StringField(\"Campus/Department\")\n organisation = StringField(\"Organisation Name\")\n city = StringField(\"City\", [validators.required()])\n state = StringField(\"State/Region\")\n country = CountrySelectField(\"Country\", [validators.required()], default=DEFAULT_COUNTRY)\n course_or_role = StringField(\"Course or Job title\")\n start_date = PartialDateField(\"Start date\")\n end_date = PartialDateField(\"End date (leave blank if current)\")\n is_student = BooleanField(\"Student\")\n is_employee = BooleanField(\"Staff\")\n disambiguated_id = StringField(\"Disambiguated Id\")\n disambiguation_source = StringField(\"Disambiguation Source\")\n resend = BooleanField(\"Resend\")\n\n\nclass DateRangeForm(FlaskForm):\n \"\"\"Simple date range selection form with ISO dates.\"\"\"\n\n from_date = DateField('DatePicker', format='%Y-%m-%d')\n to_date = DateField('DatePicker', format='%Y-%m-%d')\n\n\nclass ApplicationFromBase(FlaskForm):\n \"\"\"User/client application registration management form.\"\"\"\n\n name = StringField(\"Application name\", [validators.required()])\n homepage_url = StringField(\"Homepage URL\")\n description = TextField(\"Application Description\")\n callback_urls = TextField(\"Authorization callback URLs\")\n\n\nclass ApplicationFrom(ApplicationFromBase):\n \"\"\"Application client registration form.\"\"\"\n\n register = SubmitField(\"Register\", render_kw={\"class\": \"btn btn-primary mr-2\"})\n cancel = SubmitField(\"Cancel\", render_kw={\"class\": \"btn btn-invisible\"})\n\n\nclass CredentialForm(ApplicationFromBase):\n \"\"\"User/client application credential registration management form.\"\"\"\n\n client_id = StringField(\"Client ID\", render_kw={\"readonly\": True})\n client_secret = StringField(\"Client Secret\", render_kw={\"readonly\": True})\n revoke = SubmitField(\"Revoke all user tokens\", render_kw={\"class\": \"btn btn-danger\"})\n reset = SubmitField(\"Reset client secret\", render_kw={\"class\": \"btn btn-danger\"})\n update_app = SubmitField(\"Update application\", render_kw={\"class\": \"btn btn-primary mr-2\"})\n delete = SubmitField(\"Delete application\", render_kw={\"class\": \"btn btn-danger\"})\n\n\nclass WebhookForm(FlaskForm):\n \"\"\"Webhoook form.\"\"\"\n\n webhook_url = URLField(validators=[url()])\n webhook_enabled = BooleanField()\n email_notifications_enabled = BooleanField()\n save_webhook = SubmitField(\n \"Save\",\n render_kw={\n \"class\": \"btn btn-success\",\n \"data-toggle\": \"tooltip\",\n \"title\": \"Save Organisation webhook\"\n })\n","sub_path":"orcid_hub/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":15157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"510204457","text":"import matplotlib.pyplot as plt\nimport os\n\ndef plot_np(nparray, title=None):\n plt.scatter(nparray[:,0], nparray[:,1])\n if title:\n fig.suptitle(title, fontsize=20)\n plt.plot(nparray[0,:], 'rD')\n plt.plot(nparray[-1,:], 'ks')\n plt.show()\n\ndef plot_list(x,y, titlename=None):\n plt.scatter(x, y)\n if titlename:\n plt.title(titlename, fontsize=20)\n plt.plot(x[0], y[0], 'rD')\n plt.plot(x[-1], y[-1], 'ks')\n plt.show()\n\n\ndef plot_file(filename, title=None):\n x = []\n y = []\n with open(filename, \"r\") as trainfile:\n trainfile.readline() # skip header\n for line in trainfile:\n items = line.split(\",\")\n x.append(items[0])\n y.append(items[1])\n fig = plt.figure()\n plt.scatter(x, y)\n if title:\n fig.suptitle(title, fontsize=20)\n plt.plot(x[0], y[0], 'rD')\n plt.plot(x[-1], y[-1], 'ks')\n plt.show()\n\nif __name__ == '__main__':\n from random import sample, seed\n seed(42)\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"100.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"102.csv\"))\n #\n #\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"1.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"10.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"104.csv\"))\n #\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"101.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"108.csv\"))\n\n # Funky plots --Faked\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"107.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"112.csv\"))\n #\n # # Missing GPS values\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"117.csv\"))\n #\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"92.csv\"))\n foldername = os.path.join(\"data\", \"drivers\", \"191\")\n files = [os.path.join(foldername, f) for f in os.listdir(foldername) if os.path.isfile(os.path.join(foldername, f))]\n referencenum = 10\n referencefiles = [files[i] for i in sorted(sample(xrange(len(files)), referencenum))]\n for file in referencefiles:\n plot_file(file)","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"129600136","text":"# get pasted objects for copy-and-paste augmentation method\n# objects type are among categoryNames defined below\n\nfrom pycocotools.coco import COCO\nimport cv2\nimport math\n\nann_file_path = r\"path/to/annotation.json\"\nimg_path = r'path/to/images'\ncoco = COCO(ann_file_path)\nsave_path = r'path/to/cap_all_objects/'\n\n# get category infos\ncategoryNames = ['car', 'person', 'bus', 'motorbike', 'bicycle']\ncategoryIds = coco.getCatIds(catNms=categoryNames)\ncategoryInfos = coco.loadCats(categoryIds)\ncategoryIdToName = {cat['id']: cat['name'] for cat in categoryInfos}\n# {1: 'person', 2: 'bicycle', 3: 'car', 4: 'motorcycle', 6: 'bus'}\ncategoryCount = {cat['id']: 1 for cat in categoryInfos}\n\n# get all anninfos\nannids = coco.getAnnIds(catIds=categoryIds)\nanninfos = coco.loadAnns(annids)\n\n# for every anninfo\nfor anninfo in anninfos:\n # get imginfo according to anninfo\n imgid = anninfo['image_id']\n imginfo = coco.loadImgs([imgid])[0]\n # download image if not exists\n imgname = imginfo['file_name']\n img = cv2.imread(img_path+imgname, cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)\n # get mask according to segmentation annotation\n mask = coco.annToMask(anninfo) # 2d array, size same as img\n assert img.shape[:2] == mask.shape\n img[:, :, 3] = mask*255\n x, y, w, h = anninfo['bbox']\n if w*h <= 32*32:\n sizetype = 'small'\n elif w*h <= 96*96:\n sizetype = 'medium'\n else:\n sizetype = 'large'\n x2, y2 = x+w, y+h\n x, y = list(map(math.floor, [x, y]))\n x2, y2 = list(map(math.ceil, [x2, y2]))\n catid = anninfo['category_id']\n # save new image\n save_name = save_path+categoryIdToName[catid]+'_'+sizetype+'_'+str(categoryCount[catid])+'.png'\n cv2.imwrite(save_name, img[y:y2, x:x2])\n categoryCount[catid] += 1\n if categoryCount[catid] % 1000 == 0:\n print(f'processed {categoryIdToName[catid]} num: {categoryCount[catid]}')\n","sub_path":"utils/getPastedObjects.py","file_name":"getPastedObjects.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288274818","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n#\r\n# Complete the 'miniMaxSum' function below.\r\n#\r\n# The function accepts INTEGER_ARRAY arr as parameter.\r\n#\r\n\r\ndef miniMaxSum(arr):\r\n # Write your code here\r\n ans = []\r\n \r\n for i in range (0,len(arr)):\r\n Sum=0\r\n for j in range (0,len(arr)):\r\n if (j == i):\r\n continue\r\n else:\r\n Sum = Sum + arr[j]\r\n ans.append(Sum)\r\n \r\n print(min(ans),max(ans))\r\n \r\n\r\nif __name__ == '__main__':\r\n\r\n arr = list(map(int, input().rstrip().split()))\r\n\r\n miniMaxSum(arr)\r\n","sub_path":"Mini-Max Sum.py","file_name":"Mini-Max Sum.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80089967","text":"from rest_framework import viewsets\nfrom rest_framework import permissions\nfrom rest_framework.decorators import detail_route, list_route\nfrom rest_framework.response import Response\nfrom rest_framework import status as HTTPStatus\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\n\nfrom users.models import UserProfile, UserTogether\nfrom users.serializers import UserProfileSerializer, UserSerializer\n\nfrom utils.wechat import WeChat\nfrom utils.users import get_user_token_response, get_token_response_by_open_id\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n# Create your views here.\n\"\"\"\n1. 首页 LOGO\n2. 点击 LOGO 获取用户信息登录\n3. 一个人,单头像;两个人,双头像\n4. 点击下方跳转主页面\n\"\"\"\n\n\nclass UserProfileViewSet(viewsets.ModelViewSet):\n \"\"\"\n 自带有 detail 和 list\n \"\"\"\n queryset = UserProfile.objects.all()\n serializer_class = UserProfileSerializer\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n\n @list_route(methods=[\"POST\"], permission_classes=[permissions.AllowAny])\n def login(self, request):\n js_code = request.data.get(\"code\")\n open_id = request.data.get(\"open_id\")\n if open_id:\n token_response = get_token_response_by_open_id(open_id)\n return Response(token_response, status=HTTPStatus.HTTP_200_OK)\n elif js_code:\n we_chat = WeChat(settings.WECAHT_APPID, settings.WECHAT_SECRET)\n code_response = we_chat.login_by_code(js_code)\n open_id = code_response.get(\"openid\")\n if open_id:\n token_response = get_token_response_by_open_id(open_id)\n return Response(token_response, status=HTTPStatus.HTTP_200_OK)\n logger.error(\"no open_id or code\")\n return Response(\"No token\", status=HTTPStatus.HTTP_400_BAD_REQUEST)\n\n @list_route(methods=[\"GET\", \"PUT\"], permission_classes=[permissions.IsAuthenticated])\n def user_info(self, request, *args, **kwargs):\n if request.method == \"PUT\":\n profile = request.user.profile\n user_data = request.data\n avatar = user_data.pop(\"avatar\")\n partial = kwargs.pop('partial', True)\n if avatar:\n profile.avatar = avatar\n profile.save(update_fields=['avatar'])\n serializer = self.get_serializer(profile, data=user_data, partial=partial)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n\n if getattr(profile, '_prefetched_objects_cache', None):\n # If 'prefetch_related' has been applied to a queryset, we need to\n # forcibly invalidate the prefetch cache on the instance.\n profile._prefetched_objects_cache = {}\n return Response(get_user_token_response(request.user), status=HTTPStatus.HTTP_200_OK)\n\n return Response(get_user_token_response(request.user), status=HTTPStatus.HTTP_200_OK)\n\n @list_route(methods=[\"POST\"], permission_classes=[permissions.IsAuthenticated])\n def together(self, request, pk=None):\n \"\"\"创建用户关系\"\"\"\n object_id = request.data.get(\"objectID\")\n object_user = User.objects.filter(pk=object_id).first()\n if not object_user:\n logger.error(\"no such user:{}\".format(object_id))\n return Response({\"err_code\": \"40104\", \"err_msg\": \"找不到该对象\"}, status=HTTPStatus.HTTP_404_NOT_FOUND)\n\n # request.user / object_user 是否已经存在关系\n if UserTogether.objects.filter(Q(user_f=request.user) | Q(user_m=request.user)):\n logger.error(\"you already have relation with someone\")\n return Response({\"err_code\": \"40101\", \"err_msg\": \"你已经和某人建立关系了\"}, status=HTTPStatus.HTTP_409_CONFLICT)\n if UserTogether.objects.filter(Q(user_f=object_user) | Q(user_m=object_user)):\n logger.error(\"object already have relation with someone\")\n return Response({\"err_code\": \"40101\", \"err_msg\": \"对方已经和某人建立关系了\"}, status=HTTPStatus.HTTP_409_CONFLICT)\n\n # 自定义 manager 增加新的 get_or_create_together(user_a, user_b)\n user_together, is_created = UserTogether.objects.get_or_create_together(request.user, object_user)\n if not is_created:\n logger.warning(\"already exist relation with somebody\")\n return Response({\"err_code\": \"40102\", \"err_msg\": \"已经和对方建立过关系\"}, status=HTTPStatus.HTTP_409_CONFLICT)\n return Response({\"err_code\": \"0\", \"res\": {\"msg\": \"与对方成功建立关系\", \"you\": UserSerializer(object_user).data}})\n","sub_path":"Y_D/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211707476","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''archive.py - uploads all files with approved file names from\n'../data/local/downloads/' to Google Cloud Storage.\n\nNOTE: if the files already exist in the archive, this script will overwrite\nthem. It is your responsibility to make sure you don't wipe out the archive.\n\n'''\n\n# Libraries\nimport os\nimport argparse\nimport json\nfrom pprint import pprint\nimport re\nfrom google.cloud import storage\n\n\ndef valid_filename(filename):\n '''valid_filename: determines if the given filename is a real file. Assumes that the file is in the current working directory for the program.\n\n returns: given file name\n '''\n if not os.path.isfile(filename):\n msg = \"The given file '{}' does not exist at '{}'.\".format(\n filename,\n os.getcwd()\n )\n raise argparse.ArgumentTypeError(msg)\n\n return filename\n\n\ndef parse_args():\n '''parse_args: parses command line arguments. Returns a dictionary of arguments.\n '''\n parser = argparse.ArgumentParser(\n description='Archives data files to the Requex Google Cloud Storage archive.',\n prog='archive'\n )\n\n parser.add_argument('config_file',\n type=valid_filename,\n metavar='CONFIG_FILE',\n help=\"File path to requex configuration file. File must be in JSON format.\")\n parser.add_argument('-t', '--type', choices=['raw', 'merged', 'models'],\n help=\"Specify the type of data to be archived. 'raw' archives data downloaded from external data sources in '../data/local/downloads/' and is unmodified. 'merged' archives merged data files from '../data/local/staging/'. And 'models' archvies model files from '../data/local/models/'.\")\n\n return vars(parser.parse_args())\n\n\ndef get_config_filename(filename=None):\n '''get_config_filename: returns a verified Requex configuration file name. This function handles the ambiguity around whether the module was called from a shell with command line arguments or if called from another program using the run() function. If filename is none, the function assumes that there are\n\n return: string; valid filename.\n '''\n if filename is None:\n # get command line arguments\n args = parse_args()\n filename = args['config_file']\n else:\n if not os.path.isfile(filename):\n print(\"The given file '{}' does not exist at '{}'.\".format(\n filename,\n os.getcwd()\n ))\n exit(1)\n return filename\n\n\ndef get_config(filename):\n '''get_config: reads the configuration JSON file and stores values in a dictionary for processing.\n\n PRE: assumes the file already exists\n\n return: dict of configuration settings\n '''\n\n with open(filename, \"r\") as f:\n config = json.load(f)\n\n return config\n\n\ndef upload_blob(bucket_name, source_file_name, destination_blob_name):\n \"\"\"Uploads a file to the bucket.\"\"\"\n storage_client = storage.Client()\n bucket = storage_client.get_bucket(bucket_name)\n blob = bucket.blob(destination_blob_name)\n\n blob.upload_from_filename(source_file_name)\n\n print('success: file {} uploaded to {}.'.format(\n source_file_name,\n destination_blob_name))\n\n\ndef create_dest_filename(filename, date, file_map, data_type):\n '''create_dest_filename: takes the file name, archive date, and a dictionary that contains a file map and assembles the correct\n file path in the archive for the file's storage location.\n\n filename: the filename with extension, but without path\n date: string of the date where the file is to be stored in\n YYYY-MM-DD format\n file_map: dictionary of first three letters of a filename and the map to the root directory in the archive into which to store the file.\n data_type: Choices include: 'raw', 'merged', 'models'.\n\n returns: string; a gcs-formatted filename.\n '''\n year, month, day = date.split('-')\n\n basename = os.path.basename(filename)\n\n if data_type == 'raw':\n file_prefix = basename[:3]\n archive_dir = file_map.get(file_prefix)\n\n if archive_dir is not None:\n return archive_dir+'/'+year+'/'+month+'/'+day+'/'+basename\n else:\n return ''\n elif data_type == 'merged':\n file_prefix = basename[:len('merged')]\n if file_prefix == 'merged':\n return file_prefix+'/'+year+'/'+month+'/'+day+'/'+basename\n else:\n return ''\n elif data_type == 'models':\n # insert decision logic for 'model type' and 'model algo'\n # insert way to select the version number\n model_type = re.search(r'(?:binary|multiclass)|$', basename, flags=re.IGNORECASE).group()\n model_algo = re.search(r'(?:LSTM)|$', basename, flags=re.IGNORECASE).group()\n reg = re.compile(r'(?:_v\\d+)|$', flags=re.IGNORECASE)\n version = re.search(reg, basename).group()[1:].lower()\n if (model_type != '') and (model_algo != '') and (version != ''):\n return 'models/'+model_type+'/'+model_algo+'/'+year+'/'+month+'/'+day+'/'+version+'/'+basename\n else:\n return ''\n else:\n print(\"error: data_type '{}' is not a recognized type.\".format(data_type))\n exit(1)\n\n\ndef get_file_list(directory):\n return [f for f in os.listdir(directory)\n if os.path.isfile(directory+f)]\n\n\ndef run(config_file=None, data_type=None):\n # get configuration parameters\n config_file = get_config_filename(config_file)\n config = get_config(config_file)\n # print('configuration settings:')\n # pprint(config)\n if data_type is None:\n args = parse_args()\n data_type = args['type']\n elif data_type != 'raw' and data_type != 'merged' and data_type != 'models':\n print(\"error: archive.py called with invalid data_type option '{}'\".format(data_type))\n exit(1)\n\n # environment variable\n env_var = 'GOOGLE_APPLICATION_CREDENTIALS'\n\n # requex-svc file path for connecting to GCP storage bucket\n svc_path = config['root_dir']+config['google_auth_json']\n\n # set the local environment variable\n os.environ[env_var] = svc_path\n\n # filenames to exclude from renaming\n exclude = config['excluded_files']\n\n # approved file extensions\n if data_type == 'raw':\n # set the approved file extensions and source directory for 'raw' data\n # types.\n approved = config['data_formats_raw']\n source_dir = config['root_dir']+config['downloads_dir']\n elif data_type == 'merged':\n # set the approved file extensions and source directory for 'merged'\n # data types.\n approved = config['data_formats_merged']\n source_dir = config['root_dir']+config['staging_dir']\n elif data_type == 'models':\n # set the approved file extensions and source directory for 'models'\n # data types.\n approved = config['data_formats_models']\n source_dir = config['root_dir']+config['models_dir']\n else:\n print(\"error: data_type '{}' is not a recognized type.\".format(data_type))\n exit(1)\n\n # Google Cloud Storage archive name\n gcs_name = config['google_cloud_storage_archive']\n\n # get a list of all files in the source directory\n files = get_file_list(source_dir)\n\n # archive all file names that have a datestamp and approved extension\n for file in files:\n filename, extension = os.path.splitext(file)\n\n if filename in exclude:\n continue\n\n # only upload files with approved extensions and datestamps\n if extension in approved:\n # this makes sure a folder of files with different date stamps\n # get placed in the correct folder in the archive.\n found_date = re.search(r'\\d\\d\\d\\d-\\d\\d-\\d\\d|$', filename).group()\n if found_date != '':\n # file contains a date, archive it\n dest_file = create_dest_filename(\n source_dir+file,\n found_date,\n config['file_map'],\n data_type\n )\n if dest_file != '':\n # print(dest_file)\n upload_blob(gcs_name, source_dir+file, dest_file)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"code/pipeline/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":8340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"73430590","text":"\"\"\"prognosis_research URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', 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: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('allauth.urls')),\n path('', include('home.urls')),\n path('whats_new/', include('whats_new.urls')),\n path('prognosis/', include('prognosis.urls')),\n path('our_book/', include('our_book.urls')),\n path('methods_guidance/', include('methods_guidance.urls')),\n path('videos/', include('videos.urls')),\n path('courses_and_events/', include('courses_and_events.urls')),\n path('contact/', include('contact.urls')),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"prognosis_research/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526278758","text":"import os\nimport sys\nimport time\n# image operation\nfrom PIL import Image\nimport numpy as np\n# utils\nfrom .PCA import pca\n# detection and alignment\nfrom detection import detection\n\n# settings\ndata_root = \"./data\"\ndetector = detection.Detector()\n\n\n'''\nThis file is used to extract PCA feature of faces.\nData source: http://vis-www.cs.umass.edu/lfw/\nfaces: 13145\ntraining time: 3887 seconds (on Ubuntu 14.04, Intel core i7 3.40GHz * 8)\n\nInput face size: 150 * 170\n90% eigenvector: 89\n'''\n\ncount = 0\nimage_mat = []\nlabels = []\nfor file in os.listdir(data_root):\n # on mac os\n if file == '.DS_Store':\n continue\n\n for imagefile in os.listdir(os.path.join(data_root, file)):\n # read image\n image = Image.open(os.path.join(data_root, file, imagefile)).convert(mode='L')\n\n # detect face and landmark (must have one)\n faces = detector.detect(image)\n\n if len(faces) == 0:\n print('.', end='')\n count += 1\n sys.stdout.flush()\n continue\n\n face = np.array(faces[0].convert(mode='L'))\n\n face_vector = np.reshape(face, -1) # reshape to a row-vector\n\n image_mat.append(face_vector)\n labels.append(file)\n\nprint('\\nFind %d mis-detected faces!' % (count))\n\n# get the traning matrix\nimage_mat = np.array(image_mat, dtype=np.float32).T\nlabels = np.array(labels)\nprint(\"Collect %d faces!\" % (len(labels)))\n\n# run pca and save PC\nprint(\"Start PCA ...\")\n\nstart_time = time.time()\n[W_norm, v, mean] = pca(image_mat)\nprint('Finish in %s seconds!'%(time.time() - start_time))\n\nprint(\"saving...\")\nnp.save('../results/pca/Wnorm', W_norm)\nnp.save('../results/pca/eigenvalue', v)\nnp.save('../results/pca/mean', mean)\nprint('done!')\n","sub_path":"feature_extraction/PCA/exp_pca.py","file_name":"exp_pca.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491588755","text":"import copy\nimport base64\nimport hmac\nimport datetime\nimport time\nimport hashlib\nfrom hashlib import sha1\nfrom email.utils import formatdate\n\nfrom calendar import timegm\ntry:\n import simplejson as json\nexcept ImportError:\n import json\n\nfrom libcloud.utils.py3 import b\nfrom libcloud.utils.py3 import httplib\n\nfrom libcloud.common.base import ConnectionUserAndKey,JsonResponse\nfrom libcloud.common.types import InvalidCredsError, LibcloudError\n\nfrom libcloud.storage.base import Container,Object\nfrom libcloud.storage.drivers.s3 import BaseS3StorageDriver,BaseS3Connection\nfrom libcloud.storage.drivers.cloudfiles import CloudFilesStorageDriver\nfrom libcloud.storage.types import ContainerDoesNotExistError\nfrom libcloud.storage.types import InvalidContainerNameError\nfrom libcloud.storage.types import ContainerIsNotEmptyError\n\ndef aws_md5(data):\n \"\"\"Make an AWS-style MD5 hash (digest in base64).\"\"\"\n hasher = hashlib.new(\"sha1\")\n if hasattr(data, \"read\"):\n data.seek(0)\n while True:\n chunk = data.read(8192)\n if not chunk:\n break\n hasher.update(chunk)\n data.seek(0)\n else:\n if six.PY3 and isinstance(data, six.text_type):\n data = bytes(data, 'utf-8')\n hasher.update(data)\n\n return hasher.hexdigest()#.decode(\"ascii\")#hex(hasher.digest()).decode(\"ascii\")\n\n\nSINA_HOST = 'sinacloud.net'\n\nclass SinaResponse(JsonResponse):\n\n def success(self):\n return self.status in [httplib.OK, httplib.CREATED, httplib.NO_CONTENT]\n\n\n\nclass SinaConnection(ConnectionUserAndKey):\n\n host = SINA_HOST\n responseCls = SinaResponse\n secure = False\n\n def __init__(self,user_id,key,secure=False,host=None,port=None,url=None,timeout=None,proxy_url=None):\n super(SinaConnection,self).__init__(user_id,key,secure=False,host=host,port=port,url=url,timeout=timeout,proxy_url=proxy_url)\n\n def add_default_headers(self,headers):\n t = datetime.datetime.utcnow()\n headers['Date'] = formatdate(timegm(t.timetuple()),usegmt=True)\n return headers\n\n def pre_connect_hook(self,params,headers):\n if 'container_name' in params.keys():\n name = params['container_name']\n path = '/%s%s' %(name,self.action)\n headers['Host'] = '.'.join((params['container_name'],headers['Host']))\n else:\n path = self.action\n sign = self._get_aws_auth_param(method=self.method,headers=headers,params=params,expires=None,secret_key=self.key,path=path)\n headers['Authorization'] = 'SINA %s:%s' %(self.user_id,sign)\n params = {}\n params['formatter'] = 'json'\n return params, headers\n\n def _get_aws_auth_param(self,method,headers,params,expires,secret_key,path='/'):\n\n # StringToSign the same as S3\n # Signature = Base64(HMAC-SHA1('secret_key'),UTF-8-Encoding-Of(StringToSign))\n # ssig = Signature[5:15]\n # Authorization: SINA secret_key:ssig\n\n special_header_keys = ['content-md5', 'content-type', 'date']\n special_header_values = {'date':''}\n sina_header_values = {}\n\n headers_copy = copy.deepcopy(headers)\n for key, value in list(headers_copy.items()):\n key_lower = key.lower()\n if key_lower in special_header_keys:\n special_header_values[key_lower] = value.strip()\n elif key_lower.startswith('x-amz-') or key_lower.startswith('x-sina-'):\n sina_header_values[key.lower()] = value.strip()\n\n if 'content-md5' not in special_header_values:\n special_header_values['content-md5'] = ''\n\n if 'content-type' not in special_header_values:\n special_header_values['content-type'] = ''\n\n if 's-sina-sha1' in headers.keys():\n special_header_values['content-md5'] = headers['s-sina-sha1']\n\n special_header_values['date'] = headers['Date']\n\n keys_sorted = list(special_header_values.keys())\n keys_sorted.sort()\n\n buf = [method]\n for key in keys_sorted:\n value= special_header_values[key]\n buf.append(value)\n string_to_sign = '\\n'.join(buf)\n\n keys_sorted = list(sina_header_values.keys())\n keys_sorted.sort()\n\n sina_header_string = []\n for key in keys_sorted:\n value = sina_header_values[key]\n sina_header_string.append('%s:%s' %(key,value))\n sina_header_string = '\\n'.join(sina_header_string)\n\n values_to_sign = []\n for value in [string_to_sign,sina_header_string,path]:\n if value:\n values_to_sign.append(value)\n\n string_to_sign = '\\n'.join(values_to_sign)\n\n b64_hmac = base64.b64encode(hmac.new(b(secret_key),b(string_to_sign),sha1).digest())[5:15]\n return b64_hmac.decode('utf-8')\n\n def _user_agent(self):\n return None\n\n\n\nclass SinaStorageDriver(BaseS3StorageDriver):\n\n name = 'Sina (standard)'\n connectionCls = SinaConnection\n http_vendor_prefix = 'x-sina'\n supports_s3_multipart_upload = False\n\n def get_container(self, container_name):\n try:\n p = {}\n p['container_name'] = container_name\n response = self.connection.request(action='/?meta',params=p)\n if response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError(value=None,driver=self,container_name=container_name)\n except InvalidCredsError:\n pass\n return Container(name=container_name,extra=None,driver=self)\n\n def iterate_container_objects(self, container, ex_prefix=None):\n container_path = self._get_container_path(container)\n response = self.connection.request(container_path)\n\n if response.status != httplib.OK:\n raise LibcloudError('Unexpected status code: %s' %(response.status),driver=self)\n\n objs = json.loads(response.body)\n for obj in objs['Contents']:\n extra = {}\n yield Object(name=obj['Name'],size=int(obj['Size']),hash=obj['MD5'],extra=extra,meta_data=None,container=container,driver=self)\n\n def create_container(self, container_name):\n response = self.connection.request('/%s/' %(container_name),method='PUT')\n\n if response.status == httplib.OK:\n container = Container(name=container_name,extra=None,driver=self)\n return container\n elif response.status == httplib.CONFLICT:\n raise InvalidContainerNameError(value='Container with this name already exist, The name must be unique among all the containers in the system',container_name=container_name,driver=self)\n elif response.status == httplib.BAD_REQUEST:\n raise InvalidContainerNameError(value='Container name contains invalid characters.',container_name=container_name,driver=self)\n raise LibcloudError('Unexpected status code: %s' %(response.status),driver=self)\n\n def delete_container(self, container):\n response = self.connection.request('/%s/' %(container.name),method = 'DELETE')\n if response.status == httplib.NO_CONTENT:\n return True\n elif response.status == httplib.CONFLICT:\n raise ContainerIsNotEmptyError(value='Container must be empty before it can be deleted.',container_name=container_name,driver=self)\n elif response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError(value=None,driver=self,container_name=container.name)\n return False\n\n def _to_containers(self,obj,xpath):\n #obj = json.loads(obj)\n for container in obj['Buckets']:\n extra = {'CreationDate':container['CreationDate'],'ConsumedBytes':int(container['ConsumedBytes'])}\n yield Container(name=container['Name'],extra=extra,driver=self)\n\n def _get_container_path(self, container):\n return '/%s/' %(container.name)\n\n def _get_object_path(self, container, object_name):\n container_url = self._get_container_path(container)\n object_name_cleaned = self._clean_object_name(object_name)\n object_path = '%s%s' %(container_url,object_name_cleaned)\n return object_path\n\n def _headers_to_object(self, object_name, container, headers):\n hash = headers['etag'].replace('\"','')\n extra = {'content_type':headers['content-type'],\n 'etag': headers['etag']}\n meta_data = {}\n\n if 'last-modified' in headers:\n extra['last_modified'] = headers['last-modified']\n\n for key, value in headers.items():\n if not key.lower().startswith(self.http_vendor_prefix + '-meta-'):\n continue\n\n key = key.replace(self.http_vendor_prefix + '-meta-','')\n meta_data[key] = value\n\n obj = Object(name=object_name,size=headers['x-filesize'],\n hash=hash,extra=extra,\n meta_data=meta_data,\n container=container,\n driver=self)\n return obj\n\n def _put_object(self, container, object_name, upload_func,\n upload_func_kwargs, method='PUT', query_args=None,\n extra=None, file_path=None, iterator=None,\n verify_hash=True, storage_class=None):\n headers = {}\n extra = extra or {}\n\n if upload_func is self._upload_file:\n with open(file_path,'rb') as fp:\n headers['s-sina-sha1'] = aws_md5(fp)\n\n content_type = extra.get('content_type',None)\n meta_data = extra.get('meta_data',None)\n acl = extra.get('acl',None)\n\n if meta_data:\n for key, value in list(meta_data.items()):\n key = self.http_vendor_prefix + '-meta-%s' %(key)\n\n if acl:\n headers[self.http_vendor_prefix + '-acl'] = acl\n\n path = self._get_object_path(container,object_name)\n\n if query_args:\n path = '?'.join((path,query_args))\n\n result_dict = self._upload_object(\n object_name=object_name,content_type=content_type,\n upload_func=upload_func,\n upload_func_kwargs=upload_func_kwargs,\n request_path=path,request_method=method,\n headers=headers,file_path=file_path,\n iterator=iterator)\n\n response = result_dict['response']\n bytes_transferred = result_dict['bytes_transferred']\n headers = response.headers\n response = response.response\n\n if response.status == httplib.OK:\n obj = Object(name=object_name,size=bytes_transferred,\n hash=None,extra={'acl':acl},\n meta_data=meta_data,container=container,\n driver=self)\n return obj\n else:\n raise LibcloudError('Unexpected status code, status_code=%s' %(response.status),driver=self)\n\n\n\n","sub_path":"libcloud/storage/drivers/sina.py","file_name":"sina.py","file_ext":"py","file_size_in_byte":10916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26139190","text":"import boto3\nfrom botocore.client import ClientError\nimport zipfile,os\nimport utils as funct\nimport time\n\n#parameters defined\nparameter={\n\"InitBucketName\" : \"data-shivam\",\n\"BucketConfig\" : 'ap-south-1',\n\"YamlFileName\" : \"Template.yaml\",\n\"StackName\" : \"stack1\",\n\"SourceBucketName\" : \"shivam1052061\",\n\"YamlFilePath\" : \"https://shivam1052061-source.s3.ap-south-1.amazonaws.com/Template.yaml\",\n\"UploadFolderName\" : \"numbers\",\n\"deltagK\" : \"notdivby2\",\n\"deltagV\" : \"2no\"\n}\n\ns3 = boto3.resource('s3')\ntry:\n s3.create_bucket(Bucket=parameter[\"InitBucketName\"], CreateBucketConfiguration={'LocationConstraint':parameter[\"BucketConfig\"]})\nexcept ClientError:\n print(\"Data Bucket Already Created\")\n\nfunct.upload_object(parameter[\"InitBucketName\"], parameter[\"YamlFileName\"], parameter[\"YamlFileName\"])\n\nclient = boto3.client('cloudformation')\n\nstatus = funct.stack_status(parameter[\"StackName\"])\n\nif status == 'ROLLBACK_COMPLETE' or status == 'ROLLBACK_FAILED' or status == 'UPDATE_ROLLBACK_COMPLETE' or status == \\\n 'DELETE_FAILED':\n funct.delete_object(parameter[\"SourceBucketName\"])\n client.delete_stack(StackName=parameter[\"StackName\"])\n time.sleep(5)\n while funct.stack_status(parameter[\"StackName\"]) == 'DELETE_IN_PROGRESS':\n time.sleep(5)\n print(\"stack deleted\")\n funct.create_stack(parameter[\"StackName\"], parameter[\"YamlFilePath\"], parameter[\"SourceBucketName\"])\n print(\"stack created\")\nelif status == 'CREATE_COMPLETE' or status == 'UPDATE_COMPLETE':\n funct.update_stack(parameter[\"StackName\"], parameter[\"YamlFilePath\"], parameter[\"SourceBucketName\"])\n print(\"stack updated\")\nelse:\n funct.create_stack(parameter[\"StackName\"], parameter[\"YamlFilePath\"], parameter[\"SourceBucketName\"])\n print(\"stack created\")\n\nbucket = s3.Bucket(parameter[\"SourceBucketName\"])\nbucket.objects.all().delete()\n#remove hardcoding\n#main code\n\n#code for uploading the objects using the numbers folder\n\nfunct.upload_objects(parameter[\"SourceBucketName\"],parameter[\"UploadFolderName\"])\n\n'''\ni=1\nwhile i!=6:\n s3.Object(parameter[\"SourceBucketName\"], \"%d.txt\" % (i)).upload_file(Filename='numbers\\\\'+str(i)+'.txt')\n i=i+1\n'''\n\n#print(\"1-done\")\n#i=2\n#s3.Object('shivam1052061', \"%d.txt\" % (i)).upload_file(Filename='C:\\\\Users\\\\ADMIN\\\\PycharmProjects\\\\week2\\\\numbers\\\\'+str(i)+'.txt')\n\n#setting of object tags\nj=1\nclient = boto3.client('s3')\nwhile j!=5:\n if j%2==0:\n response1 = client.put_object_tagging(\n Bucket=parameter[\"SourceBucketName\"],\n Key='%d.txt'%(j),\n Tagging={\n 'TagSet': [\n {\n 'Key': 'divby2',\n 'Value': '2yes',\n\n\n },\n {\n 'Key': 'naturalno',\n 'Value': 'yes'\n }\n ]\n }\n )\n print(\"2-done\")\n\n j=j+1\n else:\n response1 = client.put_object_tagging(\n Bucket=parameter[\"SourceBucketName\"],\n Key='%d.txt' % (j),\n Tagging={\n 'TagSet': [\n {\n 'Key': 'naturalno',\n 'Value': 'yes'\n },\n {\n 'Key': 'notdivby2',\n 'Value': '2no'\n }\n ]\n }\n )\n j=j+1\n print(\"3-done\")\n#k=1\n\n#print(\"2-done\")\n#bucket = s3.Bucket('shivam1052061')\n# for my_bucket_object in bucket.objects.all():\n # print(my_bucket_object)\n# deletion of objects based on specific tags\n\n\nclient = boto3.client('s3')\n#deltagK='notdivby2'\n#deltagV='2no'\n\n\n\n#create a delete_tag function here\n\nbucket = s3.Bucket(parameter[\"SourceBucketName\"])\n\nfor key in bucket.objects.all():\n try:\n var=key.key\n response = client.get_object_tagging(\n Bucket=parameter[\"SourceBucketName\"],\n Key=var,\n )\n for tag in response.get('TagSet'):\n if tag.get('Key')==parameter[\"deltagK\"] and tag.get('Value')==parameter[\"deltagV\"]:\n response3 = client.delete_object(\n Bucket=parameter[\"SourceBucketName\"],\n Key=var\n )\n except:\n pass\n\n\n\n'''\n\nfor key in bucket.objects.all():\n var=key.key\n response = client.get_object_tagging(\n Bucket='shivam1052061',\n Key=var,\n )\n tagK = response['TagSet'][1]['Key']\n tagV = response['TagSet'][1]['Value']\n print(tagK + \" \")\n print(tagV + \" \")\n if tagK == deltagK and tagV == deltagV:\n # print(\"4-done\" + \" \")\n response3 = client.delete_object(\n Bucket='shivam1052061',\n Key=var\n )\n\n\n'''\n\n # print(\"4-doneanddusted\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n''' \n---------unused code------------\n\nclient = boto3.client('s3control')\nresponse = client.create_job(\n AccountId='682283364620 ',\n Operation={\n\n 'S3PutObjectTagging': {\n 'TagSet': [\n {\n 'Key': 'naturalnumber',\n 'Value': 'yo'\n },\n ]\n }\n },\n Report={\n 'Bucket': 'shivam1052061',\n 'Format': 'Report_CSV_20180820',\n 'Enabled': True,\n 'Prefix': 'string',\n 'ReportScope': 'AllTasks'\n },\n ClientRequestToken='',\n Manifest={\n 'Spec': {\n 'Format': 'json'\n },\n 'Location': {\n 'ObjectArn': 'string',\n 'ObjectVersionId': 'string',\n 'ETag': 'c81e728d9d4c2f636f067f89cc14862c'\n }\n },\n Description='string',\n Priority=2,\n RoleArn='string'\n)\n'''\n'''k=1\nprint(\"3-done\")\nwhile k!=10:\n response = client.get_object_tagging(\n Bucket='shivam1052061',\n Key=\"%d.txt\" % (k),\n )\n tagK=response['TagSet'][0]['Key']\n tagV = response['TagSet'][0]['Value']\n print(tagK+ \" \")\n print(tagV+ \" \")\n if tagK == deltagK and tagV == deltagV :\n print(\"4-\")\n response3 = client.delete_object(\n Bucket='shivam1052061',\n Key='%d.txt' % (k)\n )\n k=k+1\n print(\"4-done\")\n print(k)\n'''","sub_path":"handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":5882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643722777","text":"'''\nName: Kelsey Ackerman\nCS230: Section 5\nData: skyscrapers.csv\nURL: Link to your web application online (see extra credit)\nDescription: This program runs a streamlit application that displays skyscraper data.\nThe user can view a map graph of the data showing the locations of the structures in the skyscraper file.\nTHe user can view graphs based on structure type either viewing it by a bar graph or a piechart showing the percentage of\nbuilding types each structure makes up of the tallest buildings.\nThe user can view graphs based on country, showing the tallest structures in the country in a bar graph or comparing two\ncountries in a scatter plot.\n'''\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport streamlit as st\nimport pydeck as pdk\nimport numpy as np\nimport random\nfrom PIL import Image\n\nFILENAME = \"skyscrapers.csv\"\nB_GRAPHS = ['bar', 'pie chart']\nCOLORS = ['', 'pink', 'blue', 'cyan', 'magenta', 'purple', 'orange']\nDROPLIST = ['Home', 'By Structure Type', 'By Country', 'Map']\n\n\n# create country dropdown list\ndef country_droplist():\n # create country dropdown list\n df_countries = pd.read_csv(FILENAME, usecols=['Country']).drop_duplicates(subset=['Country'])\n # sort dataframe alphabetically\n df_sort = df_countries.sort_values(['Country'], ascending=[True])\n countries = df_sort.values.flatten().tolist()\n country_list = []\n dict_countries = {}\n # loop trhough each country\n for c in countries:\n country = c\n # get rid of leading space\n c = c.strip()\n # if country name is two words, abbreviate with first letter of each word\n if ' ' in c:\n c_split = c.split()\n c_abbrev = c_split[0][0] + c_split[1][0]\n # if country is one work, keep as one word\n else:\n c_abbrev = c\n # add c_abbrev to list\n country_list.append(c_abbrev)\n # add country to dictionary\n dict_countries[c_abbrev] = country\n\n return dict_countries, country_list\n\n\n# find how many skyscrapers are in the country in which the user will input\ndef country_df(df, country='United States'):\n # filter df to only rows where country is equal to the country the user inputs\n df_c = df[df['Country'] == country]\n df_c = df_c[['Name', 'Feet', 'Country', 'City', 'Year']]\n # sort dataframe\n df_c = df_c.sort_values(['Feet', 'Name'], ascending=[False, True])\n return df_c\n\n\n# create dataframe for building type from user input\ndef building_type(df, type='Skyscraper'):\n # filter df to only rows where type is equal to the type the user inputs\n df_type = df[df['Type'] == type]\n # specify the columns wanted for the dataframe\n df_type = df_type[['Name', 'Feet', 'Country', 'City']]\n # sort dataframe\n df_type = df_type.sort_values(['Feet', 'Name'], ascending=[False, True])\n st.subheader(f'{type}s Around the World')\n st.write(df_type)\n # get length of dataframe\n length = len(df_type)\n # if length is 10 or more, set the default value for the slider to 10\n if length >= 10:\n set_value = 10\n # else, set the default value to he length of it\n else:\n set_value = length\n return df_type, length, set_value\n\n\n# bar chart of the tallest buildings in a specific country or of the tallest skyscrapers(type of building) in the world\ndef bar_chart_country(df, country=' United States', color='orange'):\n # filter df to only rows where country is equal to the country the user inputs\n df_c = country_df(df, country)\n st.subheader(f'Structures in {country}')\n st.write(df_c)\n # sort dataframe\n sorted_df = df_c.sort_values(['Feet', 'Name'], ascending=[True, True])\n # create bar chart\n fig, ax = plt.subplots()\n x = sorted_df['Name']\n y = sorted_df['Feet']\n num = len(x)\n plt.bar(x, y, color=color)\n plt.title(f'Tallest Structures in the {country}')\n plt.ylabel('Height in Feet')\n plt.xlabel('Name of Structure')\n # rotate labels to make it easier to read\n plt.xticks(rotation=90)\n ax.set_xticks(x)\n return plt\n\n\n# function creates bar chart of different building types and shows their names and heights\ndef bar_chart_building(df, num, type='Skyscraper', color='blue'):\n # get head of rows with number specified from dataframe\n bar_df = df.head(num)\n # sort dataframe\n sorted_df = bar_df.sort_values(['Feet', 'Name'], ascending=[True, True])\n # create bar chart\n fig, ax = plt.subplots()\n # set x and y values\n x = sorted_df['Name']\n y = sorted_df['Feet']\n num = len(x)\n # plot bar chart\n plt.bar(x, y, color=color)\n plt.title(f'Top {num} Tallest {type}s in the World')\n plt.ylabel('Height in Feet')\n plt.xlabel(f'Name of {type}')\n # rotate labels to make it easier to read\n plt.xticks(rotation=90)\n ax.set_xticks(x)\n return plt\n\n# function that creates scatterplot of the heights of the buildings built in corresponding years\ndef scatter(df, c1, c2):\n # get dataframes for each country and display them\n df1 = country_df(df, c1)\n df2 = country_df(df, c2)\n st.subheader(f'Structures in{c1}')\n st.write(df1)\n st.subheader(f'Structures in{c2}')\n st.write(df2)\n # plot data\n plt.scatter(df1['Year'], df1['Feet'], color='magenta', marker='*')\n plt.scatter(df2['Year'], df2['Feet'], color='blue', marker='o')\n # create legend\n plt.legend([c1, c2], loc=0)\n plt.title(f'Years Structures were built in{c1} and{c2}')\n plt.ylabel(\"Structure's Height in Feet\")\n plt.xlabel('Year Built')\n\n return plt\n\n\n# function that creates pie chart of structure types\ndef pie_chart(df):\n # get counts of types and write to screen\n df_pie = df.groupby('Type')['Name'].count()\n st.write(df_pie)\n\n type_list = []\n count_list = []\n types = df['Type'].drop_duplicates().values.flatten().tolist()\n # for each type, add type to list, get count of structures of that type and add count to another list\n for t in types:\n data = df[df['Type'] == t]['Name'].count().astype(float)\n type_list.append(t)\n count_list.append(data)\n # plot in pie chart\n color = ['mistyrose', 'bisque', 'pink', 'azure', 'lavender', 'honeydew', 'peachpuff']\n plt.pie(count_list, labels=type_list, autopct='%1.1f%%', colors=color)\n plt.axis('equal')\n plt.title('Tallest Structure Types')\n return plt\n\n\n# call to create map graph\ndef map_graph():\n # map graph of the tallest skyscrapers around the world using the lat and long of the buildings\n st.subheader('Map of Tallest Structures Around the World')\n # create df for map\n df_map = pd.read_csv(FILENAME, usecols=['Name', 'Lat', 'Lon'])\n # rename lat and lon columns to lower case so that st.map will work\n df_map.columns = ['Name', 'lat', 'lon']\n # map df\n # set view\n view_state = pdk.ViewState(\n latitude=df_map[\"lat\"].mean(),\n longitude=df_map[\"lon\"].mean(),\n zoom=2,\n pitch=0)\n # create layer of scatterplots for each location\n layer1 = pdk.Layer('ScatterplotLayer',\n data=df_map,\n get_position='[lon, lat]',\n get_radius=100000,\n get_color=[random.randint(0, 2555), random.randint(0, 255), random.randint(0, 255)],\n pickable=True\n )\n # tool tip\n tool_tip = {\"html\": \"{Name}</br>({lat}, {lon})\",\n \"style\": {\"backgroundColor\": \"gray\",\n \"color\": \"white\"}\n }\n # create map\n map2 = pdk.Deck(map_style='mapbox://styles/mapbox/light-v9',\n initial_view_state=view_state,\n layers=[layer1],\n tooltip=tool_tip)\n # display map\n st.pydeck_chart(map2)\n\n\ndef main():\n st.header(\"Structures Around the World\")\n st.sidebar.header('Menu')\n choice = st.sidebar.selectbox('Select a category to display data:', DROPLIST)\n # read in file as a data frame\n df = pd.read_csv(FILENAME)\n # depending on choice, display correct things on screen\n if choice == 'Home':\n img = Image.open(\"skyscraper.jpg\")\n st.image(img)\n elif choice == 'By Structure Type':\n graph = st.sidebar.radio('Chart Type', B_GRAPHS)\n\n if graph == 'bar':\n color = st.sidebar.selectbox('Select a color:', COLORS)\n # create type drop down\n type_list = df['Type'].drop_duplicates().tolist()\n types = st.sidebar.selectbox('Select a structure type:', type_list)\n # get df of building type\n result = building_type(df, types)\n bar_df = result[0]\n length = result[1]\n set_value = result[2]\n num = st.sidebar.slider('Select the amount of top structures displayed:',\n min_value=1, max_value=length, value=set_value)\n if color != '':\n st.pyplot(bar_chart_building(df, num, types, color))\n else:\n st.pyplot(bar_chart_building(df, num, types))\n\n elif graph == 'pie chart':\n st.pyplot(pie_chart(df))\n\n elif choice == 'By Country':\n # display country dropdown list and get dictionary\n country_results = country_droplist()\n # set list from results\n country_list = country_results[1]\n # set dictionary from results\n country_dict = country_results[0]\n # add selectbox for countries\n countries = st.sidebar.selectbox('Select a Country:', country_list)\n # get full country name from dictionary\n country = country_dict[countries]\n # checkbox for comparing in a scatter plot\n compare = st.sidebar.checkbox('Compare with another country', False)\n if not compare:\n color = st.sidebar.selectbox('Select a color:', COLORS)\n # make and display bar chart\n if color != '':\n st.pyplot(bar_chart_country(df, country, color))\n else:\n st.pyplot(bar_chart_country(df, country))\n else:\n countries2 = st.sidebar.selectbox('Select a Second Country:', country_list)\n country2 = country_dict[countries2]\n st.pyplot(scatter(df, country, country2))\n\n elif choice == 'Map':\n map_graph()\n\n\nmain()\n","sub_path":"project/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":10310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"319777664","text":"import logging\nimport datetime\nfrom pythonjsonlogger.jsonlogger import JsonFormatter\n\nroot = logging.getLogger(__name__)\nroot = logging.getLogger()\nroot.setLevel(logging.INFO)\n\nsh = logging.StreamHandler()\n\n# log_format= dict([\n# ('asctime', 'asctime'),\n# ('name', 'name'),\n# ('levelname', 'levelname'),\n# ('message', 'message')])\n#\n# formatter = JsonFormatter(\n# fmt=log_format,\n# ensure_ascii=False,\n# mix_extra=True,\n# mix_extra_position='tail' # optional: head, mix\n# )\n\nlog_format = '%(asctime)%(name)%(levelname):%(message)'\nformatter = JsonFormatter(log_format)\n\nsh.setFormatter(formatter)\nsh.setLevel(logging.INFO)\nroot.addHandler(sh)\n\nfor logg in [logging.getLogger()] + [logging.getLogger(name) for name in logging.root.manager.loggerDict]:\n print(logg.name, logg.handlers)\n\n\nroot.info(\n 'test mix extra in fmt',\n extra={\n 'extra1': 'extra content 1',\n 'extra2': 'extra content 2'\n })\nroot.info(\n 'test mix extra in fmt',\n extra={\n 'extra3': 'extra content 3',\n 'extra4': 'extra content 4'\n })","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"35226031","text":"import os\nimport whoosh.index\nimport whoosh.fields\nimport whoosh.query\n\n\nclass WhooshIndexer:\n def __init__(self):\n fields = {\n \"path\":whoosh.fields.ID(unique=True, stored=True),\n \"author\":whoosh.fields.KEYWORD(stored=True),\n \"date\":whoosh.fields.DATETIME(stored=True),\n \"terms\":whoosh.fields.KEYWORD(stored = True, vector=True, scorable=True),\n \"body\" : whoosh.fields.NGRAM(stored=True)\n }\n self.schema = whoosh.fields.Schema(**fields)\n\n def make_dir(self,index_dir):\n\n os.mkdir(index_dir)\n self.index = whoosh.index.create_in(index_dir,self.schema)\n\n def load_dir(self,index_dir):\n self.index = whoosh.index.open_dir(index_dir)\n\n\n def add_email(self,path,subject,sender,rcpts,date,token_body, clean_body):\n with self.index.writer() as writer:\n writer.add_document(author = sender[0], date = date,terms = token_body)\n print(str(date) + \" : \" + subject + \" : \" + sender[0])\n\n def list_documents(self):\n with self.index.searcher() as searcher:\n reader = searcher.reader()\n for doc in reader.all_doc_ids():\n if reader.has_vector(doc, \"terms\"):\n stored = reader.stored_fields(doc)\n vec = searcher.vector_as(\"frequency\", doc, \"terms\") or []\n iterator = (term for term,cnt in vec for i in range(cnt))\n stored.update({\"terms\" : iterator})\n yield stored\n\n def most_distinctive_terms(self, number=7000):\n '''特有単語の取得'''\n with self.index.reader() as reader:\n for e in reader.most_distinctive_terms(\"terms\", number):\n yield e[0], e[1].decode('utf-8')\n\n def most_frequent_terms(self, number=7000):\n '''頻出単語の取得'''\n with self.index.reader() as reader:\n for e in reader.most_frequent_terms(\"terms\", number):\n yield e[0], e[1].decode('utf-8')\n\n","sub_path":"module/whoosh_module.py","file_name":"whoosh_module.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"36755487","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 1 14:09:40 2018\n\n@author: aoieht\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom numpy.linalg import inv\nfrom datetime import timedelta\n\n#导入事件样本\nevent_path = '../raw_data/event_sample.xlsx'\nevent_sample = pd.read_excel(event_path)\nevent_sample = event_sample.set_index(event_sample['股票代码'].map(str)+'@'+event_sample['会计年度'])\n\n#导入行业信息数据\nearning_forecast_path = '../raw_data/historical_earning_forecast.xlsx'\nearning_forecast_data = pd.read_excel(earning_forecast_path)\nindustry = pd.pivot_table(earning_forecast_data,index='证券代码',columns='报告期',values='Wind行业',aggfunc='first')\n\ntmp_columns = earning_forecast_data['Wind行业'].unique()\nindustry_re = pd.DataFrame(data=None,columns=tmp_columns,index=event_sample.index)\n\nfor e in range(len(event_sample)): #按事件作匹配\n try:\n tmp_stock = event_sample.iloc[e]['股票代码']\n tmp_fy = pd.to_datetime(event_sample.iloc[e]['会计年度'])\n tmp_industry = industry.loc[tmp_stock,tmp_fy]\n if tmp_industry in industry_re.columns:\n industry_re.iloc[e][tmp_industry] = 1\n industry_re.iloc[e] = industry_re.iloc[e].fillna(0)\n else: \n continue\n \n except:\n continue\n \nexceldata = industry_re\nexceldata.to_excel('event_industry.xlsx')","sub_path":"event_industry/event_industry_calculation.py","file_name":"event_industry_calculation.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68213232","text":"## Run the PyMC3 inference for a given input dataset and parameters\n\nimport numpy as np\nimport pymc3 as pm\nimport pymc3.math as ma\nimport theano.tensor as tt\nimport time as ttime\nimport os,sys,json\nfrom Chempy.parameter import ModelParameters\nfrom configparser import ConfigParser\n\n###########################\n# Read in parameter file\nif len(sys.argv)!=2:\n\tprint(\"Please supply parameter file\")\n\tsys.exit()\n\nConfig = ConfigParser()\nConfig.read(sys.argv[1])\n\nneural_model = Config.get('input','neural_model')\nmock_data_file = Config.get('input','mock_data_file')\noutfile = Config.get('input','outfile')\n\nall_n = json.loads(Config['inference']['all_n'])\nmax_stars = max(all_n)\nelem_err = Config.getboolean('inference','elem_err')\nmax_iteration = Config.getint('inference','max_iteration')\n\nchains = Config.getint('sampler','chains')\ncores = Config.getint('sampler','cores')\ntune = Config.getint('sampler','tune')\nn_init = Config.getint('sampler','n_init')\nn_samples = Config.getint('sampler','n_samples')\n\n######################\n\nos.chdir('/home/oliverphilcox/ChempyMulti/')\na=ModelParameters()\n\n# Load in the neural network weights\nmodel_numpy=np.load(neural_model)\nw_array_0=np.matrix(model_numpy[\"w0\"])\nb_array_0=np.matrix(model_numpy[\"b0\"])\nw_array_1=np.matrix(model_numpy[\"w1\"])\nb_array_1=np.matrix(model_numpy[\"b1\"])\n\n# Load standardization parameters\ninput_mean=model_numpy.f.in_mean\ninput_std=model_numpy.f.in_std\noutput_mean=model_numpy.f.out_mean\noutput_std=model_numpy.f.out_std\n\n# Load mock data\nmock_data=np.load(mock_data_file)\ntrue_Times = mock_data.f.true_time\nall_els = mock_data.f.elements\nmock_data.close()\n\n# Define priors\nLambda_prior_mean = a.p0[:2]\nTheta_prior_mean = a.p0[2:]\nLambda_prior_width = [0.3,0.3]\nTheta_prior_width = [0.3,0.1,0.1]\n\n# Now standardize\nstd_Lambda_prior_mean = (Lambda_prior_mean-input_mean[:2])/input_std[:2]\nstd_Lambda_prior_width = (Lambda_prior_width)/input_std[:2]\nstd_Theta_prior_mean = (Theta_prior_mean-input_mean[2:5])/input_std[2:5]\nstd_Theta_prior_width = (Theta_prior_width)/input_std[2:5]\n\n# Define critical theta edge:\nlog_SFR_crit = 0.29402\nstd_log_SFR_crit = (log_SFR_crit-input_mean[3])/input_std[3]\n\n# Define bounds on age to stop predicting out of parameter space:\nmin_time,max_time = [1.,13.8]\nstd_min_time,std_max_time=[(time-input_mean[-1])/input_std[-1] for time in [min_time,max_time]]\n\ndef n_star_inference(n_stars,iteration,elem_err=False,n_init=20000,n_samples=1000,max_stars=100): \n ## Define which stars to use\n these_stars = np.arange(max_stars)[iteration*n_stars:(iteration+1)*n_stars]\n \n ## Load in mock dataset\n mock_data=np.load(mock_data_file) #dataset\n mu_times = mock_data.f.obs_time[these_stars] #time of birth\n sigma_times = mock_data.f.obs_time_err[these_stars] #error on age\n all_els = mock_data.f.elements\n\n full_abundances = mock_data.f.abundances[these_stars] # chemical element abundances for data\n full_errors = mock_data.f.abundance_errs[these_stars] # error on abundances\n\n # Filter out correct elements:\n els = ['C','Fe','He','Mg','N','Ne','O','Si'] # TNG elements\n n_els = len(els)\n el_indices=np.zeros(len(els),dtype=int)\n for e,el in enumerate(els):\n for j in range(len(all_els)):\n if els[e]==str(all_els[j]):\n el_indices[e]=j\n break\n if j==len(all_els)-1:\n print(\"Failed to find element %s\"%el)\n obs_abundances = full_abundances[:,el_indices]\n obs_errors = full_errors[:,el_indices]\n\n # Now standardize dataset\n norm_data=(obs_abundances-output_mean)/output_std\n norm_sd = obs_errors/output_std\n\n data_obs = norm_data.ravel()\n data_sd = np.asarray(norm_sd).ravel()\n\n std_times_mean = (mu_times-input_mean[-1])/input_std[-1]\n std_times_width = sigma_times/input_std[-1]\n \n # Define stacked local priors\n Local_prior_mean = np.vstack([np.hstack([std_Theta_prior_mean,std_times_mean[i]]) for i in range(n_stars)])\n Local_prior_sigma = np.vstack([np.hstack([std_Theta_prior_width,std_times_width[i]]) for i in range(n_stars)])\n \n # Bound variables to ensure they don't exit the training parameter space\n lowBound = tt._shared(np.asarray([-5,std_log_SFR_crit,-5,std_min_time]))\n upBound = tt._shared(np.asarray([5,5,5,std_max_time]))\n \n # Create stacked mean and variances\n loc_mean=np.hstack([np.asarray(std_Theta_prior_mean).reshape(1,-1)*np.ones([n_stars,1]),std_times_mean.reshape(-1,1)])\n loc_std=np.hstack([np.asarray(std_Theta_prior_width).reshape(1,-1)*np.ones([n_stars,1]),std_times_width.reshape(-1,1)])\n \n # Share theano variables\n w0=tt._shared(w_array_0)\n b0=tt._shared(b_array_0)\n w1=tt._shared(w_array_1)\n b1=tt._shared(b_array_1)\n ones_tensor = tt.ones([n_stars,1])\n b0_all = ma.matrix_dot(ones_tensor,b0)\n b1_all = ma.matrix_dot(ones_tensor,b1)\n \n # Define PyMC3 Model\n simple_model=pm.Model()\n \n with simple_model:\n # Define priors\n Lambda = pm.Normal('Std-Lambda',mu=std_Lambda_prior_mean,\n sd=std_Lambda_prior_width,\n shape=(1,len(std_Lambda_prior_mean)))\n\n Locals = pm.Normal('Std-Local',mu=loc_mean,sd=loc_std,shape=loc_mean.shape,\n transform=pm.distributions.transforms.Interval(lowBound,upBound),\n )\n TimeSq = tt.reshape(Locals[:,-1]**2.,(n_stars,1))\n\n TruLa = pm.Deterministic('Lambda',Lambda*input_std[:2]+input_mean[:2])\n TruTh = pm.Deterministic('Thetas',Locals[:,:3]*input_std[2:5]+input_mean[2:5])\n TruTi = pm.Deterministic('Times',Locals[:,-1]*input_std[-1]+input_mean[-1])\n\n ## NEURAL NET\n Lambda_all = ma.matrix_dot(ones_tensor,Lambda)\n InputVariables = ma.concatenate([Lambda_all,Locals,TimeSq],axis=1)\n\n layer1 = ma.matrix_dot(InputVariables,w0)+b0_all\n output = ma.matrix_dot(ma.tanh(layer1),w1)+b1_all\n\n if elem_err:\n # ERRORS\n #element_error = pm.Normal('Element-Error',mu=-2,sd=1,shape=(1,n_els))\n element_error = pm.HalfCauchy('Std-Element-Error',beta=0.01/output_std,shape=(1,n_els))\n TruErr = pm.Deterministic('Element-Error',element_error*output_std)\n stacked_error = ma.matrix_dot(ones_tensor,element_error)\n tot_error = ma.sqrt(stacked_error**2.+norm_sd**2.) # NB this is all standardized by output_std here\n else:\n tot_error = norm_sd # NB: all quantities are standardized here\n\n predictions = pm.Deterministic(\"Predicted-Abundances\",output*output_std+output_mean)\n\n # Define likelihood function (unravelling output to make a multivariate gaussian)\n likelihood=pm.Normal('likelihood', mu=output.ravel(), sd=tot_error.ravel(), \n observed=norm_data.ravel())\n \n # Now sample\n init_time = ttime.time()\n with simple_model:\n samples=pm.sample(draws=n_samples,chains=chains,cores=cores,tune=tune,\n nuts_kwargs={'target_accept':0.9},init='advi+adapt_diag',n_init=n_init)\n end_time = ttime.time()-init_time\n\n def construct_output(samples):\n Lambda=samples.get_values('Lambda')[:,0,:]\n Thetas=samples.get_values('Thetas')[:,:,:]\n Times=samples.get_values('Times')[:,:]\n \n predictions = samples.get_values('Predicted-Abundances')[:,:,:]\n \n if elem_err:\n Errs = samples.get_values('Element-Error')[:,0,:]\n return Lambda,Thetas,Times,Errs,predictions\n else:\n return Lambda,Thetas,Times,predictions\n\n print(\"Finished after %.2f seconds\"%end_time)\n \n if elem_err:\n Lambda,Thetas,Times,Errs,predictions=construct_output(samples)\n return Lambda,Thetas,Times,end_time,Errs,predictions\n else:\n Lambda,Thetas,Times,predictions=construct_output(samples)\n return Lambda,Thetas,Times,end_time,predictions\n \n\n\n## RUN THE INFERENCE ##\nchain_params=[]\nfor nn in all_n:\n mini_chain=[]\n for iteration in range(max_stars//nn):\n if iteration>=max_iteration:\n break\n print(\"Starting inference using %d stars iteration %d of %d\"%(nn,iteration+1,min(max_iteration,max_stars//nn)))\n try:\n mini_chain.append(n_star_inference(nn,iteration,elem_err=elem_err,n_init=n_init,\n n_samples=n_samples,max_stars=max_stars))\n except ValueError or FloatingPointError:\n mini_chain.append(n_star_inference(nn,iteration,elem_err=elem_err,n_init=n_init,\n n_samples=n_samples,max_stars=max_stars))\n chain_params.append(mini_chain)\n\n## Save output\nprint(\"Saving output\")\nall_n = all_n[:len(chain_params)]\nall_Lambda = [[cc[0] for cc in c] for c in chain_params]\nall_Thetas = [[cc[1][:,:,:] for cc in c] for c in chain_params]\nall_Times = [[cc[2] for cc in c] for c in chain_params]\nall_timescale = [[cc[3] for cc in c] for c in chain_params]\nif elem_err:\n all_Err = [[cc[4] for cc in c] for c in chain_params]\nelse:\n all_Err=0.\nall_predictions = [[cc[-1] for cc in c] for c in chain_params]\n\nmean_timescale = [np.mean(all_timescale[i],axis=0) for i in range(len(all_timescale))]\n\nnp.savez(outfile,n_stars=all_n,Lambdas=all_Lambda,Thetas=all_Thetas,Times=all_Times,\n runtimes=all_timescale,Errors=all_Err,mean_runtimes=mean_timescale)\nprint(\"Inference complete: output saved to %s\"%outfile)\n","sub_path":"run_pymc3.py","file_name":"run_pymc3.py","file_ext":"py","file_size_in_byte":9501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"588852246","text":"import fresh_tomatoes\r\nimport movie\r\n#creating Toy Story object\r\ntoy_story = movie.Movie(\"Toy Story\",\r\n \"A story of a boy and his toys that come to live\",\r\n \"http://vignette4.wikia.nocookie.net/disney/images\"\\\r\n \"/4/4c/\"\\\r\n \"Toy-story-movie-posters-4.jpg/\"\r\n \"revision/latest?cb=20140816182710\",\r\n \"https://www.youtube.com/watch?v=4KPTXpQehio\")\r\n\r\n\r\n#creating Transformers object\r\ntransformers = movie.Movie(\"Transformers\",\r\n \"The fate of humanity is at stake when two races\"\\\r\n \"of robots,the good Autobots and the villainous\"\\\r\n \"Decepticons,bring their\"\\\r\n \"war to Earth. The robots have the\"\\\r\n \"ability to change into different mechanical\"\\\r\n \"objects\"\r\n \"as they seek the key to ultimate power. Only a\"\r\n \"human youth, Sam Witwicky (Shia LaBeouf)\"\\\r\n \"can save the world from total destruction.\",\r\n \"http://www.gstatic.com/tv/thumb/movieposters\"\r\n \"/159729/p159729_p_v8_aq.jpg\",\r\n \"https://www.youtube.com/watch?v=KrUhwet0ngg\")\r\n\r\n#creating Stomp The Yard object\r\nstomp_the_yard = movie.Movie(\"Stomp The Yard\",\r\n \"After his brother's death, a troubled but gifted\"\r\n \"street dancer enrolls in Atlanta's Truth\"\r\n \"University.As he tries to concentrate\"\r\n \"on his studies and woo a pretty\"\r\n \"classmate, he finds himself in the middle\"\\\r\n \"of a tug-of-war between fraternities, who want\"\r\n \"to utilize his talents in an upcoming\"\r\n \"dance competition.\",\r\n \"http://www.gstatic.com/tv/thumb/dvdboxart/\"\r\n \"162827/p162827_d_v8_aa.jpg\",\r\n \"https://www.youtube.com/watch?v=hvLzhK7Vatw\")\r\n#creating Get Out object\r\nget_out = movie.Movie(\"Get Out\",\r\n \"Now that Chris (Daniel Kaluuya) and his girlfriend, Rose\"\r\n \"(Allison Williams), have reached the meet-the-parents\"\\\r\n \"milestone of dating, she invites him for a weekend\"\r\n \"getaway upstate with Missy and Dean. At first, Chris\"\r\n \"reads the family's overly accommodating behavior\"\r\n \"as nervous attempts to deal with their daughter's\"\r\n \"interracial relationship,but as the weekend progresses\"\r\n \", a series of increasingly disturbing discoveries\"\r\n \"lead him to a truth that he never could have imagined.\",\r\n \"https://cdn.traileraddict.com/content/universal-pictures/\"\r\n \"get-out-2017-2.jpg\",\r\n \"https://www.youtube.com/watch?v=A2JbO9lnVLE\")\r\n\r\n#creating The Accountant object\r\nthe_accountant = movie.Movie(\"The Accountant\",\r\n \"Christian Wolff (Ben Affleck) is a mathematics\"\r\n \"savant with more affinity for numbers\"\r\n \"than people.Using a small-town CPA office\"\r\n \"as a cover, he makes his\"\r\n \"living as a freelance accountant for dangerous\"\\\r\n \"criminal organizations. With a Treasury agent\"\r\n \"(J.K. Simmons) hot on his heels,\"\r\n \"Christian takes on a\"\\\r\n \"state-of-the-art robotics company\"\r\n \"as a legitimate client\"\r\n \". As Wolff gets closer to the truth about a\"\\\r\n \"discrepancy that involves millions of dollars,\"\r\n \"the body count starts to rise.\",\r\n \"http://t0.gstatic.com/images?q=tbn:ANd9GcS\"\r\n \"TfMmvT_-0ELHJlI6OrXOoPCZqV6hlty_A6mvaABzaJRkoBgzW\",\r\n \"https://www.youtube.com/watch?v=DBfsgcswlYQ\")\r\n\r\n#creating guardians of the galaxy object\r\nguardians_of_the_galaxy = movie.Movie(\"Guardians of the Galaxy\",\r\n \"Brash space adventurer Peter Quill (Chris Pratt)\"\r\n \"finds himself the quarry of relentless bounty\"\r\n \"hunters\"\\\r\n \"after he steals an orb coveted by Ronan, a\"\r\n \"powerful villain. To evade Ronan, Quill is\"\r\n \"forced into an uneasy truce with four disparate\"\r\n \"misfits: gun-toting Rocket Raccoon,\"\r\n \"treelike-humanoid Groot,\"\\\r\n \"enigmatic Gamora, and vengeance-driven\"\r\n \"Drax the Destroyer.\"\r\n \"But when he discovers the orb's true\"\\\r\n \"power and the cosmic threat it poses, Quill must\"\r\n \"rally his ragtag group to save the universe.\",\r\n \"https://lh3.googleusercontent.com/-Glzj9zb8mRw/\"\r\n \"VDr1bPJxtTI/AAAAAAAAAMA/0VmhS2IK1Wc05tz\"\r\n \"gu4HoCN_pPROOkZcogCJoC/\"\r\n \"w800-h800/10672330_67188876625\"\r\n \"9482_6844791399166584697_n.jpg\",\r\n \"https://www.youtube.com/watch?v=d96cjJhvlMA\")\r\n#make list of favorite movies\r\nmovies = [toy_story, transformers, stomp_the_yard, get_out,\\\r\n the_accountant, guardians_of_the_galaxy]\r\n#pass list of favorite movies to open_movies_page\r\n#function defined in fresh_tomatoes\r\nfresh_tomatoes.open_movies_page(movies)\r\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":6028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"601735349","text":"import math\nimport numpy as np\nimport cv2\nfrom geo_helper import Line,Point\nclass Lane:\n\n def __init__(self):\n self.max_lines = 5\n\n\n def find_lines(self, image: np.ndarray):\n bw_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n bright_pixels = self.__find_bright_pixles(bw_image, 15)\n yellow_mask, white_mask = self.__find_white_yellow_masks(image)\n result = self.__integrate_masks(bright_pixels=bright_pixels,yellow_mask=yellow_mask, white_mask=white_mask)\n result = result * 255\n lines , mask= self.__hough_transform(result)\n return lines , mask\n\n def draw_lines_on_image(self, lines, image: np.ndarray):\n if lines is not None:\n for line in lines:\n cv2.line(img=image, pt1=(line.p1.x, line.p1.y), pt2=(line.p2.x, line.p2.y), color=(0, 0, 255),\n thickness=2)\n return image\n\n\n def __integrate_masks(self, bright_pixels: np.ndarray, yellow_mask: np.ndarray, white_mask: np.ndarray):\n white_or_yellow = cv2.bitwise_or(white_mask, yellow_mask)\n filtered_img = cv2.bitwise_and(bright_pixels,white_or_yellow)\n final_image = cv2.bitwise_or(filtered_img, yellow_mask)\n return final_image\n\n def __find_bright_pixles(self, image: np.ndarray, margin: int):\n threshold = 13 # 0.05 * 255\n bright_pixels = np.zeros_like(image)\n for y in range(0, bright_pixels.shape[0]):\n for x in range(margin, bright_pixels.shape[1] - margin):\n marg_dif = abs((int)(image[y, x-margin]) - (int)(image[y, x+margin]))\n bright_dif = 2 * (int)(image[y, x]) - (int)(image[y, x - margin]) - (int)(image[y, x + margin]) - marg_dif\n brightness = min(255, bright_dif)\n if brightness > threshold:\n bright_pixels[y,x] = 1\n return bright_pixels\n\n\n\n def __find_white_yellow_masks(self, image: np.ndarray):\n hsv_image = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\n hsv_image = np.asarray(hsv_image, dtype=np.float64) / 255\n\n hue_min = 0.1\n hue_max = 0.2\n sat_min = 0.35\n val_min = 0.5\n white_sat_max = 0.15\n white_val_min = 0.4\n\n im_mask_yellow = np.asarray(np.zeros((hsv_image.shape[0],hsv_image.shape[1])), dtype=np.uint8)\n im_mask_white = np.zeros_like(im_mask_yellow)\n for y in range(0, hsv_image.shape[0]):\n for x in range(0, hsv_image.shape[1]):\n pixel_hsv = hsv_image[y,x]\n if pixel_hsv[0] > hue_min and pixel_hsv[0] < hue_max and pixel_hsv[1] > sat_min and pixel_hsv[2] > val_min:\n im_mask_yellow[y, x] = 1\n if pixel_hsv[1] < white_sat_max and pixel_hsv[2] > white_val_min:\n im_mask_white[y, x] = 1\n return im_mask_yellow, im_mask_white\n\n def __hough_transform(self, image: np.ndarray):\n found_lines = []\n img_with_lines = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)\n lines = cv2.HoughLines(image=image, rho=20, theta=2 * np.pi / 180,threshold=10, min_theta=355 * np.pi / 180, max_theta=365 * np.pi / 180)\n if lines is not None:\n max_line_to_take = min(500, len(lines))\n for i in range(0, max_line_to_take):\n line = lines[i]\n rho = line[0][0]\n theta = line[0][1]\n a = math.cos(theta)\n b = math.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 1000 * (-b))\n y1 = int(y0 + 1000 * (a))\n x2 = int(x0 - 1000 * (-b))\n y2 = int(y0 - 1000 * (a))\n new_line = Line(Point(x1,y1), Point(x2,y2))\n self.__update_lines(found_lines,new_line, img_with_lines)\n self.draw_lines_on_image(found_lines, img_with_lines)\n return found_lines, img_with_lines\n\n\n def __update_lines(self, lines: list, new_line: Line, image: np.ndarray):\n if len(lines) >= self.max_lines:\n return\n found_close_line = False\n for existing_line in lines:\n if self.__lines_are_close(existing_line, new_line):\n found_close_line = True\n break\n\n if not found_close_line:\n lines.append(new_line)\n\n def __lines_are_close(self, line1 : Line , line2 : Line):\n if line1.intersect(line2) or line1.is_close_to(line2):\n print('found intersection: {0} , {1}'.format(line1, line2))\n return True\n return False\n\n\n\n\n\n\n\n","sub_path":"lane.py","file_name":"lane.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378336651","text":"\"\"\"\n This test just focuses on scripts - no pyinstaller binaries\n\n After failed run:\n 1) run pg_file_ops.check\n 2) run pg_file_ops.clean\n 3) pkill sf_eventmon\n 4) remove /onefs/monitor_tests (so it can go back into DB)\n 5) close_scan_by_id --scan-id <>\n After good run:\n 1) run pg_file_ops.check\n 2) run pg_file_ops.clean\n\"\"\"\nfrom trepan.api import debug\n\nfrom configparser import RawConfigParser\nimport os\nimport shutil\nimport signal\nimport stat\nimport subprocess as sp\nimport sys\nimport time\n\nimport pathfix # this needs to be first\n\nfrom sf_em_common.close_scan_by_id import main as close_scan_by_id\nfrom sf_em_common.testutils import check_output_wrapper, custom_scan_to_json, monitor_scan_to_json, one_scan_to_json, entry_to_json\nfrom sf_em_common.utils import make_sure_datadir_exists\n\nfrom pg_file_ops_base import TestMonitorFileOpsWithPostgresBase,arg_handler\n\"\"\"\n assumes script is running in virtual env\n start running instance of monitor (through dev env python script)\n run at least one case of each type - ADDED, CHANGED, MOVED, REMOVED\n run at least one case of utf8 (exotic) and not-utf8-compatible filenames\n inspect pg DB after ADDED and then other group of file ops\n\n uses config.ini in test/\n\n REFACTOR:\n may want to rework this to use a known permanent path (/opt instead of /ifs/monitor_test)?\n\"\"\"\n\"\"\"\n Base class defines the following methods:\n start_monitor():\n wait_for_monitor():\n stop_scan():\n wait_for_queue_binding(exchange,queue):\n wait_for_events_enabled():\n setup_test_dir():\n stop_event_generation():\n close_other_scans():\n teardown_class():\n create_files(file_list):\n change_file(target_file):\n rename_file(source_file):\n remove_file(target_file):\n wait_for_db(fname, not_in=False):\n check_added_file(fs_vol,added_file):\n check_changed_file(fs_vol,changed_file,mode=None,):\n check_moved_file(fs_vol,moved_file,is_source=False):\n check_removed_file(fs_vol,removed_file):\n check_files_in_DB():\n arg_handler():\n\n\"\"\"\nclass TestMonitorFileOpsWithPostgres(TestMonitorFileOpsWithPostgresBase):\n \"\"\"\n This test needs to have sf-agent running (assume it's a local instance, for now)\n Since we're using a preloaded vsn of onefs, assume /ifs already exists and is registered to SF\n perhaps adding volume to SF can happen here, too, but assume that I'm using preconfigured onefs client for now\n \"\"\"\n def __init__(self,args):\n \"\"\"\n uses config.ini in test/ by default. specify another file with --cfg option\n \"\"\"\n super(TestMonitorFileOpsWithPostgres,self).__init__(args)\n self.args.sf_package='pg-file-ops'\n self.onefs_fs = self.fs_dir\n self.onefs_vol=self.fs_vol\n self.isihost = self.config.get('test_monitor_file_ops','isihost')\n self.share = self.config.get('test_monitor_file_ops','share')\n self.onefs_queue = self.fs_queue\n self.onefs_exchange = self.fs_exchange\n\n def start_monitor(self):\n \"\"\"\n \"\"\"\n cmd_argument_list = ['--isihost',self.isihost,'--vol',self.onefs_vol,'--filesystem',self.onefs_fs]\n self.start_monitor_from_script(cmd_argument_list)\n def stop_scan(self):\n \"\"\"\n \"\"\"\n self.stop_scan_from_script()\n\n\n def check_files_in_DB(self):\n print(\"v\"*40,'check_files_in_DB',\"v\"*40)\n\n# self.test_filesD = {'added':'fAdd','changed':'fChange','moved':'fMove','removed':'fRemove'}\n added_file = self.test_filesD['added']\n changed_file = self.test_filesD['changed']\n removed_file = self.test_filesD['removed']\n source_moved_file = self.test_filesD['moved'] \n target_moved_file = self.test_filesD['moved'] + '.moved'\n \"\"\"\n target_file_a = self.test_filesD['utf-8']\n target_file_b = self.test_filesD['non-utf8']\n \"\"\"\n\n self.check_added_file(self.onefs_vol,added_file)\n self.check_changed_file(self.onefs_vol,changed_file,mode=0o755)\n self.check_moved_file(self.onefs_vol,source_moved_file,is_source=True)\n self.check_moved_file(self.onefs_vol,target_moved_file,is_source=False)\n self.check_removed_file(self.onefs_vol,removed_file)\n\n print(\"^\"*40,'check_files_in_DB',\"^\"*40)\n\n\n#--------------------------------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n \"\"\"\n start monitor with:\n python sf_eventmon --vol ifs --filesystem /ifs --serial \\\n --scan-id ${SCAN_ID} \\\n --vol ${VOL} ${DIR}\n\n\n \"\"\"\n print(\"-\"*50 + 'Setup Monitor' + \"-\"*50)\n args = arg_handler()\n# debug()\n file_ops_test = TestMonitorFileOpsWithPostgres(args)\n file_ops_test.test_filesD = {'added':'fAdd','changed':'fChange','moved':'fMove','removed':'fRemove'}\n file_ops_test.test_filesL = [v for v in file_ops_test.test_filesD.values()]\n file_ops_test.start_monitor()\n file_ops_test.wait_for_monitor()\n file_ops_test.wait_for_events_enabled()\n print(\"-\"*50 + 'Setup Test Dir' + \"-\"*50)\n file_ops_test.setup_test_dir()\n\n print(\"-\"*50 + 'Create Files' + \"-\"*50)\n file_ops_test.create_files(file_ops_test.test_filesL)\n added_file = file_ops_test.test_filesD['added']\n changed_file = file_ops_test.test_filesD['changed']\n removed_file = file_ops_test.test_filesD['removed']\n source_moved_file = file_ops_test.test_filesD['moved'] \n target_moved_file = file_ops_test.test_filesD['moved'] + '.moved'\n file_ops_test.wait_for_db(file_ops_test.test_filesD['added'])\n file_ops_test.wait_for_db(file_ops_test.test_filesD['removed'])\n\n try:\n print(\"-\"*50 + 'New File Ops' + \"-\"*50)\n file_ops_test.change_file(changed_file)\n file_ops_test.rename_file(source_moved_file)\n file_ops_test.wait_for_db(source_moved_file,True)\n file_ops_test.wait_for_db(target_moved_file)\n file_ops_test.remove_file(removed_file)\n file_ops_test.wait_for_db(file_ops_test.test_filesD['removed'],True)\n print(\"-\"*50 + 'Check Files' + \"-\"*50)\n file_ops_test.check_files_in_DB()\n except Exception:\n file_ops_test.stop_scan()\n file_ops_test.close_other_scans()\n raise Exception('Failure during file ops')\n try:\n#first close scan\n print(\"-\"*50 + 'Stop Scan' + \"-\"*50)\n file_ops_test.stop_scan()\n file_ops_test.stop_event_generation()\n except Exception:\n print(\"-\"*50 + 'Remove other Scans' + \"-\"*50)\n file_ops_test.close_other_scans()\n\n#clean DB, kill sf_eventmon\n print(\"-\"*50 + 'Stop Monitor' + \"-\"*50)\n# file_ops_test.teardown_class()\n","sub_path":"sf-onefs/tests/pg_file_ops.py","file_name":"pg_file_ops.py","file_ext":"py","file_size_in_byte":6683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"3843858","text":"import discord\nimport asyncio\nimport random\nimport aiohttp\nimport re\nfrom discord.ext import commands\nfrom config.secrets import *\nfrom utils.checks import embed_perms, cmd_prefix_len\nimport logging\nfrom urllib import parse\nfrom urllib.request import Request, urlopen\nfrom pymongo import MongoClient\nfrom datetime import datetime as dt\nfrom pprint import pformat\n\nlogger = logging.getLogger('discord')\n\nclass Roleplay(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.session = aiohttp.ClientSession(loop=self.bot.loop, headers={\"User-Agent\": \"AppuSelfBot\"})\n self.mongo_client = MongoClient()\n self.rp_db = self.mongo_client['rp']\n self.xp = self.rp_db.xp\n self.characters = self.rp_db.characters\n\n async def log_post(self, message):\n player_id = hash(message.author)\n res = self.xp.find_one(\n {\n 'id': player_id\n }\n )\n if not res:\n res = await self.create_xp(message=message)\n \n player_hist = res['history']\n player_xp = res['xp']\n now = dt.now()\n date = str(now.year*10000 + now.month*100 + now.day)\n if date in player_hist:\n player_hist[date] += 1\n else:\n player_hist[date] = 1\n player_xp += 1\n\n self.xp.update_one(\n {\n 'id': player_id\n },\n {\n '$set': {\n 'history': player_hist,\n 'xp': player_xp\n }\n }\n )\n\n async def create_xp(self, ctx=None, message=None, member=None):\n if not message:\n message = ctx.message\n if not member:\n member = message.author\n player_id = hash(member)\n player_name = str(member)\n res = self.xp.find_one(\n {\n 'name': player_name\n }\n )\n if res:\n channel = self.bot.get_channel(BOT_DEBUG_CHANNEL)\n await channel.send('Error: {}({}) already exists in database'.format(player_name, player_id))\n return res\n ret = {\n 'id': player_id,\n 'name': player_name,\n 'xp': 0,\n 'history': {}\n }\n self.xp.insert_one(ret)\n return ret\n\n async def create_character(self, ctx, name):\n message = ctx.message\n member = message.author\n player_id = hash(member)\n player_name = str(member)\n char_name = name\n res = self.characters.find_one(\n {\n 'name': player_name\n }\n )\n if res:\n channel = self.bot.get_channel(BOT_DEBUG_CHANNEL)\n await channel.send('Error: {}({}) already exists in database'.format(player_name, player_id))\n return res\n ret = {\n 'id': player_id,\n 'name': player_name,\n 'wounds': 0,\n 'strain': 0,\n 'soak': 0,\n 'defense': {\n 'ranged': 0,\n 'melee': 0\n },\n 'character': {\n 'name': char_name,\n 'career': '',\n 'specializations': [],\n 'species': '',\n 'base_skills': {\n 'INT': 0,\n 'BRA': 0,\n 'PRE': 0,\n 'WIL': 0,\n 'AGI': 0,\n 'CUN': 0\n },\n 'ranks': {\n 'astrogation': 0,\n 'athletics': 0,\n 'brawl': 0,\n 'charm': 0,\n 'coercion': 0,\n 'computers': 0,\n 'cool': 0,\n 'coordination': 0,\n 'cybernetics': 0,\n 'deception': 0,\n 'discipline': 0,\n 'education': 0,\n 'gunnery': 0,\n 'knowledge core worlds': 0,\n 'knowledge education': 0,\n 'knowledge lore': 0,\n 'knowledge outer rim': 0,\n 'knowledge underworld': 0,\n 'knowledge warfare': 0,\n 'knowledge xenology': 0,\n 'leadership': 0,\n 'lightsaber': 0,\n 'mechanics': 0,\n 'medicine': 0,\n 'melee': 0,\n 'negotiation': 0,\n 'perception': 0,\n 'piloting planetary': 0,\n 'piloting space': 0,\n 'ranged heavy': 0,\n 'ranged light': 0,\n 'resilience': 0,\n 'skullduggery': 0,\n 'stealth': 0,\n 'streetwise': 0,\n 'survival': 0,\n 'vigilance': 0,\n },\n 'skill_characteristic': {\n 'INT': [\n 'astrogation',\n 'computers',\n 'knowledge core worlds',\n 'knowledge education',\n 'knowledge lore',\n 'knowledge outer rim',\n 'knowledge underworld',\n 'knowledge warfare',\n 'knowledge xenology',\n 'cybernetics',\n 'mechanics',\n 'medicine'\n ],\n 'BRA': [\n 'athletics',\n 'brawl',\n 'lightsaber',\n 'melee',\n 'resilience'\n ],\n 'PRE': [\n 'charm',\n 'cool',\n 'leadership',\n 'negotiation'\n ],\n 'WIL': [\n 'coercion',\n 'discipline',\n 'vigilance'\n ],\n 'AGI': [\n 'coordination',\n 'gunnery',\n 'piloting planetary',\n 'piloting space',\n 'ranged heavy',\n 'ranged light',\n 'stealth'\n ],\n 'CUN': [\n 'deception',\n 'perception',\n 'skullduggery',\n 'streetwise',\n 'survival'\n ]\n },\n 'duty': {\n 'type': '',\n 'points': ''\n },\n 'critical_injuries': [],\n 'weapons': [],\n 'equipment': [],\n 'talents': [],\n 'credits': [],\n 'max_encumberance': 0,\n 'total_xp': 0,\n 'available_xp': 0,\n 'history_brief': '',\n 'appearance_brief': '',\n 'thumbnail': ''\n }\n }\n self.characters.insert_one(ret)\n return ret\n\n async def report_characters_pid(self, ctx, player_id):\n char = self.characters.find_one(\n {\n 'id': player_id\n }\n )\n # # Thanks to IgneelDxD for help on this\n # if str(user.avatar_url)[54:].startswith('a_'):\n # avi = 'https://images.discordapp.net/avatars/' + str(user.avatar_url)[35:-10]\n # else:\n # avi = user.avatar_url \n if char:\n if embed_perms(ctx.message):\n em = discord.Embed(colour=0x708DD0)\n name = char['name'] if char['name'] else 'None'\n character = char['character']['name'] if char['character']['name'] else 'None'\n career = char['character']['career'] if char['character']['career'] else 'None'\n specializations = ', '.join(char['character']['specializations']) if char['character']['specializations'] else 'None'\n species = char['character']['species'] if char['character']['species'] else 'None'\n appearance = char['character']['appearance_brief'] if char['character']['appearance_brief'] else 'None'\n em.add_field(name='Player', value=name, inline=True)\n em.add_field(name='Character', value=character, inline=True)\n em.add_field(name='Characteristics', value=' '.join(['**{0}**:{1}'.format(s, char['character']['base_skills'][s]) for s in char['character']['base_skills']]), inline=True)\n em.add_field(name='Career', value=career, inline=True)\n em.add_field(name='Species', value=species, inline=True)\n em.add_field(name='Specializations', value=specializations, inline=True)\n em.add_field(name='Appearance', value=appearance, inline=True)\n try:\n em.set_thumbnail(url=char['character']['thumbnail'])\n except:\n pass\n await ctx.send(embed=em)\n else:\n msg = 'Unimplemented'\n await ctx.send(msg) \n else:\n await ctx.send('Character not found.')\n\n async def get_player_by_ctx(self, ctx):\n player_id = hash(ctx.message.author)\n res = self.xp.find_one(\n {\n 'id': player_id\n }\n )\n if not res:\n res = await self.create_xp(ctx=ctx)\n return res\n\n async def get_player_by_id(self, ctx, player_id):\n res = self.xp.find_one(\n {\n 'id': hash(player_id)\n }\n )\n if not res:\n res = await self.create_xp(ctx=ctx)\n return res\n\n async def get_player_by_member(self, ctx, member):\n res = self.xp.find_one(\n {\n 'id': hash(member)\n }\n )\n if not res:\n res = await self.create_xp(ctx=ctx, member=member)\n return res\n\n @commands.command(pass_context=True, aliases=['new_character'])\n async def newchar(self, ctx, name):\n await self.create_character(ctx, name)\n await ctx.send('Character created.')\n\n @commands.command(pass_context=True, aliases=['character'])\n async def char(self, ctx):\n message = ctx.message\n member = message.author\n player_id = hash(member)\n await self.report_characters_pid(ctx, player_id)\n\n @commands.command(pass_context=True, aliases=['listxpraw'])\n async def xplistraw(self, ctx):\n res = self.xp.find()\n for entry in res:\n await ctx.send(pformat(entry))\n\n @commands.command(pass_context=True, aliases=['listxp'])\n async def xplist(self, ctx):\n res = self.xp.find()\n for entry in res:\n user = ctx.guild.get_member_named(entry['name'])\n try:\n if user.nick:\n username = user.nick\n else:\n username = user.name\n except:\n username = user.name\n await ctx.send('{} has {} XP.'.format(username, entry['xp']))\n\n @commands.command(pass_context=True)\n @commands.has_role(\"Vanir\")\n async def find_one(self, ctx, query: str):\n res = self.xp.find_one(\n eval(query)\n )\n await ctx.send(pformat(res))\n\n @commands.command(pass_context=True)\n @commands.has_role(\"Vanir\")\n async def update_one(self, ctx, query: str, request: str):\n res = self.xp.update_one(\n eval(query),\n eval(request)\n )\n await ctx.send(pformat(res))\n\n @commands.has_role(\"GameMaster\")\n @commands.command(pass_context=True)\n async def givexp(self, ctx, points: int, *, name: discord.Member=None):\n if name:\n try:\n user = ctx.message.mentions[0]\n except:\n user = ctx.guild.get_member_named(name)\n if not user:\n user = ctx.guild.get_member(int(name))\n if not user:\n await ctx.send('Could not find user.')\n return\n else:\n user = ctx.message.author\n res = await self.get_player_by_member(ctx, user)\n self.xp.update_one(\n {\n 'id': res['id']\n },\n {'$set': {\n 'xp': res['xp'] + points\n }}\n )\n await ctx.send(\"{0}'s XP is increased by {1}.\".format(res['name'], points))\n\n @commands.has_role(\"GameMaster\")\n @commands.command(aliases=['set_xp'],pass_context=True)\n async def setxp(self, ctx, points: int, *, name: discord.Member=None):\n # await ctx.send(\"{},{}\".format(points, name))\n if name:\n try:\n user = ctx.message.mentions[0]\n except:\n user = ctx.guild.get_member_named(name)\n if not user:\n user = ctx.guild.get_member(int(name))\n if not user:\n await ctx.send('Could not find user.')\n return\n else:\n user = ctx.message.author\n res = await self.get_player_by_member(ctx, user)\n # await ctx.send(\"{},{},{},{}\".format(user,hash(user),res,hash(ctx.message.author)))\n self.xp.update_one(\n {\n 'id': res['id']\n },\n {'$set': {\n 'xp': points\n }}\n )\n await ctx.send(\"{0}'s XP is set to {1}.\".format(str(user), points))\n\n @commands.command(aliases=['experience'],pass_context=True)\n async def xp(self, ctx, name: discord.Member=None):\n if name:\n try:\n user = ctx.message.mentions[0]\n except:\n user = ctx.guild.get_member_named(name)\n if not user:\n user = ctx.guild.get_member(int(name))\n if not user:\n await ctx.send('Could not find user.')\n return\n else:\n user = ctx.message.author\n res = await self.get_player_by_member(ctx,user)\n msg = await ctx.send('{} has {} xp.'.format(str(user), res['xp'])) \n\n @commands.command(aliases=['test'],pass_context=True)\n async def xptest(self, ctx):\n logger.debug('Calling XPtest')\n msg = await ctx.send('You have 10000000 xp.') ","sub_path":"commands/ded/rp.py","file_name":"rp.py","file_ext":"py","file_size_in_byte":14572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263050242","text":"import datetime\n\nfrom markupupdowndown import config\nfrom markupupdowndown.generators import render_plugin_skel\n\n\ndef init_subparser(subparsers):\n help_msg = 'create new plugin'\n parser_plugin = subparsers.add_parser('plugin', help=help_msg)\n parser_plugin.set_defaults(func=command_plugin)\n parser_plugin.add_argument('slug', action='store',\n help=\"path name for plugin\")\n\n\ndef command_plugin(args):\n render_plugin_skel(args.slug)\n","sub_path":"markupupdowndown/commands/new/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"201127865","text":"import shutil\n\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport re\nimport requests\nimport random\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nPIC_NUM = 505\n\ndef mkdir(path):\n floder = os.path.exists(path)\n if not floder:\n os.makedirs(path)\n print(\"new folder...\")\n print(\"OK\")\n else:\n print(\"there is a folder!\")\n\ndef get_dir_size(dir):\n size = 0\n for root, dirs, files in os.walk(dir):\n size += sum([os.path.getsize(os.path.join(root, name)) for name in files])\n return size\n\nheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/56.0.2924.87 Safari/537.36'}\n\nfileList = {'sunflower':'%E5%90%91%E6%97%A5%E8%91%B5','rose':\"%E7%8E%AB%E7%91%B0\",\n 'dandelion':\"%E8%92%B2%E5%85%AC%E8%8B%B1\",'daisy':'%E9%9B%8F%E8%8F%8A',\n 'tulip':\"%E9%83%81%E9%87%91%E9%A6%99\"}\n\nmkdir(\"temp\")\nfor item in fileList.keys():\n mkdir(item)\n page = 0\n count = 0\n while (count < PIC_NUM):\n print(str(count))\n url = \"https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=\"+fileList[item]+\"&pn=\"+str(count)+\\\n \"&ct=&ic=0&lm=-1&width=0&height=0\"\n print(url)\n html = urlopen(url).read().decode('utf-8')\n with open(\"temp\"+\"//\"+item+str(page)+'.html', 'w') as fp:\n fp.write(html)\n for addr in re.findall(str('\"objURL\":\"(.*?)\"'), html, re.S):\n if(count > PIC_NUM-1):\n continue\n print(\"正在爬取第\"+str(count)+\"张图片:\"+addr)\n try:\n pics = requests.get(addr,timeout = 10)\n except requests.exceptions.ConnectionError:\n print(\"Url请求错误\")\n fq = open(item+\"//\"+str(count)+\".png\", 'w+b')\n fq.write(pics.content)\n fq.close()\n count += 1\n print('下载完成。'+str(count))\n page += 1\n\nmkdir(\"test\")\nfor item in fileList.keys():\n for i in range(0,5):\n shutil.move(item+'//'+str(random.randint(0,505))+'.png', 'test//'+item+str(i)+'.png')\n\n\nsize = {}\nfor item in fileList.keys():\n size[item] = get_dir_size(item)\n print(item+' size is: %.3f Mb' % (size[item] / 1024 / 1024))\nsize['test'] = get_dir_size('test')\n\nprint('test size is: %.3f Mb' % (size['test'] / 1024 / 1024))\n#print(size)\n\n\nsunflower = [0]\nrose = [0]\ni = 0\nfor root, dirs, files in os.walk('sunflower'):\n sunflower = np.array([os.path.getsize(os.path.join(root, name)) for name in files]) / 1024\n i += 1\nsunflower.sort()\n#print(sunflower)\ni = 0\nfor root, dirs, files in os.walk('rose'):\n rose = np.array([os.path.getsize(os.path.join(root, name)) for name in files]) / 1024\n i += 1\nrose.sort()\n#print(rose)\nX = np.linspace(1,500,500,endpoint=True)\n\nsunflowerMean=np.mean(sunflower)\nroseMean = np.mean(rose)\n\nsunflowerVar = np.var(sunflower)\nprint('方差值为:'+str(sunflowerVar))\nroseVar = np.var(rose)\nprint('方差值为:'+str(roseVar))\n\n#曲线\nplt.scatter(X, sunflower, color = \"blue\", linewidth = 1.0,linestyle=\"-\", label = \"sunflower\")\nplt.scatter(X, rose, color = \"green\", linewidth = 1.0,linestyle=\"-\", label = \"rose\")\n#均值\nplt.axhline(y = sunflowerMean,color=\"red\",linestyle=\"dotted\", label = \"sunflowerMean\")\nplt.axhline(y = roseMean,color=\"grey\",linestyle=\"dotted\", label = \"sunflowerMean\")\n#99%分位线\nsunflowerPercentile99 = np.percentile(sunflower, 99)\nrosePercentile99 = np.percentile(rose, 99)\nplt.axhline(y = sunflowerPercentile99,color=\"yellow\",linestyle=\"dotted\", label = \"sunflowerPercentile99\")\nplt.axhline(y = rosePercentile99,color=\"black\",linestyle=\"dotted\", label = \"rosePercentile99\")\n#80%分位线\nsunflowerPercentile80 = np.percentile(sunflower, 80)\nrosePercentile80 = np.percentile(rose, 80)\nplt.axhline(y = sunflowerPercentile80,color='aliceblue',linestyle=\"dotted\", label = \"sunflowerPercentile80\")\nplt.axhline(y = rosePercentile80,color='mediumseagreen',linestyle=\"dotted\", label = \"rosePercentile80\")\n\nplt.xlabel(\"Pics\",fontsize=15)\nplt.ylabel(\"KB\",fontsize=15)\nplt.legend(loc='upper left')\n\nplt.show()","sub_path":"Spider.py","file_name":"Spider.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"652082295","text":"import pyautogui\nimport time\nimport sys\nimport datetime\n\n# sys.path.insert(0,'../');\n\nfrom firefox_auto import firefox_auto_api;\nfrom insta_auto import positionCache;\n\npyautogui.FAILSAFE = True;\npyautogui.PAUSE = 2;\n\n\n# insta_auto config data\nlogMessageFileObj = None;\n\ndisplayResolution = 1080; # 1920x1080x32\n\nnextImage_ICON = \"\";\nprevImage_ICON = \"\";\nlikeImage_ICON = \"\";\nlikedImage_ICON = \"\";\n\nnoOfPagesDownsForLatestPic = 0;\nfirstLatestImageLocationX = 0;\nfirstLatestImageLocationY = 0;\npixelRangeForFirstLatestImage = 0;\n\nretryLimit = 7;\nretryDelay = 1;\n\n\n# log screenshot to file\ndef logScreenshot(fileName = \"a.jpg\"):\n pyautogui.screenshot(fileName);\n\n\n# log message to log file\ndef logMessage(fileName = \"insta_auto_api.log\",msg = \"\"):\n global logMessageFileObj;\n \n T = str(datetime.datetime.now());\n \n if(logMessageFileObj == None):\n logMessageFileObj = open(fileName,\"a\");\n logMessageFileObj.write(T+\"::\"+msg+\"\\n\");\n \n\n\n# initialize insta config data\ndef init_InstaAutoConfigData(display_resolution = 1080,\n retry_limit = 7,\n retry_delay = 2):\n \n global displayResolution;\n\n global nextImage_ICON;\n global prevImage_ICON;\n global likeImage_ICON;\n global likedImage_ICON;\n\n global noOfPagesDownsForLatestPic;\n global firstLatestImageLocationX;\n global firstLatestImageLocationY;\n global pixelRangeForFirstLatestImage;\n\n global retryLimit;\n global retryDelay;\n\n\n retryLimit = retry_limit;\n retryDelay = retry_delay;\n\n \n if(displayResolution == 600):\n displayResolution = 600;\n\n nextImage_ICON = 'data/images/insta_NextImage_disp800x600_2122017.png';\n prevImage_ICON = 'data/images/insta_PrevImage_disp800x600_2122017.png';\n likeImage_ICON = 'data/images/insta_Like_disp800x600_2122017.png';\n likedImage_ICON = 'data/images/insta_Liked_disp800x600_2122017.png';\n\n noOfPagesDownsForLatestPic = 2;\n firstLatestImageLocationX = 127;\n firstLatestImageLocationY = 531;\n pixelRangeForFirstLatestImage = 20;\n\n elif(displayResolution == 720):\n displayResolution = 720;\n\n nextImage_ICON = './data/images/insta_NextImage_disp1280x720_15012018.png';\n prevImage_ICON = './data/images/insta_PrevImage_disp1280x720_15012018.png';\n likeImage_ICON = './data/images/insta_Like_disp1280x720_15012018.png';\n likedImage_ICON = './data/images/insta_Liked_disp1280x720_15012018.png';\n\n noOfPagesDownsForLatestPic = 2;\n firstLatestImageLocationX = 289;\n firstLatestImageLocationY = 646;\n pixelRangeForFirstLatestImage = 50;\n\n elif(displayResolution == 1080):\n displayResolution = 1080;\n\n nextImage_ICON = './data/images/insta_NextImage_disp1280x720_15012018.png';\n prevImage_ICON = './data/images/insta_PrevImage_disp1280x720_15012018.png';\n likeImage_ICON = './data/images/insta_Like_disp1280x720_15012018.png';\n likedImage_ICON = './data/images/insta_Liked_disp1280x720_15012018.png';\n\n noOfPagesDownsForLatestPic = 1;\n firstLatestImageLocationX = 560;\n firstLatestImageLocationY = 750;\n pixelRangeForFirstLatestImage = 100;\n\n return True;\n\n\n\n\n\n\n\ndef clickLatestPic():\n try:\n # go to home/start of page\n ret_val = firefox_auto_api.goToTopOfPage();\n if(ret_val == None or ret_val == False):\n logMessage(msg = \"Error: firefox api failed to go top of the page\");\n return False;\n\n # go two pages down\n ret_val = firefox_auto_api.goPageDown(noOfPages = noOfPagesDownsForLatestPic);\n if(ret_val == None or ret_val == False):\n logMessage(msg = \"Error: firefox api failed to go down page for No.of pages :\"+str(noOfPagesDownsForLatestPic));\n return False;\n \n # click on possible first image\n try:\n pyautogui.click(firstLatestImageLocationX, firstLatestImageLocationY);\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to click on first image, err:\"+str(e));\n return False;\n \n # wait till the image loads\n count = 0;\n while(count < retryLimit):\n xy = isNextImage();\n if(xy == None): \n time.sleep(retryDelay);\n else:\n break;\n count += 1;\n \n if(count >= retryLimit):\n logMessage(msg = \"Error: Latest Image is not loaded after multiple tries\");\n return False;\n \n except Exception as e:\n logMessage(msg = \"Error: unknown cause: \"+str(e));\n return None;\n \n return True;\n\n\n\n\n\nnextIMG_positionCache = positionCache.positionCache(img = nextImage_ICON);\ndef isNextImage():\n global nextIMG_positionCache;\n try:\n # nextIMG_position = pyautogui.locateOnScreen(nextImage_ICON);\n nextIMG_position = nextIMG_positionCache.locateOnScreen(img = nextImage_ICON);\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to locate next icon to confirm next Image; with err :\"+str(e));\n return None;\n return nextIMG_position;\n\n\n\n\nprevIMG_positionCache = positionCache.positionCache(img = prevImage_ICON);\ndef isPrevImage():\n global prevIMG_positionCache;\n \n try:\n # prevIMG_position = pyautogui.locateOnScreen(prevImage_ICON);\n prevIMG_position = prevIMG_positionCache.locateOnScreen(img = prevImage_ICON);\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to locate prev-icon to confirm prev image; with err :\"+str(e));\n return None;\n return prevIMG_position;\n \n\n\n\n\nlike_positionCache = positionCache.positionCache(img = likeImage_ICON);\ndef likeImage():\n global like_positionCache;\n \n try:\n # get like icon position\n # like_position = pyautogui.locateOnScreen(likeImage_ICON);\n like_position = like_positionCache.locateOnScreen(img = likeImage_ICON);\n if(like_position == None):\n logMessage(msg = \"Error: pyautogui failed to locate like icon\");\n return False;\n else:\n # click like\n try:\n pyautogui.click(like_position[0]+10, like_position[1]+10);\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to click like; with err :\"+str(e));\n return False;\n # confirm liked\n if(isLiked() == None or isLiked() == False):\n logMessage(msg = \"Error: clicking like did not work. like icon did not turn liked!\");\n return False;\n except Exception as e:\n logMessage(msg = \"Error: unknown error while liking image; with err :\"+str(e));\n return None;\n\n return True;\n\n\n\n\nliked_positionCache = positionCache.positionCache(img = likedImage_ICON);\ndef isLiked():\n global liked_positionCache;\n \n try:\n # liked_position = pyautogui.locateOnScreen(likedImage_ICON);\n liked_position = liked_positionCache.locateOnScreen(img = likedImage_ICON);\n if(liked_position == None):\n return False;\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to locate liked icon with err :\"+str(e));\n return None;\n \n return True;\n\n\n\n\n\ndef nextImage():\n global nextIMG_positionCache;\n \n try:\n # nextIMG_position = pyautogui.locateOnScreen(nextImage_ICON);\n nextIMG_position = nextIMG_positionCache.locateOnScreen(img = nextImage_ICON);\n if(nextIMG_position == None):\n logMessage(msg = \"Error: pyautogui failed to locate next icon\");\n return False;\n else:\n pyautogui.click(nextIMG_position[0]+5,nextIMG_position[1]+5);\n except Exception as e:\n logMessage(msg = \"Error: unknown error while locating next icon with err :\"+str(e));\n return None;\n \n return True;\n\n\n\n\n\n\n\ndef getHashTagLink(tag = None):\n if(tag == None):\n logMessage(msg = \"Error: no tag passed to generate instagram hash-tag link\");\n return None;\n \n link = \"https://www.instagram.com/explore/tags/\"+tag+\"/\";\n \n return link;\n\n","sub_path":"insta_auto/insta_auto_api.py","file_name":"insta_auto_api.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"527599781","text":"\"\"\"\nFunctions to modify customer information in the customers.db table.\n\"\"\"\nimport logging\nfrom peewee import JOIN, DoesNotExist\nimport create_db\nimport customer_model as cm\n\n\nlogging.basicConfig(level=logging.INFO)\nLOGGER = logging.getLogger(__name__)\ncreate_db.main()\n\n\ndef add_customer(customer_id, name, lastname, home_address, phone_number, email_address, active, credit_limit):\n \"\"\"\n Adds a customer to the database. Must have all parameters set for full customer record.\n\n :param customer_id: Customer identification number\n :param name: First name\n :param lastname: Last name\n :param home_address: Home address of customer\n :param phone_number: Phone number of customer\n :param email_address: Email address of current customer\n :param active: Boolean of customer status\n :param credit_limit: Customer's credit limit\n :return: None\n \"\"\"\n try:\n with cm.database.transaction():\n contact_id = cm.Identity.create(\n customer_id=customer_id,\n name=name,\n last_name=lastname,\n credit_limit=credit_limit,\n active=active\n )\n contact_id.save()\n LOGGER.info(f\"Succesfully added record to Identity {contact_id.customer_id}: {contact_id.last_name}\")\n\n except Exception as e:\n LOGGER.info(f'Error creating = {customer_id}: {name} {lastname}')\n LOGGER.info(e)\n\n try:\n with cm.database.transaction():\n contact_info = cm.Contact.create(\n home_address=home_address,\n email_address=email_address,\n phone_number=phone_number,\n customer_id=customer_id\n )\n contact_info.save()\n\n LOGGER.info(f\"Contact updated successfully with {contact_info.customer_id}: {contact_info.home_address}\")\n\n except Exception as e:\n LOGGER.info(f'Error creating = {customer_id}: {home_address}')\n LOGGER.info(e)\n\n\ndef search_customer(customer_id):\n \"\"\"\n Finds a customer information based on their\n :param customer_id:\n :return:\n \"\"\"\n customer_info = dict()\n try:\n with cm.database.transaction():\n customer = cm.Identity \\\n .select(cm.Identity, cm.Contact) \\\n .join(cm.Contact, JOIN.INNER) \\\n .where(cm.Contact.customer_id == customer_id) \\\n .get()\n\n customer_info['name'] = customer.name\n customer_info['lastname'] = customer.last_name\n customer_info['email_address'] = customer.contact.email_address\n customer_info['phone_number'] = customer.contact.phone_number\n\n except DoesNotExist:\n LOGGER.warning(f\"The customer ID {customer_id} does not exist in the database\")\n\n return customer_info\n\n\ndef delete_customer(customer_id):\n \"\"\"\n Deletes a customer record and all associated information\n based on the input of their customer identification number.\n :param customer_id: Customer Identification number\n :return: None\n \"\"\"\n\n try:\n with cm.database.transaction():\n customer = cm.Identity \\\n .select(cm.Identity.customer_id) \\\n .where(cm.Identity.customer_id == customer_id) \\\n .get()\n\n customer.delete_instance(recursive=True)\n LOGGER.info(\"Successfully deleted user from database.\")\n\n except DoesNotExist:\n LOGGER.warning(f\"The customer ID {customer_id} does not exist in the database\")\n raise ValueError(\"Customer ID does not exist\")\n\n\ndef update_customer_credit(customer_id, credit_limit):\n \"\"\"\n Adjusts the credit limit for a customer specified by their\n customer identification number.\n\n :param customer_id: Customer id to increase limit\n :param credit_limit: Number to adjust credit limit to\n :return:\n \"\"\"\n\n try:\n with cm.database.transaction():\n customer = (cm.Identity\n .select()\n .where(cm.Identity.customer_id == customer_id)\n .get())\n\n LOGGER.info(f\"Updating {customer.name} {customer.last_name} with credit limit {credit_limit}\")\n customer.credit_limit = credit_limit\n customer.save()\n LOGGER.info(f\"Updated {customer.name} {customer.last_name} credit limit to: {customer.credit_limit}\")\n\n except DoesNotExist:\n LOGGER.warning(f\"The customer ID {customer_id} does not exist in the database\")\n raise ValueError(\"User Does not exist\")\n\n\n\ndef list_active_customers():\n \"\"\"\n Checks the Identity table of the database and counts the number\n of active customers. Value must equal 1 in the 'active' column.\n :return: number of active customers\n \"\"\"\n try:\n with cm.database.transaction():\n active_customers = (cm.Identity\n .select()\n .where(cm.Identity.active == 1)\n .count())\n\n except Exception as e:\n LOGGER.warning(f\"Unable to determine active customers due to:\\n {e}\")\n\n return active_customers\n","sub_path":"students/mgummel/lesson03/assignment/basic_operations.py","file_name":"basic_operations.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"406510995","text":"from apps.reports import styles\n\nMONTH_NAMES = {\n 1: 'январь',\n 2: 'февраль',\n 3: 'март',\n 4: 'апрель',\n 5: 'май',\n 6: 'июнь',\n 7: 'июль',\n 8: 'август',\n 9: 'сентябрь',\n 10: 'октябрь',\n 11: 'ноябрь',\n 12: 'декабрь'\n}\n\n\ndef write_table(attendance_item, first_row, sheet):\n for i, kindergarten in enumerate(attendance_item.keys()):\n current_row = i + first_row + 1\n attendance = attendance_item[kindergarten]\n sheet.write(current_row, 0, kindergarten, styles.style)\n sheet.write(\n current_row, 1,\n attendance['children_count'],\n styles.style\n )\n sheet.write(\n current_row, 2,\n attendance['children_little_national_count'],\n styles.style\n )\n sheet.write(\n current_row, 3,\n attendance['work_days'],\n styles.style\n )\n sheet.write(\n current_row, 4,\n attendance['work_days'] * attendance['children_count'],\n styles.style\n )\n sheet.write(\n current_row, 5,\n attendance['work_days'] * attendance['children_little_national_count'],\n styles.style\n )\n\n\ndef write_table_title(sheet, row, text):\n first_column = 0\n last_column = 17\n sheet.write_merge(row, row, first_column, last_column, style=styles.group_style)\n sheet.write(row, 0, text, styles.group_style)\n","sub_path":"apps/reports/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"347644646","text":"# -*- coding: utf-8 -*-\n__author__ = 'Luke'\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom dwebsocket.decorators import accept_websocket\nfrom rest_framework.views import APIView, Response\nfrom zalo01.serializers import PhoneSerializers, OperationLogSerializers\nfrom func_timeout import func_set_timeout\nfrom Zalo.settings import redis_cache, HOST_IP\nfrom django.db.models import F\nfrom django.shortcuts import render, HttpResponse\nfrom zalo01.viewss.server_views import is_superuser\nfrom zalo01 import common, models\nfrom Zalo import rabbitMQ\nfrom Zalo.common import get_screenshot, get_phone_info_status\nimport uuid, json, time\nimport threading\n\n\nclass PhoneView(APIView):\n\n @method_decorator(login_required)\n def get(self, request):\n phone_all = models.PhoneInfo.objects.filter(userinfo=request.user)\n server_ip_dict = {}\n for phone in phone_all:\n if server_ip_dict.get(phone.server.id, None):\n continue\n server_ip_dict[phone.server.id] = phone.server.ip\n th_list = []\n for server_id, server_ip in server_ip_dict.items():\n satrt_th = threading.Thread(target=common.update_phone, args=(server_ip, server_id, []))\n th_list.append(satrt_th)\n satrt_th.start()\n for i in th_list:\n i.join()\n phone_all = models.PhoneInfo.objects.filter(userinfo=request.user).order_by(\"status\").reverse()\n phone_json_list = []\n for phone_info in phone_all:\n if phone_info.idinfo:\n phone_json_list.append(\n {\"phone_id\": phone_info.id, \"phone_name\": phone_info.phone_name,\n \"phone_status\": phone_info.status, \"phone_screenshot\": get_screenshot(phone_info),\n \"phone_info_status\": get_phone_info_status(phone_info)\n }\n )\n # 更新聊天室\n common.update_chat_room(request)\n return render(request, \"Phone/phone_index.html\",\n {\n \"nav\": \"phone\",\n \"phone_all\": phone_json_list\n }\n )\n\n @method_decorator(login_required)\n def post(self, request):\n result = {\"code\": 200, \"msg\": \"\"}\n instruct = request.data.get(\"instruct\")\n phone_id_list = request.data.get(\"phone_list\")\n if phone_id_list == \"\":\n result[\"code\"] = 401\n result[\"msg\"] = \"Vui lòng chọn 1 thiết bị để tiến hành thao tác\"\n return Response(result)\n dispose_content = common.DisposeContent(request, result)\n new_content, phone_obj_all = eval(\"dispose_content.{}()\".format(instruct))\n if result[\"code\"] != 200:\n return Response(result)\n # 根据服务器IP进行分发\n start_phone = {}\n Base_url = HOST_IP + \"static/openvpn/\"\n for phone in phone_obj_all:\n if not start_phone.get(phone.server.ip, None):\n start_phone[phone.server.ip] = []\n start_phone[phone.server.ip].append(\n {\n \"udid\": phone.udid, \"zalo_id\": phone.idinfo.code + phone.idinfo.phone,\n \"device_name\": phone.phone_name,\n \"zalo_pwd\": phone.idinfo.password, \"id\": phone.id,\n \"user_id\": request.user.id, \"app_install\": phone.app_install,\n \"open_vpn_name\": phone.OpenVpn.file_name, \"open_vpn_url\": Base_url + phone.OpenVpn.file_name,\n \"VPN_status\": phone.VPN_status, \"id_id\": phone.idinfo.id, \"zalo_status\": phone.zalo_status\n }\n )\n device_number = 0\n # 登陆验证码相关!!!!\n redis_set = \"{}_code_set\".format(request.user.id)\n over_set = \"{}_over_set\".format(request.user.id)\n user_handle_sum = \"{}_handle_sum\".format(request.user.id) # 执行设备数\n accomplish = \"{}_accomplish\".format(request.user.id) # 已完成\n redis_cache.delete(accomplish)\n redis_cache.delete(over_set)\n redis_cache.delete(redis_set)\n redis_cache.set(user_handle_sum, len(phone_obj_all))\n # 重写进度条,支持多任务进度条。\n task_name = \"{}_{}\".format(instruct, int(time.time()))\n # instruct 操作, execute_status 状态(是否开始执行 0~1)\n # progress 进度(0~100)百分比\n # device_all 设备总数, succeed_sum 执行完毕数\n # wait_time 发送进入队列时间,start_time 第一个设备执行时间, over_time 结束时间\n task_info = {\n \"instruct\": instruct, \"execute_status\": 0,\n \"progress\": 0, \"wait_time\": time.time(),\n \"start_time\": None, \"over_time\": None, \"uuid\": task_name,\n \"devices\": str([device.phone_name for device in phone_obj_all]),\n \"device_all\": len(phone_obj_all), \"succeed_device\": dict(),\n }\n redis_cache.hmset(\"{}_order\".format(request.user.username), {task_name: json.dumps(task_info)})\n print(\"开始分发\", instruct, start_phone, new_content)\n for ip, value in start_phone.items():\n queue_name = \"{}_appium\".format(ip)\n for adb in value:\n # 分发时,存入redis,执行完后更改状态,查看结果。\n key_uuid = str(uuid.uuid4())\n redis_key = \"{}_{}_{}\".format(request.user.id, adb[\"id\"], time.time())\n new_content[\"device_number\"] = device_number\n message_data = json.dumps(\n {\"instruct\": instruct, \"data\": adb, \"content\": new_content, \"redis_key\": redis_key,\n \"user\": request.user.username, \"user_id\": request.user.id, \"task_name\": task_name})\n rabbitMQ.push(queue_name, message_data, key_uuid)\n models.PhoneInfo.objects.filter(id=adb[\"id\"]).update(is_operation=1)\n device_number += 1\n return Response(result)\n\n @method_decorator(login_required)\n def put(self, request):\n pass\n\n\nclass PhoneAlterView(APIView):\n\n @method_decorator(login_required)\n def get(self, request, pk):\n lo_zalo = None\n lo_vpn = None\n phone_obj = models.PhoneInfo.objects.filter(pk=pk).first()\n device_info = {\"user_id\": \"\", \"zalo_id\": \"\", \"vpn_id\": \"\"}\n if phone_obj.userinfo:\n device_info[\"user_id\"] = str(phone_obj.userinfo.id)\n if phone_obj.idinfo:\n device_info[\"zalo_id\"] = str(phone_obj.idinfo.id)\n if phone_obj.OpenVpn:\n device_info[\"vpn_id\"] = str(phone_obj.OpenVpn.id)\n user_all = models.UserInfo.objects.filter(is_active=1)\n user_list = [{\"username\": user.username, \"id\": user.id} for user in user_all]\n vpn_list = [{\"name\": vpn.file_name, \"id\": vpn.id} for vpn in\n models.OpenVpn.objects.filter(device_max__gt=F(\"device_count\"), status=1)]\n local_vpn = models.OpenVpn.objects.filter(phoneinfo=phone_obj).first()\n if local_vpn:\n lo_vpn = {\"id\": local_vpn.id, \"name\": local_vpn.file_name}\n if lo_vpn in vpn_list:\n vpn_list.remove(lo_vpn)\n local_id = models.IdInfo.objects.filter(phoneinfo=phone_obj).first()\n zalo_list = [{\"id\": zalo.id, \"name\": zalo.name} for zalo in models.IdInfo.objects.filter(phoneinfo=None)]\n if local_id:\n lo_zalo = {\"id\": local_id.id, \"name\": local_id.name}\n if lo_zalo in zalo_list:\n zalo_list.remove(lo_zalo)\n return Response({\n \"code\": 200, \"zalo_list\": zalo_list, \"user_list\": user_list,\n \"device\": device_info, \"vpn_list\": vpn_list, \"lo_zalo\": lo_zalo,\n \"lo_vpn\": lo_vpn, \"devicename\": phone_obj.phone_name,\n })\n\n @method_decorator(login_required)\n def put(self, request, pk):\n # 如果更改了zalo账号以及vpn,则将状态对应改为2,下次执行app操作时会更新状态。\n phone_obj = models.PhoneInfo.objects.filter(pk=pk).first()\n if not request.user.is_superuser:\n if phone_obj.userinfo.id != request.user.id:\n return Response({\"code\": 403, \"msg\": \"No Access\"})\n phone_obj = models.PhoneInfo.objects.filter(pk=pk).first()\n devicename = request.data.get(\"devicename\")\n user_id = request.data.get(\"user_id\")\n zalo_id = request.data.get(\"zalo_id\")\n vpn_id = request.data.get(\"vpn_id\")\n vpn_status = request.data.get(\"vpn_status\")\n zalo_status = request.data.get(\"zalo_status\")\n # 设备状态,当这个状态为1表示正在运行,如果修改为0为造成错误,所以请务必确认手机是否在正常运行中。\n is_operation = request.data.get(\"is_operation\")\n if not phone_obj:\n return Response({\"code\": 401, \"msg\": \"The phone doesn't exist\"})\n try:\n user_id = int(user_id)\n zalo_id = int(zalo_id)\n vpn_id = int(vpn_id)\n except:\n return Response({\"code\": 401, \"msg\": \"Please enter the correct parameters\"})\n if devicename:\n if phone_obj.phone_name != devicename:\n models.PhoneInfo.objects.filter(pk=pk).update(phone_name=devicename)\n if user_id:\n if not phone_obj.userinfo:\n models.PhoneInfo.objects.filter(pk=pk).update(userinfo_id=user_id)\n elif not phone_obj.userinfo.id == user_id:\n models.PhoneInfo.objects.filter(pk=pk).update(userinfo_id=user_id)\n else:\n models.PhoneInfo.objects.filter(pk=pk).update(userinfo_id=None)\n if vpn_id:\n if not phone_obj.OpenVpn:\n models.PhoneInfo.objects.filter(pk=pk).update(OpenVpn_id=vpn_id, VPN_status=0)\n elif not phone_obj.OpenVpn.id == vpn_id:\n models.PhoneInfo.objects.filter(pk=pk).update(OpenVpn_id=vpn_id, VPN_status=2)\n else:\n models.PhoneInfo.objects.filter(pk=pk).update(OpenVpn_id=None, VPN_status=0)\n if zalo_id:\n if not phone_obj.idinfo:\n models.PhoneInfo.objects.filter(pk=pk).update(idinfo_id=zalo_id, zalo_status=0)\n elif not phone_obj.idinfo.id == zalo_id:\n models.PhoneInfo.objects.filter(pk=pk).update(idinfo_id=zalo_id, zalo_status=2)\n else:\n models.PhoneInfo.objects.filter(pk=pk).update(idinfo_id=None, zalo_status=0)\n if vpn_status:\n models.PhoneInfo.objects.filter(pk=pk).update(VPN_status=vpn_status)\n if zalo_status:\n models.PhoneInfo.objects.filter(pk=pk).update(zalo_status=zalo_status)\n if is_operation:\n models.PhoneInfo.objects.filter(pk=pk).update(is_operation=is_operation)\n return Response({\"code\": 200, \"msg\": \"successfully\"})\n\n\n@func_set_timeout(10)\ndef Get_message(request, _uid):\n res_data = rabbitMQ.pull(_uid)\n print(\"收到消息了\", res_data)\n return res_data\n\n\nclass Get_AJAX_Room(APIView):\n\n def get(self, request):\n result = {\"code\": 400}\n room_class_index = request.GET.get(\"room_class_index\")\n room_res = common.update_chat_room(request, room_class_index)\n if room_res:\n result[\"code\"] = 200\n result[\"data\"] = room_res\n else:\n result[\"msg\"] = \"更新聊天室中,请稍后重试。\"\n return Response(result)\n\n\n@accept_websocket\ndef WebSocketView(request):\n if request.is_websocket():\n print(\"%s 连接上了websocket\" % request.user.username)\n accomplish = \"{}_accomplish\".format(request.user.id)\n _uid = \"{}_mq_code\".format(request.user.id)\n redis_set = \"{}_code_set\".format(request.user.id)\n over_set = \"{}_over_set\".format(request.user.id)\n short = \"{}_short\".format(request.user.id)\n user_handle_sum = \"{}_handle_sum\".format(request.user.id)\n while True:\n try:\n time.sleep(5)\n msg = request.websocket.read()\n if msg:\n if msg.decode(\"utf8\") == \"quit\":\n request.websocket.close()\n return\n res_data = {}\n redis_cache.sdiffstore(short, redis_set, over_set)\n phone_number = redis_cache.spop(short)\n if phone_number:\n phone_number = phone_number.decode(\"utf8\")\n res_data[\"phone_number\"] = phone_number\n redis_cache.sadd(over_set, phone_number)\n res_data[\"progress_bar\"] = len(redis_cache.sinter(accomplish)) / int(\n redis_cache.get(user_handle_sum).decode(\"utf8\")) * 100\n request.websocket.send(json.dumps(res_data).encode('utf-8'))\n if res_data[\"progress_bar\"] == 100:\n request.websocket.close()\n return\n except BaseException as b:\n return\n\n\n@accept_websocket\ndef Progress_bar(request):\n if request.is_websocket():\n while True:\n try:\n _user_key = \"{}_order\".format(request.user.username)\n result = {\"record_list\": []}\n for x in redis_cache.hkeys(_user_key):\n dict_info = json.loads(redis_cache.hmget(_user_key, x.decode(\"utf8\"))[0].decode(\"utf8\"))\n if not dict_info[\"over_time\"]:\n print(dict_info)\n dict_info[\"progress\"] = round(len(dict_info[\"succeed_device\"]) / dict_info[\"device_all\"] * 100,\n 2)\n if dict_info[\"device_all\"] <= len(dict_info[\"succeed_device\"]):\n dict_info[\"over_time\"] = time.time()\n redis_cache.hmset(_user_key, {x.decode(\"utf8\"): json.dumps(dict_info)})\n result[\"record_list\"].append(dict_info)\n request.websocket.send(json.dumps(result).encode('utf-8'))\n msg = request.websocket.read()\n if msg:\n msg_info = msg.decode(\"utf8\")\n if msg_info == \"quit\":\n request.websocket.close()\n return\n # else:\n # redis_cache.hdel(_user_key, msg_info)\n time.sleep(5)\n except BaseException as b:\n print(b)\n return\n\n\nclass Code(APIView):\n\n def post(self, request):\n phone_number = request.data.get(\"phone_number\")\n code = request.data.get(\"code\")\n print(code)\n if len(code) != 4:\n return Response({\"code\": 401, \"msg\": \"Verification code error\"})\n result_json = json.dumps({\"phone_number\": phone_number, \"code\": code})\n redis_cache.set(phone_number, result_json)\n redis_cache.expire(phone_number, 120)\n return Response({\"code\": 200, \"msg\": \"Received your captcha\"})\n","sub_path":"zalo/Zalo/zalo01/viewss/phone_views.py","file_name":"phone_views.py","file_ext":"py","file_size_in_byte":15063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248845443","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Mike\n# @Contact : 597290963@qq.com\n# @Time : 2021/2/14 9:44\n# @File : CanJump.py\nfrom typing import List\n\n\"\"\"\n给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。\n\n数组中的每个元素代表你在该位置可以跳跃的最大长度。\n\n判断你是否能够到达最后一个下标。\n\"\"\"\n\n\nclass Solution:\n\n def canJump(self, nums: List[int]) -> bool:\n if len(nums) == 1:\n return True\n if len(nums) == 0:\n return False\n\n dp = [0 for i in range(len(nums))]\n dp[0] = nums[0]\n\n for i in range(1, len(nums)):\n \"\"\"\n 判断前一个能达到的最远位置是否大于当前位置\n \"\"\"\n if dp[i - 1] < i:\n return False\n else:\n dp[i] = max(dp[i - 1], i + nums[i])\n if dp[i] >= len(nums) - 1:\n return True\n\n return False\n\n def canJump1(self, nums: List[int]) -> bool:\n \"\"\"\n 注意到 下标i只与下标i - 1有关,优化空间为O(1)\n :param nums:\n :return:\n \"\"\"\n if len(nums) == 1:\n return True\n if len(nums) == 0:\n return False\n\n max_jump = nums[0]\n for i in range(1, len(nums)):\n if max_jump < i:\n return False\n else:\n max_jump = max(max_jump, i + nums[i])\n if max_jump >= len(nums) - 1:\n return True\n\n return False","sub_path":"datastructure/dp_exercise/CanJump.py","file_name":"CanJump.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"379759931","text":"from __future__ import division\nimport numpy as np\nfrom scipy import special as sp\nimport scipy.integrate\n\n\n\n\nG = 6.67e-11\nc=3e8\n\ndef Gwaves(motion,constants):\n \n print ('Getting the waveform')\n t = motion[:,0]\n e = motion[:,1]\n g = motion[:,2]\n a = motion[:,3]\n \n M = constants[0] #total mass of inner binary\n nmodes = constants[1]\n iota = constants[2]\n mu = constants[3]\n D = constants[4]\n \n \n MA = np.sqrt(G*M) * a**(-3/2)*t #mean anomaly\n fdynamic = np.sqrt(G*M/(4*np.pi**2)) * a**(-3/2) #reparam of a to f\n omega = 2*np.pi*fdynamic\n \n\n \n #Convert to geometric units\n mu = mu * G/c**2\n M = M * G/c**2\n D = D\n omega = omega/c\n \n AA = mu/D * (M*omega)**(2/3)\n\n \n \n waveform_out = np.zeros((len(t), 3))\n waveform_out[:,0] = t \n \n \n \n \n \n for n in np.arange(1,nmodes+1):\n print ('Mode sum. n = ', n,nmodes)\n J_2 = sp.jv(n-2,n*e)\n J_1 = sp.jv(n-1,n*e) \n Jn = sp.jv(n,n*e) \n J1 = sp.jv(n+1,n*e)\n J2 = sp.jv(n+2,n*e)\n \n an = -n*AA*(J_2 - 2*e*J_1 + 2*Jn/n + 2*e*J1 - J2)*np.cos(n*MA)\n bn = -n*AA*np.sqrt((1-e**2)) * (J_2 - 2*Jn + J2)*np.sin(n*MA)\n cn = 2*AA*Jn*np.cos(n*MA)\n \n \n hplus = -(1+np.cos(iota)) * (an*np.cos(2*g) - bn*np.sin(2*g)) + (1-np.cos(iota)**2)*cn\n hcross = 2*np.cos(iota)*(bn*np.cos(2*g) + an*np.sin(2*g))\n \n waveform_out[:,1] = waveform_out[:,1] + hplus\n waveform_out[:,2] = waveform_out[:,2] + hcross\n \n\n \n \n return waveform_out\n\n\n\n\ndef overlap(data1,data2):\n \n #Get data in Fourier regime\n f1,hp1,hc1 = FT(data1)\n f2,hp2,hc2 = FT(data2)\n \n f = f1\n \n #Noise\n S = noise(f)\n \n \n \n hplusN = hp1\n hcrossN = hc1\n \n hN = np.sqrt(abs(hplusN)**2 + abs(hcrossN)**2) #numerical\n hsig1 = hN\n normN = 2 * scipy.integrate.simps( (hN * np.conj(hN) + np.conj(hN) * hN)/(S),f)\n hN = hN / np.sqrt(normN)\n #overlap = 2 * scipy.integrate.simps( (hN * np.conj(hN) + np.conj(hN) * hN)/(S),f)\n\n\n hplusA = hp2\n hcrossA = hc2\n \n hA = np.sqrt(abs(hplusA)**2 + abs(hcrossA)**2) #numerical\n hsig2 = hA\n normA = 2 * scipy.integrate.simps( (hA * np.conj(hA) + np.conj(hA) * hA)/(S),f)\n hA = hA / np.sqrt(normA)\n \n \n overlap = 2 * scipy.integrate.simps( (hN * np.conj(hA) + np.conj(hN) * hA)/(S),f)\n\n \n\n\n \n print ('overlap = ', overlap)\n \n \n return f,hsig1,hsig2, np.sqrt(S)\n\n \n \n \n \ndef FT(data): \n \n t = data[:,0]\n hplus = data[:,1]\n hcross = data[:,2]\n \n \n dt = t[1] - t[0]\n fs = 1/dt\n\n #Get the frequencies\n f = np.fft.rfftfreq(t.size,dt)\n\n \n #Take the FT\n hp = dt*np.fft.rfft(hplus)\n hc = dt*np.fft.rfft(hcross)\n \n hN =np.sqrt(abs(hp)**2 + abs(hc)**2) \n \n \n #Get rid of zeroth frequencies - WHY?\n hp = hp[1:] # get rid of zeroth frequency\n hc = hc[1:]\n f = f[1:]\n \n return f, hp, hc\n \n \n \n \n \n \ndef noise(f):\n #Calculate the LISA noise curve\n Larm = 2.5e9\n Clight = 3e8\n fstar = Clight/(2*np.pi*Larm)\n NC = 2\n\n alpha = 0.133\n beta = 243.\n kappa = 482.\n gamma = 917.\n f_knee = 2.58e-3\n\n A = 1.8e-44/NC\n Sc = 1. + np.tanh(gamma*(f_knee-f))\n Sc *=np.exp(-f**alpha + beta*f*np.sin(kappa*f))\n\n Sc *= A*f**(-7./3.)\n\n\n #LISA response function\n\n RFILE = np.loadtxt('ResponseFunction.txt')\n Rx = RFILE[:,0] * fstar\n Ry = RFILE[:,1] * NC\n\n newR = np.interp(f,Rx,Ry)\n R = newR\n\n\n #Power Spectral Density\n P_oms = (1.5e-11)**2 * (1. + (2.0e-3/f)**4)\n P_acc = (3.0e-15)**2 * (1.+(0.4e-3/f)**2)*(1. + (f/(8.0e-3))**4)\n Pn = (P_oms + 2.*(1. + np.cos(f/fstar)**2)*P_acc/(2*np.pi*f)**4)/Larm**2\n\n #Total noise\n S = Pn/R + Sc\n \n\n \n return S","sub_path":"Jupyter/Code/Revised/.ipynb_checkpoints/GravRadiation-checkpoint.py","file_name":"GravRadiation-checkpoint.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518117646","text":"#!/usr/bin/env python\n# Read in 2D stacks for two events\n# Compute tdiff, ave_amp, amp_ratio\n# Plot radial and transverse cuts through stack, plus beam sum\n# Write out tdiff, ave_amp, amp_ratio results\n# John Vidale 3/2019\n\ndef pro6stacked_seis(eq_file1, eq_file2, plot_scale_fac = 0.03, slow_delta = 0.0005,\n\t\t\t slowR_lo = -0.1, slowR_hi = 0.1, slowT_lo = -0.1, slowT_hi = 0.1,\n\t\t\t start_buff = -50, end_buff = 50, norm = 0, freq_corr = 1.0,\n\t\t\t plot_dyn_range = 1000, fig_index = 401, get_stf = 0, ref_phase = 'blank',\n\t\t\t ARRAY = 0, max_rat = 1.8, min_amp = 0.2, turn_off_black = 0,\n\t\t\t R_slow_plot = 0, T_slow_plot = 0, tdiff_clip = 1, event_no = 0):\n\n\timport obspy\n\timport obspy.signal\n\tfrom obspy import UTCDateTime\n\tfrom obspy import Stream, Trace\n\tfrom obspy import read\n\tfrom obspy.geodetics import gps2dist_azimuth\n\timport numpy as np\n\timport os\n\tfrom obspy.taup import TauPyModel\n\timport obspy.signal as sign\n\timport matplotlib.pyplot as plt\n\tmodel = TauPyModel(model='iasp91')\n\tfrom scipy.signal import hilbert\n\timport math\n\timport time\n\timport statistics\n\n#%% Get info\n\t#%% get locations\n\tprint('Running pro6_plot_stacked_seis')\n\tstart_time_wc = time.time()\n\n\tif ARRAY == 1:\n\t\tgoto = '/Users/vidale/Documents/PyCode/LASA/EvLocs'\n\t\tos.chdir(goto)\n\n\tfile = open(eq_file1, 'r')\n\tlines=file.readlines()\n\tsplit_line = lines[0].split()\n\tt1 = UTCDateTime(split_line[1])\n\tdate_label1 = split_line[1][0:10]\n\n\tfile = open(eq_file2, 'r')\n\tlines=file.readlines()\n\tsplit_line = lines[0].split()\n\tt2 = UTCDateTime(split_line[1])\n\tdate_label2 = split_line[1][0:10]\n\n\t#%% read files\n\t# #%% Get saved event info, also used to name files\n\t# date_label = '2018-04-02' # date for filename\n\tif ARRAY == 1:\n\t\tgoto = '/Users/vidale/Documents/PyCode/LASA/Pro_files'\n\t\tos.chdir(goto)\n\tfname1 = 'HD' + date_label1 + '_2dstack.mseed'\n\tfname2 = 'HD' + date_label2 + '_2dstack.mseed'\n\tst1 = Stream()\n\tst2 = Stream()\n\tst1 = read(fname1)\n\tst2 = read(fname2)\n\n\ttshift = st1.copy() # make array for time shift\n\tamp_ratio = st1.copy() # make array for relative amplitude\n\tamp_ave = st1.copy() # make array for relative amplitude\n\n\tprint('Read in: event 1 ' + str(len(st1)) + ' event 2 ' + str(len(st2)) + ' traces')\n\tnt1 = len(st1[0].data)\n\tnt2 = len(st2[0].data)\n\tdt1 = st1[0].stats.delta\n\tdt2 = st2[0].stats.delta\n\tprint('Event 1 - First trace has ' + str(nt1) + ' time pts, time sampling of '\n\t\t + str(dt1) + ' and thus duration of ' + str((nt1-1)*dt1))\n\tprint('Event 2 - First trace has ' + str(nt2) + ' time pts, time sampling of '\n\t\t + str(dt2) + ' and thus duration of ' + str((nt2-1)*dt2))\n\tif nt1 != nt2 or dt1 != dt2:\n\t\tprint('nt or dt not does not match')\n\t\texit(-1)\n\n\t#%% Make grid of slownesses\n\tslowR_n = int(1 + (slowR_hi - slowR_lo)/slow_delta) # number of slownesses\n\tslowT_n = int(1 + (slowT_hi - slowT_lo)/slow_delta) # number of slownesses\n\tprint(str(slowT_n) + ' trans slownesses, hi and lo are ' + str(slowT_hi) + ' ' + str(slowT_lo))\n\t# In English, stack_slows = range(slow_n) * slow_delta - slow_lo\n\ta1R = range(slowR_n)\n\ta1T = range(slowT_n)\n\tstack_Rslows = [(x * slow_delta + slowR_lo) for x in a1R]\n\tstack_Tslows = [(x * slow_delta + slowT_lo) for x in a1T]\n\tprint(str(slowR_n) + ' radial slownesses, ' + str(slowT_n) + ' trans slownesses, ')\n\n#%% Loop over slowness\n\ttotal_slows = slowR_n * slowT_n\n\tglobal_max = 0\n\tfor slow_i in range(total_slows): # find envelope, phase, tshift, and global max\n\t\tif slow_i % 200 == 0:\n\t\t\tprint('At line 101, ' +str(slow_i) + ' slowness out of ' + str(total_slows))\n\t\tif len(st1[slow_i].data) == 0: # test for zero-length traces\n\t\t\t\tprint('%d data has zero length ' % (slow_i))\n\n\t\tseismogram1 = hilbert(st1[slow_i].data) # make analytic seismograms\n\t\tseismogram2 = hilbert(st2[slow_i].data)\n\n\t\tenv1 = np.abs(seismogram1) # amplitude\n\t\tenv2 = np.abs(seismogram2)\n\t\tamp_ave[slow_i].data = 0.5 * (env1 + env2)\n\t\tamp_ratio[slow_i].data = env1/env2\n\n\t\tangle1 = np.angle(seismogram1) # time shift\n\t\tangle2 = np.angle(seismogram2)\n\t\tphase1 = np.unwrap(angle1)\n\t\tphase2 = np.unwrap(angle2)\n\t\tdphase = (angle1 - angle2)\n#\t\tdphase = phase1 - phase2\n\t\tfor it in range(nt1):\n\t\t\tif dphase[it] > math.pi:\n\t\t\t\tdphase[it] -= 2 * math.pi\n\t\t\telif dphase[it] < -1 * math.pi:\n\t\t\t\tdphase[it] += 2 * math.pi\n\t\t\tif dphase[it] > math.pi or dphase[it] < -math.pi:\n\t\t\t\tprint(f'Bad dphase value {dphase[it]:.2f} {it:4d}')\n\t\tfreq1 = np.diff(phase1) #freq in radians/sec\n\t\tfreq2 = np.diff(phase2)\n\t\tave_freq = 0.5*(freq1 + freq2)\n\t\tave_freq_plus = np.append(ave_freq,[1]) # ave_freq one element too short\n#\t\ttshift[slow_i].data = dphase / ave_freq_plus # 2*pi top and bottom cancels\n\t\ttshift[slow_i].data = dphase/(2*math.pi*freq_corr)\n\n\t\tlocal_max = max(abs(amp_ave[slow_i].data))\n\t\tif local_max > global_max:\n\t\t\tglobal_max = local_max\n#%% Extract slices\n\ttshift_full = tshift.copy() # make array for time shift\n\tfor slow_i in range(total_slows): # ignore less robust points\n\t\tif slow_i % 200 == 0:\n\t\t\tprint('At line 140, ' +str(slow_i) + ' slowness out of ' + str(total_slows))\n\t\tfor it in range(nt1):\n\t\t\tif ((amp_ratio[slow_i].data[it] < (1/max_rat)) or (amp_ratio[slow_i].data[it] > max_rat) or (amp_ave[slow_i].data[it] < (min_amp * global_max))):\n\t\t\t\ttshift[slow_i].data[it] = np.nan\n\t#%% If desired, find transverse slowness nearest T_slow_plot\n\tlowest_Tslow = 1000000\n\tfor slow_i in range(slowT_n):\n\t\tif abs(stack_Tslows[slow_i] - T_slow_plot) < lowest_Tslow:\n\t\t\tlowest_Tindex = slow_i\n\t\t\tlowest_Tslow = abs(stack_Tslows[slow_i] - T_slow_plot)\n\n\tprint(str(slowT_n) + ' T slownesses, index ' + str(lowest_Tindex) + ' is closest to input parameter ' + str(T_slow_plot) + ', slowness diff there is ' + str(lowest_Tslow) + ' and slowness is ' + str(stack_Tslows[lowest_Tindex]))\n\t# Select only stacks with that slowness for radial plot\n\tcentralR_st1 = Stream()\n\tcentralR_st2 = Stream()\n\tcentralR_amp = Stream()\n\tcentralR_ampr = Stream()\n\tcentralR_tdiff = Stream()\n\tfor slowR_i in range(slowR_n):\n\t\tii = slowR_i*slowT_n + lowest_Tindex\n\t\tcentralR_st1 += st1[ii]\n\t\tcentralR_st2 += st2[ii]\n\t\tcentralR_amp += amp_ave[ii]\n\t\tcentralR_ampr += amp_ratio[ii]\n\t\tcentralR_tdiff += tshift[ii]\n\n\t#%% If desired, find radial slowness nearest R_slow_plot\n\tlowest_Rslow = 1000000\n\tfor slow_i in range(slowR_n):\n\t\tif abs(stack_Rslows[slow_i] - R_slow_plot) < lowest_Rslow:\n\t\t\tlowest_Rindex = slow_i\n\t\t\tlowest_Rslow = abs(stack_Rslows[slow_i] - R_slow_plot)\n\n\tprint(str(slowR_n) + ' R slownesses, index ' + str(lowest_Rindex) + ' is closest to input parameter ' + str(R_slow_plot) + ', slowness diff there is ' + str(lowest_Rslow) + ' and slowness is ' + str(stack_Rslows[lowest_Rindex]))\n\n\t# Select only stacks with that slowness for transverse plot\n\tcentralT_st1 = Stream()\n\tcentralT_st2 = Stream()\n\tcentralT_amp = Stream()\n\tcentralT_ampr = Stream()\n\tcentralT_tdiff = Stream()\n\n\t#%% to extract stacked time functions\n\tevent1_sample = Stream()\n\tevent2_sample = Stream()\n\n\tfor slowT_i in range(slowT_n):\n\t\tii = lowest_Rindex*slowT_n + slowT_i\n\t\tcentralT_st1 += st1[ii]\n\t\tcentralT_st2 += st2[ii]\n\t\tcentralT_amp += amp_ave[ii]\n\t\tcentralT_ampr += amp_ratio[ii]\n\t\tcentralT_tdiff += tshift[ii]\n\n\t#%% compute timing time series\n\tttt = (np.arange(len(st1[0].data)) * st1[0].stats.delta + start_buff) # in units of seconds\n\n#%% Plot radial amp and tdiff vs time plots\n\tfig_index = 6\n#\tplt.close(fig_index)\n\tplt.figure(fig_index,figsize=(30,10))\n\tplt.xlim(start_buff,end_buff)\n\tplt.ylim(stack_Rslows[0], stack_Rslows[-1])\n\tfor slowR_i in range(slowR_n): # loop over radial slownesses\n\t\tdist_offset = stack_Rslows[slowR_i] # trying for approx degrees\n\t\tttt = (np.arange(len(centralR_st1[slowR_i].data)) * centralR_st1[slowR_i].stats.delta\n\t\t + (centralR_st1[slowR_i].stats.starttime - t1))\n\t\tplt.plot(ttt, (centralR_st1[slowR_i].data - np.median(centralR_st1[slowR_i].data))*plot_scale_fac /global_max + dist_offset, color = 'green')\n\t\tplt.plot(ttt, (centralR_st2[slowR_i].data - np.median(centralR_st2[slowR_i].data))*plot_scale_fac /global_max + dist_offset, color = 'red')\n\t\t# extract stacked time functions\n\t\tif get_stf != 0:\n\t\t\tif np.abs(stack_Rslows[slowR_i]- 0.005) < 0.000001: # kludge, not exactly zero when desired\n\t\t\t\tevent1_sample = centralR_st1[slowR_i].copy()\n\t\t\t\tevent2_sample = centralR_st2[slowR_i].copy()\n#\t\tplt.plot(ttt, (centralR_amp[slowR_i].data) *plot_scale_fac/global_max + dist_offset, color = 'purple')\n\t\tif turn_off_black == 0:\n\t\t\tplt.plot(ttt, (centralR_tdiff[slowR_i].data)*plot_scale_fac/1 + dist_offset, color = 'black')\n\t\t\tplt.plot(ttt, (centralR_amp[slowR_i].data)*0.0 + dist_offset, color = 'lightgray') # reference lines\n\tplt.xlabel('Time (s)')\n\tplt.ylabel('R Slowness (s/km)')\n\tplt.title(ref_phase + ' seismograms and tdiff at ' + str(T_slow_plot) + ' T slowness, green is event1, red is event2')\n\t# Plot transverse amp and tdiff vs time plots\n\tfig_index = 7\n#\tplt.close(fig_index)\n\tplt.figure(fig_index,figsize=(30,10))\n\tplt.xlim(start_buff,end_buff)\n\tplt.ylim(stack_Tslows[0], stack_Tslows[-1])\n\n\tfor slowT_i in range(slowT_n): # loop over transverse slownesses\n\t\tdist_offset = stack_Tslows[slowT_i] # trying for approx degrees\n\t\tttt = (np.arange(len(centralT_st1[slowT_i].data)) * centralT_st1[slowT_i].stats.delta\n\t\t + (centralT_st1[slowT_i].stats.starttime - t1))\n\t\tplt.plot(ttt, (centralT_st1[slowT_i].data - np.median(centralT_st1[slowT_i].data))*plot_scale_fac /global_max + dist_offset, color = 'green')\n\t\tplt.plot(ttt, (centralT_st2[slowT_i].data - np.median(centralT_st2[slowT_i].data))*plot_scale_fac /global_max + dist_offset, color = 'red')\n#\t\tplt.plot(ttt, (centralT_amp[slowT_i].data) *plot_scale_fac/global_max + dist_offset, color = 'purple')\n\t\tif turn_off_black == 0:\n\t\t\tplt.plot(ttt, (centralT_tdiff[slowT_i].data)*plot_scale_fac/1 + dist_offset, color = 'black')\n\t\t\tplt.plot(ttt, (centralT_amp[slowT_i].data)*0.0 + dist_offset, color = 'lightgray') # reference lines\n\tplt.xlabel('Time (s)')\n\tplt.ylabel('T Slowness (s/km)')\n\tplt.title(str(event_no) + ' ' + date_label1 + ' ' +ref_phase + ' seismograms and tdiff ' + str(R_slow_plot) + ' R slowness, green is event1, red is event2')\n\tos.chdir('/Users/vidale/Documents/PyCode/LASA/Quake_results/Plots')\n#\tplt.savefig(date_label1 + '_' + str(start_buff) + '_' + str(end_buff) + '_stack.png')\n\n#%% R-T tshift averaged over time window\n\tfig_index = 8\n\tstack_slice = np.zeros((slowR_n,slowT_n))\n\tfor slowR_i in range(slowR_n): # loop over radial slownesses\n\t\tfor slowT_i in range(slowT_n): # loop over transverse slownesses\n\t\t\tindex = slowR_i*slowT_n + slowT_i\n\t\t\tnum_val = np.nanmedian(tshift[index].data)\n#\t\t\tnum_val = statistics.median(tshift_full[index].data)\n\t\t\tstack_slice[slowR_i, slowT_i] = num_val # adjust for dominant frequency of 1.2 Hz, not 1 Hz\n#\tstack_slice[0,0] = -0.25\n#\tstack_slice[0,1] = 0.25\n#\ttdiff_clip = 0.4/1.2\n\ttdiff_clip_max = tdiff_clip # DO NOT LEAVE COMMENTED OUT!!\n\ttdiff_clip_min = -tdiff_clip\n\n\ty1, x1 = np.mgrid[slice(stack_Rslows[0], stack_Rslows[-1] + slow_delta, slow_delta),\n\t\t\t\t slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta)]\n\n\tfig, ax = plt.subplots(1, figsize=(7,6))\n#\t\tfig, ax = plt.subplots(1, figsize=(9,2))\n#\t\tfig.subplots_adjust(bottom=0.3)\n#\tc = ax.pcolormesh(x1, y1, stack_slice, cmap=plt.cm.bwr, vmin = tdiff_clip_min, vmax = tdiff_clip_max)\n\tc = ax.pcolormesh(x1, y1, stack_slice, cmap=plt.cm.coolwarm, vmin = tdiff_clip_min, vmax = tdiff_clip_max)\n\tax.axis([x1.min(), x1.max(), y1.min(), y1.max()])\n\tcircle1 = plt.Circle((0, 0), 0.019, color='black', fill=False)\n\tax.add_artist(circle1)\n\tcircle2 = plt.Circle((0, 0), 0.040, color='black', fill=False)\n\tax.add_artist(circle2) #outer core limit\n\tfig.colorbar(c, ax=ax)\n\tplt.ylabel('R Slowness (s/km)')\n\tplt.title(ref_phase + ' time shift')\n#\tplt.title('T-R average time shift ' + date_label1 + ' ' + date_label2)\n\tplt.show()\n\n#%% R-T amplitude averaged over time window\n\tfig_index = 9\n\tstack_slice = np.zeros((slowR_n,slowT_n))\n\tsmax = 0\n\tfor slowR_i in range(slowR_n): # loop over radial slownesses\n\t\tfor slowT_i in range(slowT_n): # loop over transverse slownesses\n\t\t\tindex = slowR_i*slowT_n + slowT_i\n\t\t\tnum_val = np.nanmedian(amp_ave[index].data)\n\t\t\tstack_slice[slowR_i, slowT_i] = num_val\n\t\t\tif num_val > smax:\n\t\t\t\tsmax = num_val\n#\tstack_slice[0,0] = 0\n\n\ty1, x1 = np.mgrid[slice(stack_Rslows[0], stack_Rslows[-1] + slow_delta, slow_delta),\n\t\t\t\t slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta)]\n\n#\tfig, ax = plt.subplots(1)\n\tfig, ax = plt.subplots(1, figsize=(7,6))\n#\tc = ax.pcolormesh(x1, y1, stack_slice/smax, cmap=plt.cm.gist_yarg, vmin = 0.5)\n\tc = ax.pcolormesh(x1, y1, stack_slice/smax, cmap=plt.cm.gist_rainbow_r, vmin = 0)\n#\tc = ax.pcolormesh(x1, y1, stack_slice, cmap=plt.cm.gist_rainbow_r, vmin = 0)\n\tax.axis([x1.min(), x1.max(), y1.min(), y1.max()])\n\tcircle1 = plt.Circle((0, 0), 0.019, color='black', fill=False)\n\tax.add_artist(circle1) #inner core limit\n\tcircle2 = plt.Circle((0, 0), 0.040, color='black', fill=False)\n\tax.add_artist(circle2) #outer core limit\n\tfig.colorbar(c, ax=ax)\n\tplt.xlabel('Transverse Slowness (s/km)')\n\tplt.ylabel('Radial Slowness (s/km)')\n\tplt.title(ref_phase + ' beam amplitude')\n#\tplt.title('Beam amplitude ' + date_label1 + ' ' + date_label2)\n\tos.chdir('/Users/vidale/Documents/PyCode/LASA/Quake_results/Plots')\n\tplt.savefig(date_label1 + '_' + str(start_buff) + '_' + str(end_buff) + '_beam.png')\n\tplt.show()\n\n#%% Save processed files\n\tif ARRAY == 0:\n\t\tgoto = '/Users/vidale/Documents/PyCode/Hinet'\n\tif ARRAY == 1:\n\t\tgoto = '/Users/vidale/Documents/PyCode/LASA/Pro_Files'\n\tos.chdir(goto)\n\n\tfname = 'HD' + date_label1 + '_' + date_label2 + '_tshift.mseed'\n\ttshift_full.write(fname,format = 'MSEED')\n\n\tfname = 'HD' + date_label1 + '_' + date_label2 + '_amp_ave.mseed'\n\tamp_ave.write(fname,format = 'MSEED')\n\n\tfname = 'HD' + date_label1 + '_' + date_label2 + '_amp_ratio.mseed'\n\tamp_ratio.write(fname,format = 'MSEED')\n\n#%% Option to write out stf\n\tif get_stf != 0:\n\t\tevent1_sample.taper(0.1)\n\t\tevent2_sample.taper(0.1)\n\t\tfname = 'HD' + date_label1 + '_stf.mseed'\n\t\tevent1_sample.write(fname,format = 'MSEED')\n\t\tfname = 'HD' + date_label2 + '_stf.mseed'\n\t\tevent2_sample.write(fname,format = 'MSEED')\n\n\telapsed_time_wc = time.time() - start_time_wc\n\tprint('This job took ' + str(elapsed_time_wc) + ' seconds')\n\tos.system('say \"Done\"')\n","sub_path":"pro6_plot_stacked_seis_copy.py","file_name":"pro6_plot_stacked_seis_copy.py","file_ext":"py","file_size_in_byte":14292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"246440109","text":"from __future__ import print_function\nimport ROOT as rt\nimport root_numpy\nimport pickle\nimport argparse\nimport os\nimport sys\nimport shutil\nimport numpy as np\nimport logging\n\n\n\"\"\"\npython tree_to_np.py [files and/or directories to be converted] \n -d [destination of resulting numpy arrays] \n -n [path to the connected np array]\n -c [True/False clean (remove) the directory of concatenate files]\npython tree_to_np.py source1 -d ./ -name_conn conn.pkl -clean True\n\npython2.7 tree_to_np.py /eos/cms/store/user/fsiroky/data_fifthrun/ -d=/eos/cms/store/group/comm_dqm/cmsml4dc/2016-v1/data2016_v2\n\n\"\"\"\n\ndef convert_tree_to_np(sources, destination, npy_files=[]):\n \"\"\" Converts the root files in sources to numpy arrays\n Params\n sources : list\n root file paths/names or path to directory of root files\n destination : str\n path to directory where the npy files will be saved\n npy_files : list\n list of already converted files (for recursive functionality)\n Returns\n list\n paths to the converted files \n \"\"\"\n for i in xrange(len(sources)):\n if os.path.isdir(sources[i]) and ('failed' not in sources[i]):\n # source is a directory -> recurse on all files in directory\n new_sources = [sources[i]+'/'+e for e in os.listdir(sources[i])]\n new_destination = destination+'/'+sources[i].split('/')[-1]\n\n print('new_sources ', len(new_sources), new_sources[-9:])\n print('new_destination ', new_destination)\n logging.info('new_sources '+ str(len(new_sources))+' '+ str(new_sources[-9:]))\n logging.info('new_destination '+ new_destination)\n os.mkdir(new_destination)\n convert_tree_to_np(new_sources, new_destination, npy_files)\n else:\n if \".root\" in sources[i]:\n try:\n # print(i, sources[i])\n logging.info(str(i) +' '+ sources[i])\n print(str(i)+' ', end=\"\")\n sys.stdout.flush()\n\n tChain = rt.TChain('MyAnalysis/MyTree')\n tChain.Add(sources[i])\n\n array = root_numpy.tree2array(tChain)\n # print 'Total number of entries: ',tChain.GetEntries()\n \n pkl_file_name = destination+'/'+sources[i].split('/')[-1][:-5]\n np.save(pkl_file_name, array)\n npy_files.append(pkl_file_name+'.npy')\n except Exception as e:\n if os.path.exists('failed.pkl'):\n continue\n else:\n mylist=[]\n with open('failed.pkl', 'wb') as f:\n pickle.dump(mylist, f)\n print(\"\")\n print(e)\n print(sources[i], \" ** FAILED ** \")\n logging.error(sources[i]+ \" ** FAILED ** \")\n logging.error(e)\n\n f = open('failed.pkl', 'rb')\n failed = pickle.load(f)\n f.close()\n failed.append(sources[i])\n f = open('failed.pkl', 'wb')\n pickle.dump(failed, f)\n f.close()\n \n \n\n return npy_files\n\ndef concatenate_pickles(npy_files, name_conn, clean=False, sources=[], destination=\"./\"):\n \"\"\"Concatenate numpy arrays in multiple files into one numpy array and saves it.\n Params\n npy_files : list\n paths to np arrays\n name_conn : str\n path to the concatenated np array (destination)\n Returns\n void\n \"\"\"\n # loading the first array\n array = np.load(npy_files[0])\n for npy_file_name in npy_files[1:]:\n print(npy_file_name)\n next_array = np.load(npy_file_name)\n \n array = np.concatenate((array, next_array), axis=0)\n\n np.save(name_conn, array)\n\n if clean:\n # removes the directory of unconcatenated npy files\n for i in xrange(len(sources)):\n if os.path.isdir(sources[i]):\n shutil.rmtree(destination+'/'+sources[i].split('/')[-1])\n\n\ndef main():\n logging.basicConfig(filename='tree_to_np.log',level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M')\n parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')\n parser.add_argument( dest='sources', metavar='N', type=str, nargs='+', help='Help sources') #'-s', '--sources',\n parser.add_argument(\"-d\", \"--destination\", dest=\"destination\", default=\"./\", help=\"Help destination\")\n parser.add_argument(\"-n\", \"-name_conn\", dest=\"name_conn\", default=\"\", help=\"Help name_conn\")\n parser.add_argument(\"-c\", \"-clean\", dest=\"clean\", default=False, help=\"Help clean\")\n args = parser.parse_args()\n\n print(args)\n sources = args.sources\n destination = args.destination\n name_conn = args.name_conn\n clean = not( args.clean=='False' )\n\n npy_files = convert_tree_to_np(sources, destination)\n print(npy_files)\n logging.info(str(npy_files))\n\n if name_conn:\n concatenate_pickles(npy_files, name_conn, clean=clean, sources=sources, destination=destination)\n\n\nif __name__ == '__main__':\n main()\n print(\"tree_to_np DONE\")\n\n\n","sub_path":"rt_np_test/tree_to_np.py","file_name":"tree_to_np.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"430182017","text":"# Import so that the bot could function\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\nimport time\nimport random\nfrom random import randint\nimport Config\nimport datetime\nimport asyncio\nimport discord\nimport os\nfrom discord.ext.commands import Bot\n\n#Determine the bots prefix\nbot = commands.Bot(command_prefix = Config.PREFIX)\n\n@bot.event\nasync def on_ready():\n print(\"===================================\")\n print(\"Logged in as: %s\"%bot.user.name)\n print(\"ID: %s\"%bot.user.id)\n print('Server count:', str(len(bot.servers)))\n print('User Count:',len(set(bot.get_all_members())))\n print(\"Py Lib Version: %s\"%discord.__version__)\n print(\"===================================\")\n\n@bot.command(pass_context = True)\nasync def rules(ctx):\n\t\tembed = discord.Embed(title=\"Welcome To The Official SkiGang Discord Server!\", colour=discord.Colour(0xea821a), timestamp=datetime.datetime.utcfromtimestamp(1547283256))\n\n\t\tembed.set_thumbnail(url=\"https://i.imgur.com/hYceQ6F.jpg\")\n\n\t\tembed.add_field(name=\"Rules\", value=\"1. Do NOT Spam Music unless allowed, or in a music only channel.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"2. Do NOT impersonate anyone.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"3. Do NOT spam any chats.\", inline = False)\n\t\tembed.add_field(name=\"\\u200B\", value=\"4. No trolling, at least keep it to a minimum :wink:\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"5. No Channel hopping. Channel hopping is defined as switching channels in quick succession for either positive or negative purposes.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"6. No glitching of any kind, or attempting to gain control of permissions through dishonest means.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"7. No Innappropriate pictures/porn pics in any chat other than #nsfw-💀\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"8. Be respectful to all users/staff.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"9. No spamming staff for roles/ranks.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"10. Have a fun time and enjoy your stay!\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\t\tembed.add_field(name = \"------------Support Rules/HowTo------------\", value = \"If you have any questions about the discord server or about your Garry's Mod server please see the #support-🎫 channel and use the command -new YOURQUESTION\", inline = False)\n\t\tembed.add_field(name = \"\\u200B\", value = \"DO NOT ASK FOR SUPPORT IN GENERAL CHAT... ONLY #support-🎫 CHAT\", inline = True)\n\t\tembed.add_field(name = \"--------------------END--------------------\", value = \"\\u200B\", inline = True)\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\n\t\tawait bot.say(content=\"\", embed=embed)\n\t\t\n@bot.command(pass_context = True)\nasync def support(ctx):\n\t\tembed = discord.Embed(title=\"Discord Support HowTo\", colour=discord.Colour(0xea821a), timestamp=datetime.datetime.utcfromtimestamp(1547283256))\n\n\t\tembed.set_thumbnail(url=\"https://i.imgur.com/hYceQ6F.jpg\")\n\t\t\n\t\tembed.add_field(name=\"Commands\", value=\"To create a ticket please use the command -new YOURQUESTION\")\n\t\tembed.add_field(name=\"Please give all support staff time to read and respond to each problem/question thanks.\", value=\"\\u200B\")\n\n\t\tawait bot.say(content=\"\", embed=embed)\n \nclient.run(os.getenv('TOKEN'))\n","sub_path":"skibot.py","file_name":"skibot.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583121753","text":"from inspect import getgeneratorstate\n\n\ndef is_even_number():\n value = yield\n\n # запускаем безсконечный генератор (unbound generator)\n while True:\n\n if value % 2:\n result = False\n else:\n result = True\n\n value = yield result\n\n\ndef main():\n print('*' * 80)\n a = 3\n b = 4\n\n # создаем генератор\n even_number_checker = is_even_number()\n\n print(str.format(\n '[*] even_number_checker (created) state: {}',\n getgeneratorstate(even_number_checker)\n ))\n\n # запускае (prime) генератор\n even_number_checker.send(None)\n\n print(str.format(\n '[*] even_number_checker (primed) state: {}',\n getgeneratorstate(even_number_checker)\n ))\n\n print('-' * 80)\n\n # отправляем значение в объект генератор\n a_is_even = even_number_checker.send(a)\n print(str.format('[*] {} is even: {}', a, a_is_even))\n\n print('-' * 80)\n\n # отправляем значение в объект генератор\n b_is_even = even_number_checker.send(b)\n print(str.format('[*] {} is even: {}', b, b_is_even))\n\n # закрываем бесконенчный генератор\n even_number_checker.close()\n\n # закрытый генератор не может принимать значения\n try:\n even_number_checker.send(23)\n except StopIteration:\n pass\n\n print('-' * 80)\n\n print(str.format(\n '[*] even_number_checker (closed) state: {}',\n getgeneratorstate(even_number_checker)\n ))\n\n print('-' * 80)\n\n # создаем новый генератор проверки четных чисел\n yac = is_even_number()\n yac.send(None)\n\n # создаем выражение генератора, которое предоставляет числа, кратные 2 и 7\n even_number_divided_by_seven = (\n even_number for even_number in range(1, 101) if\n yac.send(even_number) is True\n and even_number % 7 == 0\n )\n\n [print(str.format(\n '[*] value: {}', value), end=str.format('\\n{}\\n', '-' * 40)\n ) for value in even_number_divided_by_seven]\n\n print('-' * 80)\n\n print('*' * 80)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"core/builtin_features/generators/generator_function/gen_extended_unbound.py","file_name":"gen_extended_unbound.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"417037579","text":"import requests\nfrom bs4 import BeautifulSoup\nimport bs4\n\ndef getHTMLText(url):\n try:\n r = requests.get(url , timeout = 30)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n return r.text\n except:\n print(\"error\")\n\n\ndef fillUiveList(ulist,html):\n soup = BeautifulSoup(html , \"html.parser\")\n for tr in soup.find(\"tbody\").children:\n if isinstance(tr , bs4.element.Tag):\n tds = tr(\"td\")\n ulist.append([tds[0].string , tds[1].string , tds[2].string])\n\n\ndef printUniveList(ulist,num):\n print(\"{:^10}\\t{:^6}\".format(\"排名\" , \"学校\" ))\n for i in range(num):\n item = ulist[i]\n print(\"{:^10}\\t{:^6}\".format(item[0],item[1]))\n\ndef main():\n uinfo = []\n url = \"http://www.zuihaodaxue.cn/ARWU2018.html\"\n html = getHTMLText(url)\n fillUiveList(uinfo , html)\n printUniveList(uinfo , 20)\n\nif __name__ == '__main__':\n main()","sub_path":"Boss/Request/University.py","file_name":"University.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289181339","text":"import time\nfrom pageobjects.environments import Environments\nfrom pageobjects.nodes import Nodes, RolesPanel\nfrom tests import preconditions\nfrom tests.base import BaseTestCase\n\nERROR_ROLE_CANNOT_COMBINE = 'This role cannot be combined ' \\\n 'with the other roles already selected.'\nROLE_UNALLOCATED = 'UNALLOCATED'\nROLE_CONTROLLER = 'CONTROLLER'\nROLE_COMPUTE = 'COMPUTE'\nROLE_CINDER = 'CINDER'\nROLE_CEPH = 'CEPH-OSD'\n\n\nclass BaseClass(BaseTestCase):\n\n def assertNodeInRoles(self, node, roles):\n for role in roles:\n self.assertIn(role, node.roles.text, \"node's roles\")\n\n def setUp(self):\n BaseTestCase.setUp(self)\n Environments().create_cluster_boxes[0].click()\n Nodes().add_nodes.click()\n time.sleep(1)\n\n\nclass TestRolesSimpleFlat(BaseClass):\n\n @classmethod\n def setUpClass(cls):\n BaseTestCase.setUpClass()\n preconditions.Environment.simple_flat()\n\n def test_controller(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.controller.click()\n self.assertFalse(r.compute.is_enabled())\n self.assertIn(\n ERROR_ROLE_CANNOT_COMBINE,\n r.compute.find_element_by_xpath('../..').text,\n 'error \"{}\" is visible'.format(ERROR_ROLE_CANNOT_COMBINE))\n with Nodes()as n:\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_CONTROLLER])\n self.assertTrue(n.apply_changes.is_enabled())\n n.nodes_discovered[0].checkbox.click()\n self.assertFalse(n.apply_changes.is_enabled())\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_UNALLOCATED])\n\n def test_one_controller_allowed_nodes_disabled(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.controller.click()\n for n in Nodes().nodes_discovered[1:]:\n self.assertFalse(\n n.checkbox.find_element_by_tag_name('input').is_enabled(),\n 'Checkbox is disabled')\n\n def test_one_controller_allowed_controller_role_disabled(self):\n with Nodes()as n:\n with RolesPanel() as r:\n n.nodes_discovered[0].checkbox.click()\n self.assertTrue(r.controller.is_enabled())\n for node in n.nodes_discovered[1:]:\n node.checkbox.click()\n self.assertFalse(r.controller.is_enabled())\n\n def test_compute(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.compute.click()\n self.assertFalse(r.controller.is_enabled())\n self.assertIn(\n ERROR_ROLE_CANNOT_COMBINE,\n r.controller.find_element_by_xpath('../..').text,\n 'error \"{}\" is visible'.format(ERROR_ROLE_CANNOT_COMBINE))\n with Nodes()as n:\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_COMPUTE])\n self.assertTrue(n.apply_changes.is_enabled())\n n.nodes_discovered[0].checkbox.click()\n self.assertFalse(n.apply_changes.is_enabled())\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_UNALLOCATED])\n\n def test_cinder(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.cinder.click()\n with Nodes()as n:\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_CINDER])\n self.assertTrue(n.apply_changes.is_enabled())\n n.nodes_discovered[0].checkbox.click()\n self.assertFalse(n.apply_changes.is_enabled())\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_UNALLOCATED])\n\n def test_ceph(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.ceph_osd.click()\n with Nodes()as n:\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_CEPH])\n self.assertTrue(n.apply_changes.is_enabled())\n n.nodes_discovered[0].checkbox.click()\n self.assertFalse(n.apply_changes.is_enabled())\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_UNALLOCATED])\n\n def test_multiroles(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.controller.click()\n r.cinder.click()\n r.ceph_osd.click()\n with Nodes()as n:\n self.assertNodeInRoles(\n n.nodes_discovered[0],\n [ROLE_CONTROLLER, ROLE_CINDER, ROLE_CEPH])\n\n def test_several_nodes(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n n.nodes_discovered[1].checkbox.click()\n n.nodes_discovered[2].checkbox.click()\n with RolesPanel() as r:\n r.compute.click()\n r.cinder.click()\n r.ceph_osd.click()\n with Nodes()as n:\n self.assertNodeInRoles(\n n.nodes_discovered[0],\n [ROLE_COMPUTE, ROLE_CINDER, ROLE_CEPH])\n self.assertNodeInRoles(\n n.nodes_discovered[1],\n [ROLE_COMPUTE, ROLE_CINDER, ROLE_CEPH])\n self.assertNodeInRoles(\n n.nodes_discovered[2],\n [ROLE_COMPUTE, ROLE_CINDER, ROLE_CEPH])\n\n\nclass TestRolesHAFlat(BaseClass):\n\n @classmethod\n def setUpClass(cls):\n BaseTestCase.setUpClass()\n preconditions.Environment.ha_flat()\n\n def test_controller_role_always_enabled(self):\n with Nodes()as n:\n for node in n.nodes_discovered:\n node.checkbox.click()\n self.assertTrue(RolesPanel().controller.is_enabled())\n RolesPanel().controller.click()\n for node in n.nodes_discovered:\n self.assertNodeInRoles(node, [ROLE_CONTROLLER])\n\n def test_all_nodes_could_be_controller(self):\n RolesPanel().controller.click()\n with Nodes()as n:\n for node in n.nodes_discovered:\n node.checkbox.click()\n for node in n.nodes_discovered:\n self.assertNodeInRoles(node, [ROLE_CONTROLLER])\n","sub_path":"fuelweb_ui_test/tests/test_roles.py","file_name":"test_roles.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578538016","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport numpy as np\n\nlis = []\n\nstructs_params = np.load('/home/chengch/NMA/data/10W/data/struct_params.npy')\nstructs_aligned = np.load('/home/chengch/NMA/data/10W/data/structs_aligned.npy')\nIR = np.load('/home/chengch/NMA/data/10W/data/IR.npy')\ndata = structs_params[:,16]\ndata = abs(data)\n\n#this si making the split_number for all data\nstruct1 =[]\nstruct2= []\nstruct3 = []\nstruct4 = []\nfor _, x in enumerate(data):\n lis.append((_,x)) \n\nfor _ in lis:\n if 170 < _[1] <= 180:\n struct1.append(_)\n elif 160 < _[1] <= 170:\n struct2.append(_)\n elif 150 < _[1] <= 160:\n struct3.append(_)\n elif 140 < _[1] <= 150:\n struct4.append(_)\n\n#this is split the struct_params to 140-150, 150-160, 160-170, 170-180, 160-180\nstruct_params1 =[]\nstruct_params2 = []\nstruct_params3 = []\nstruct_params4 = []\n\nfor _ in struct1:\n struct_params1.append(structs_params[_[0]])\nfor _ in struct2:\n struct_params2.append(structs_params[_[0]])\nfor _ in struct3:\n struct_params3.append(structs_params[_[0]])\nfor _ in struct4:\n struct_params4.append(structs_params[_[0]]) \n\n#\nnp.save('struct_params1.npy',struct_params1)\nnp.save('struct_params2.npy',struct_params2)\nnp.save('struct_params3.npy',struct_params3)\nnp.save('struct_params4.npy',struct_params4)\n#160-180\nfor _ in struct2:\n struct_params1.append(structs_params[_[0]])\nnp.save('struct_params1_2.npy',struct_params1)\n\nprint ('_____________struct_params finished_____________')\n#this is split the IR to 140-150, 150-160, 160-170, 170-180, 160-180\nIR1 = []\nIR2 = [] \nIR3 = []\nIR4 = [] \n\nfor _ in struct1:\n IR1.append(IR[_[0]])\nfor _ in struct2:\n IR2.append(IR[_[0]])\nfor _ in struct3:\n IR3.append(IR[_[0]])\nfor _ in struct4:\n IR4.append(IR[_[0]]) \n\nnp.save('IR1.npy',IR1)\nnp.save('IR2.npy',IR2)\nnp.save('IR3.npy',IR3)\nnp.save('IR4.npy',IR4)\n#160-180\nfor _ in struct2:\n IR1.append(IR[_[0]])\nnp.save('IR1_2.npy',IR1)\nprint ('_____________IR finished_____________')\n\nstruct_aligned1 = []\nstruct_aligned2 = []\nstruct_aligned3 = []\nstruct_aligned4 = []\n\nfor _ in struct1:\n struct_aligned1.append(structs_aligned[_[0]])\nfor _ in struct2:\n struct_aligned2.append(structs_aligned[_[0]])\nfor _ in struct3:\n struct_aligned3.append(structs_aligned[_[0]])\nfor _ in struct4:\n struct_aligned4.append(structs_aligned[_[0]])\n\nnp.save('struct_aligned1.npy',struct_aligned1)\nnp.save('struct_aligned2.npy',struct_aligned2)\nnp.save('struct_aligned3.npy',struct_aligned3)\nnp.save('struct_aligned4.npy',struct_aligned4)\n\nfor _ in struct2:\n struct_aligned1.append(structs_aligned[_[0]])\n\nnp.save('struct_aligned1_2.npy',struct_aligned1)\n","sub_path":"data_wash_copy.py","file_name":"data_wash_copy.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491787881","text":"import numpy\nimport scipy.linalg\n\n# as column vector\nP0b = numpy.matrix([[0.33, 0.33, 0.34]])\n\nQb = numpy.matrix([[-0.21, 0.2, 0.01],\n [ 0.05, -0.1, 0.05],\n [ 0.01, 0.2, -0.21]])\n\nMb = numpy.matrix([[0.21, 0, 0 ],\n [0, 0.1, 0 ],\n [0, 0, 0.21]])\n\nPEb = numpy.matrix([[ 0, 20./21., 1./21.],\n [ 1./2., 0, 1./2. ],\n [20./21., 1./21., 0 ]])\n\nPEb_corrected = numpy.matrix([[ 0, 20./21., 1./21.],\n [ 1./2., 0, 1./2. ],\n [ 1./21., 20./21., 0 ]])\n\nUSb = numpy.matrix([[-0.1, 0.05],\n [ 0.2, -0.21]])\n\ndef Q_from_M_PE(M, PE):\n return M * (PE - numpy.eye(M.shape[0]))\n\ndef p_t_given_s(Qx, t, s):\n return numpy.asmatrix(scipy.linalg.expm(Qx * (t - s)))\n\ndef p_t(Qx, Px0, t):\n return Px0 * scipy.linalg.expm(Qx * t)\n\n#----------------------------------\n\ndef barometric_example_subsystem_dist(t):\n entrance_dist = numpy.matrix([0.5, 0.5])\n S_intensity = numpy.matrix([[-0.1, 0.05],\n [ 0.2, -0.21]])\n expS = scipy.linalg.expm(S_intensity * t)\n e = numpy.asmatrix(numpy.ones(entrance_dist.shape[0])).T\n return 1 - entrance_dist * expS * e\n\ndef barometric_example_subsystem_dist_direct(t):\n \"\"\" Example 2.4: distribution in time over when the pressure begins to fall. \"\"\"\n return 1 - 1.0476*pow(0.960,t) + 0.0476*pow(0.7641,t)\n\n","sub_path":"sandbox/clayton/ctbn.py","file_name":"ctbn.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"552536440","text":"import sys\nimport subprocess\nimport re\n\nfrom PySide import QtGui\nfrom PySide import QtCore\nfrom PySide.QtWebKit import QWebView, QWebSettings\n\nnotif_h = 230\nnotif_w = 250\nnotif_x = 100\nnotif_y = 100\n\ndef scan(view):\n\twindow = subprocess.Popen([\"xdotool\", \"getactivewindow\"],stdout=subprocess.PIPE)\n\twindow_id = window.communicate()[0].strip(\"\\n\")\n\twindow_inf=subprocess.Popen([\"xwininfo\", \"-id\" ,window_id],stdout=subprocess.PIPE)\n\twindow_info = window_inf.communicate()[0].strip(\"\\n\")\n\t#print window_info\n\n\tgeometry = re.findall(\"\\\"([\\s\\S]*)\\\"[\\s\\S]*Absolute upper-left X:\\s*(-*\\d+)\\s*Absolute upper-left Y:\\s*(-*\\d+)[\\s\\S]*Width:\\s*(\\d+)\\s*Height:\\s*(\\d+)\",\n\t\t\t\t\t\t\twindow_info)\n\n\t#print geometry\n\n\t#if not view.isActiveWindow():\n\tif view.x() != int(geometry[0][1]) and view.y() != int(geometry[0][2]):\n\t\tview.setGeometry(int(geometry[0][1])+int(geometry[0][3]),int(geometry[0][2]),notif_w,notif_h)\n\t\tview.raise_()\n\n\treturn 0\n\n\nclass MainWindow(QtGui.QWidget):\n\tdef __init__(self):\n\t\tQtGui.QWidget.__init__(self)\n\n\t\tself.qbutton=QtGui.QPushButton(self)\n\t\tself.qbutton.setText(\"Quit\")\n\t\tself.qbutton.clicked.connect(QtCore.QCoreApplication.instance().quit)\n\t\tself.qbutton.setGeometry(100,100,100,50)\n\n\t\tself.setGeometry(200,200,500,400)\n\t\tself.setWindowTitle('Quit button')\n\t\t\n #self.show()\n\n\"\"\"\"\nif __name__ == '__main__':\n \n\tapp = QtGui.QApplication(sys.argv)\n\twindow=MainWindow()\n\twindow.show()\n\n\tview = QWebView()\n\tview.setGeometry(notif_x,notif_y,notif_w,notif_h)\n\tview.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Expanding)\n\tview.setWindowFlags(QtCore.Qt.FramelessWindowHint)\n\tview.load(\"index.html\")\n\t#view.show()\n\n\tglobal_timer = QtCore.QTimer()\n\tglobal_timer.timeout.connect(lambda: scan(view))\n\tglobal_timer.start(50)\n\t\n\tsys.exit(app.exec_())\n\"\"\"","sub_path":"desktop/pygui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"45416333","text":"# Copyright 2017 AT&T Corporation.\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\nimport mock\nimport os\n\nfrom tempest import config\nfrom tempest.tests import base\n\nfrom patrole_tempest_plugin import rbac_policy_parser\n\nCONF = config.CONF\n\n\nclass RbacPolicyTest(base.TestCase):\n\n def setUp(self):\n super(RbacPolicyTest, self).setUp()\n\n current_directory = os.path.dirname(os.path.realpath(__file__))\n self.custom_policy_file = os.path.join(current_directory,\n 'resources',\n 'custom_rbac_policy.json')\n self.admin_policy_file = os.path.join(current_directory,\n 'resources',\n 'admin_rbac_policy.json')\n self.alt_admin_policy_file = os.path.join(current_directory,\n 'resources',\n 'alt_admin_rbac_policy.json')\n self.tenant_policy_file = os.path.join(current_directory,\n 'resources',\n 'tenant_rbac_policy.json')\n\n @mock.patch.object(rbac_policy_parser, 'LOG', autospec=True)\n def test_custom_policy(self, m_log):\n default_roles = ['zero', 'one', 'two', 'three', 'four',\n 'five', 'six', 'seven', 'eight', 'nine']\n\n converter = rbac_policy_parser.RbacPolicyParser(\n None, \"test\", self.custom_policy_file)\n\n expected = {\n 'policy_action_1': ['two', 'four', 'six', 'eight'],\n 'policy_action_2': ['one', 'three', 'five', 'seven', 'nine'],\n 'policy_action_3': ['zero'],\n 'policy_action_4': ['one', 'two', 'three', 'five', 'seven'],\n 'policy_action_5': ['zero', 'one', 'two', 'three', 'four', 'five',\n 'six', 'seven', 'eight', 'nine'],\n 'policy_action_6': ['eight'],\n }\n\n fake_rule = 'fake_rule'\n\n for role in default_roles:\n self.assertFalse(converter.allowed(fake_rule, role))\n m_log.debug.assert_called_once_with(\n \"{0} not found in policy file.\".format('fake_rule'))\n m_log.debug.reset_mock()\n\n for rule, role_list in expected.items():\n for role in role_list:\n self.assertTrue(converter.allowed(rule, role))\n for role in set(default_roles) - set(role_list):\n self.assertFalse(converter.allowed(rule, role))\n\n def test_admin_policy_file_with_admin_role(self):\n converter = rbac_policy_parser.RbacPolicyParser(\n None, \"test\", self.admin_policy_file)\n\n role = 'admin'\n allowed_rules = [\n 'admin_rule', 'is_admin_rule', 'alt_admin_rule'\n ]\n disallowed_rules = ['non_admin_rule']\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertTrue(allowed)\n\n for rule in disallowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertFalse(allowed)\n\n def test_admin_policy_file_with_member_role(self):\n converter = rbac_policy_parser.RbacPolicyParser(\n None, \"test\", self.admin_policy_file)\n\n role = 'Member'\n allowed_rules = [\n 'non_admin_rule'\n ]\n disallowed_rules = [\n 'admin_rule', 'is_admin_rule', 'alt_admin_rule']\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertTrue(allowed)\n\n for rule in disallowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertFalse(allowed)\n\n def test_admin_policy_file_with_context_is_admin(self):\n converter = rbac_policy_parser.RbacPolicyParser(\n None, \"test\", self.alt_admin_policy_file)\n\n role = 'fake_admin'\n allowed_rules = ['non_admin_rule']\n disallowed_rules = ['admin_rule']\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertTrue(allowed)\n\n for rule in disallowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertFalse(allowed)\n\n role = 'super_admin'\n allowed_rules = ['admin_rule']\n disallowed_rules = ['non_admin_rule']\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertTrue(allowed)\n\n for rule in disallowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertFalse(allowed)\n\n def test_tenant_policy(self):\n \"\"\"Test whether rules with format tenant_id:%(tenant_id)s work.\n\n Test whether Neutron rules that contain project_id, tenant_id, and\n network:tenant_id pass.\n \"\"\"\n test_tenant_id = mock.sentinel.tenant_id\n converter = rbac_policy_parser.RbacPolicyParser(\n test_tenant_id, \"test\", self.tenant_policy_file)\n\n # Check whether Member role can perform expected actions.\n allowed_rules = ['rule1', 'rule2', 'rule3']\n for rule in allowed_rules:\n allowed = converter.allowed(rule, 'Member')\n self.assertTrue(allowed)\n self.assertFalse(converter.allowed('admin_rule', 'Member'))\n\n # Check whether admin role can perform expected actions.\n allowed_rules.append('admin_rule')\n for rule in allowed_rules:\n allowed = converter.allowed(rule, 'admin')\n self.assertTrue(allowed)\n\n # Check whether _try_rule is called with the correct target dictionary.\n with mock.patch.object(converter, '_try_rule', autospec=True) \\\n as mock_try_rule:\n mock_try_rule.return_value = True\n\n expected_target = {\n \"project_id\": test_tenant_id,\n \"tenant_id\": test_tenant_id,\n \"network:tenant_id\": test_tenant_id\n }\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, 'Member')\n self.assertTrue(allowed)\n mock_try_rule.assert_called_once_with(\n rule, expected_target, mock.ANY, mock.ANY)\n mock_try_rule.reset_mock()\n","sub_path":"tests/test_rbac_policy_parser.py","file_name":"test_rbac_policy_parser.py","file_ext":"py","file_size_in_byte":6908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"146396702","text":"import logging\nimport grpc\n\nimport python_to_rust_simple_pb2\nimport python_to_rust_simple_pb2_grpc\nfrom datetime import datetime\n\n\nREQUEST_COUNT = 10000\n\n\ndef run():\n with grpc.insecure_channel(\n \"localhost:50051\", compression=grpc.Compression.Gzip\n ) as channel:\n\n stub = python_to_rust_simple_pb2_grpc.PythonToRustSimpleServiceStub(channel)\n start = datetime.now()\n for i in range(REQUEST_COUNT):\n response = stub.increase(python_to_rust_simple_pb2.IncreaseRequest(num=i))\n assert response.num == i + 1\n print(f\"{REQUEST_COUNT} requests is completed in {datetime.now() - start}\")\n\n\nif __name__ == \"__main__\":\n logging.basicConfig()\n run()\n","sub_path":"python_to_rust_simple/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"415291515","text":"#!/usr/bin/env python3\n\n\"\"\"\nMake all the histograms\n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom h5py import File\nfrom collections import defaultdict\nimport numpy as np\nimport re, json\n\ndef get_args():\n parser = ArgumentParser(description=__doc__)\n parser.add_argument('input_files', nargs='+')\n parser.add_argument('-c','--counts')\n parser.add_argument('-o','--output-name', required=True)\n return parser.parse_args()\n\ndef get_mass(jets, j1, j2):\n eta, phi, pt = [jets['jet_' + x] for x in ['eta','phi','pt']]\n m2 = 2*pt[:,j1]*pt[:,j2]*(np.cosh(eta[:,j1] - eta[:,j2]) -\n np.cos(phi[:,j1] - phi[:,j2]))\n return np.sqrt(m2)\n\nclass Histogram:\n def __init__(self, edges=0, do_errors=False):\n self.counts = 0\n self.edges = edges\n self.errors = 0\n self._do_errors = do_errors\n def fill(self, values, weights=None):\n counts, edges = np.histogramdd(\n values, bins=self.edges, weights=weights)\n self.counts += counts\n if self._do_errors:\n errors, _ = np.histogramdd(\n values, bins=self.edges, weights=weights**2)\n self.errors += errors\n def __iadd__(self, other):\n self.counts += other.counts\n self.errors += other.errors\n # todo, check the edges and do_errors\n # but also allow them to be different if the old histogram is\n # empty\n self.edges = other.edges\n self._do_errors = other._do_errors\n return self\n def __add__(self, other):\n hist = Histogram(np.array(self.edges))\n hist.counts = np.array(self.counts)\n hist.errors = np.array(self.errors)\n hist._do_errors = self._do_errors\n hist += other\n return hist\n def write_to(self, group, name):\n hist_group = group.create_group(name)\n hist_group.attrs['hist_type'] = 'n_dim'\n hist_group.create_dataset('values', data=self.counts,\n chunks=self.counts.shape)\n if self._do_errors:\n hist_group.create_dataset('errors', data=np.sqrt(self.errors),\n chunks=self.counts.shape)\n for num, edges in enumerate(self.edges):\n hist_group.create_dataset(f'axis_{num}', data=edges)\n\ndef make_hists(grp, hists, sample_norm, slice_size=1000000):\n event_ds = grp['1d']\n jets_ds = grp['2d']\n mass_binning = np.concatenate(\n ([-np.inf], np.linspace(0, 1e3, 100+1), [np.inf]))\n for start in range(0, event_ds.shape[0], slice_size):\n sl = slice(start, start+slice_size)\n weights = event_ds['weight', sl] * sample_norm\n jets = jets_ds[sl,:]\n\n pass_jvt = jets['jet_JvtPass_Medium'] == 1\n good_jets = pass_jvt & ~np.isnan(jets['jet_eta'])\n good_jet_number = np.add.accumulate(good_jets, axis=1)\n n_jets = good_jet_number[:,-1]\n good_jet_number[~good_jets] = 0\n good_events = n_jets >= 3\n\n weights = weights[good_events]\n jets = jets[good_events,:]\n good_jet_number = good_jet_number[good_events,:]\n\n sel_jets = np.stack(\n [jets[good_jet_number == x] for x in [1,2,3]], axis=1)\n\n mass23 = get_mass(sel_jets, 1, 2)\n mass13 = get_mass(sel_jets, 0, 2)\n mass12 = get_mass(sel_jets, 0, 1)\n masses = np.stack((mass12, mass13, mass23), axis=1)\n\n mass_hist = Histogram([mass_binning]*masses.shape[1])\n mass_hist.fill(masses, weights=weights)\n hists['mass'] += mass_hist\n\n mass_1323 = Histogram([mass_binning]*2, do_errors=True)\n mass_1323.fill(np.stack((mass13,mass23), axis=1), weights=weights)\n hists['mass_1323'] += mass_1323\n\n return hists\n\ndef run():\n args = get_args()\n if args.counts:\n with open(args.counts) as cfile:\n counts_dict = json.load(cfile)\n else:\n counts_dict = defaultdict(lambda: 1.0)\n hists = defaultdict(Histogram)\n id_re = re.compile('\\.([0-9]{6,8})\\.')\n for fname in args.input_files:\n sample_id = id_re.search(fname).group(1)\n sample_norm = 1 / float(counts_dict[sample_id])\n with File(fname,'r') as h5file:\n grp = h5file['outTree']\n n_events = grp['1d'].shape[0]\n print(f'running on {n_events:,} events')\n make_hists(grp, hists, sample_norm)\n\n with File(args.output_name,'w') as out_file:\n for name, hist in hists.items():\n hist.write_to(out_file, name)\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"make_hists.py","file_name":"make_hists.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"390076858","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nimport ast\n\n@frappe.whitelist()\ndef get_resource_complete(parent_table, child_tables):\n \"\"\"get table and child tables\n\n args:\n parent_table -- parent table name\n child_tables -- list of [target column name, child table name] ex: [['items', 'tabDetail']]\n \"\"\"\n child_tables = ast.literal_eval(child_tables)\n parent = frappe.db.sql(\"SELECT * FROM `%s`\" % parent_table, as_dict=True)\n parent_length = len(parent)\n for child in child_tables:\n tmp = frappe.db.sql(\"SELECT * FROM `%s` ORDER BY idx\" % child[1], as_dict=True)\n ln = len(tmp)\n for i in range(ln):\n for j in range(parent_length):\n if tmp[i][\"parent\"] == parent[j][\"name\"]:\n if child[0] not in parent[j]:\n parent[j][child[0]] = []\n parent[j][child[0]].append(tmp[i])\n break\n return parent\n\n@frappe.whitelist()\ndef get_theme_setting():\n data = frappe.db.sql(\"\"\"SELECT * FROM `tabSingles` WHERE doctype = 'Theme Setting' \"\"\", as_dict=1)\n return data\n","sub_path":"bdtheme/provider.py","file_name":"provider.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26758941","text":"import urllib.request\nimport json\nfrom urllib.parse import quote\n\n#зоны\n\"\"\"\ngeourl = \"http://api.unit-online.ru/zones\"\nrespornse = urllib.request.urlopen(geourl)\ncontent = respornse.read()\ndata = json.loads(content.decode(\"utf8\"))\nfor i in data[\"zones\"]:\n print(i)\n\"\"\"\n#поиск персонажа\n\"\"\"\ndef poiskpers(nick):\n geourl = \"http://api.unit-online.ru/online?type=user&name={0}\".format(quote(nick))\n respornse = urllib.request.urlopen(geourl)\n i = respornse.read()\n data = json.loads(i.decode(\"utf8\"))\n print()\n\n if \"clan\" in data[\"user\"]:\n return \"<img src=\\\"http://www.unit-online.ru/icons/icon/clan%s.png\\\">%s[%s]\" \\\n \"<a target=\\\"_blank\\\" href=\\\"http://unit-online.ru/character?id=%s\\\">\" \\\n \"<img src=\\\"http://unit-online.ru/static/img/ico_i.gif\\\"></a> %s<br>\" \\\n % (data[\"user\"][\"clan\"], nick, data[\"user\"][\"level\"], data[\"user\"][\"id\"], data[\"online\"])\n elif \"clan\" not in data[\"user\"]:\n return \"%s[%s]\" \\\n \"<a target=\\\"_blank\\\" href=\\\"http://unit-online.ru/character?id=%s\\\">\" \\\n \"<img src=\\\"http://unit-online.ru/static/img/ico_i.gif\\\"></a> %s<br>\" \\\n % (nick, data[\"user\"][\"level\"], data[\"user\"][\"id\"], data[\"online\"])\n\nprint(poiskpers(\"жириновский в в\"))\n\"\"\"\n\noruzh = {\"Ближний бой\":{}, \"Энергетическое оружие\":{}, \"Тяжёлое оружие\":{}, \"Лёгкое оружие\":{}}\nbb = []\ngeourl = \"http://api.unit-online.ru/items?type={0}\".format(quote(\"оружие\"))\nrespornse = urllib.request.urlopen(geourl)\ni = respornse.read()\ndata = json.loads(i.decode(\"utf8\"))\nfor i in data[\"items\"]:\n geourl = \"http://api.unit-online.ru/item?id=%s\" % i[\"id\"]\n respornse = urllib.request.urlopen(geourl)\n ctrp = respornse.read()\n data1 = json.loads(ctrp.decode(\"utf8\"))\n print(data1[\"item\"][\"params\"])\n","sub_path":"parsejson/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"12479019","text":"import boto3\nimport json\nimport logging\n\nfrom botocore.exceptions import ClientError\n\n\nlogging.basicConfig(\n format='%(asctime)s|%(name).10s|%(levelname).5s: %(message)s',\n level=logging.WARNING\n)\n\nlog = logging.getLogger('LoggerDefinition')\nlog.setLevel(logging.DEBUG)\n\n\n\nclass LoggerDefinition(object):\n\n\n def __init__(self, s):\n\n self._gg = s.client('greengrass')\n self._iot = s.client('iot')\n\n\n def formatDefinition(self, config, cfntmp):\n ''' Format a Cloudformation Greengrass Group Logger Definition.\n '''\n loggers = []\n\n for logger in config.get('Loggers', []):\n loggers.append(logger)\n\n cfntmp.format(loggers=json.dumps(loggers))\n","sub_path":"gg_manager/definitions/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274723376","text":"#Implementation af fixpunktsmetoden til bestemmelse af nulpunkt\nimport matplotlib.pyplot as plt\nimport math\nimport numpy as np\n\n#Funktionen for fixpunktsmetoden\ndef iter(f, xinit, N):\n L1 = [i for i in range(N+1)]\n L2 = [0.0 for i in range(N+1)]\n L2[0] = xinit\n for i in range(N):\n L2[i+1] = f(L2[i])\n return zip(L1, L2)\n\n#Den oprindelige funktion\ndef f(x):\n return x*np.cosh(75/x)-x-15\n\n#De to forskellige omskrivniger (g(x))\ndef func1(x):\n return x*np.cosh(75/x)-15 #Den konvergerer\n\ndef func2(x):\n return (x+15)/(np.cosh(75/x)) #Den konvergerer ikke\n\n#Variable\nx0=100 #Initierende gæt\niterationer=30 #Antal iterationer\n\n#Den omskrivning der undersøges\nf_valgt = func1\n\nX = iter(f_valgt,x0,iterationer)\n\nprint('Iteration Værdi')\n\nfor i, fi in X:\n print('%5d %5.8E' % (i, fi))\n\n#Herunder sættes hvad der skal plottes\nx = np.linspace(-100,1000,1000)\ny1 = f_valgt(x) #Hvilken omskrivning der printes\ny2 = x # y = x printes\ny_oprindelig = f(x) #Den oprindelige funktion, f(x), printes\n\n#Funktionerne plottes\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\n#Akserne tilpasses\nplt.axis([1, 250, 0, 250])\n\n#Plotter den valgte funktion samt y=x\nplt.plot(x, y1, 'r', label=\"g(x)\")\nplt.plot(x, y2, 'b', label='y = x')\nplt.plot(x, y_oprindelig, '--k', label='f(x)')\n\n#Modifikation af plots\nax.spines['right'].set_color('none') #Fjerner højre side af kassen\nax.spines['top'].set_color('none') #Fjerner toppen af kassen\nplt.axhline(c = 'black', lw = 0.7) #Tilføjer x-akse\nplt.legend(loc=\"best\")\nplt.show()","sub_path":"Eksamen_1/Iteration.py","file_name":"Iteration.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558542494","text":"# python3 showflattened.py flattened_images-x10-y15.txt 15 10 0\n\"\"\" get 1d flattened image to an picture on the sreen\nsee CHANGE below\n\"\"\"\nimport numpy as np\nimport sys\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\nA = np.loadtxt(sys.argv[1])\nprint(A.shape)\nydim=int(sys.argv[2])\nxdim=int(sys.argv[3])\nB=A.reshape((A.shape[0],ydim, xdim))\n#print(B)\n\n\nbigfig= np.concatenate(B[:][:][:],1)\nprint (bigfig.shape)\n#newshapeY = int(round(bigfig.shape[0]*2))\n#newshapeX= int(round(bigfig.shape[1]/2))\n#print(newshapeY, newshapeX)\n#bigfig= bigfig.reshape((150, -1))\n\n# CHANGE (if dimensions do not match)\nif int(sys.argv[4]) > 0:\n bigfig= np.hsplit(bigfig,sys.argv[4])\n bigfig= np.concatenate(bigfig[:][:][:],0)\n\n#bigfig=np.asarray(bigfig)\n#bigfig = np.asarray(bigfig)\nprint(bigfig.shape)\nplt.imshow(bigfig, cmap = 'gray', interpolation = 'bicubic')\nplt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis\nplt.show()\n\n\n","sub_path":"showflattened.py","file_name":"showflattened.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"318058771","text":"from django import forms\nfrom django.forms import ModelForm\nfrom django.utils.translation import gettext_lazy as _\nfrom django.contrib.auth import get_user_model\n\nfrom peanut.store.models import Address, Customer, ShippingContact\n\nclass PaymentMethodForm(forms.Form):\n token_id = forms.CharField(widget=forms.HiddenInput(),\n required=False)\n name = forms.CharField(label=_('Nombre del tarjetahabiente'),\n max_length=25,\n widget=forms.TextInput(attrs={\n 'size': 25,\n 'maxlength': 25,\n 'data-conekta': 'card[name]'}))\n reference = forms.CharField(label=_('Numero de tarjeta de credito'),\n max_length=26,\n widget=forms.TextInput(attrs={\n 'size': 26,\n 'maxlength': 26,\n 'data-conekta': 'card[number]'}))\n card_cvc = forms.CharField(label='CVC',\n max_length=4, \n widget=forms.TextInput(attrs={\n 'size': 4,\n 'maxlength': 4,\n 'data-conekta': 'card[cvc]'}))\n exp_month = forms.CharField(label='Fecha de expiracion (MM/AAAA)',\n max_length=2, \n widget=forms.TextInput(attrs={\n 'size': 2,\n 'maxlength': 2,\n 'data-conekta': 'card[exp_month]'}))\n exp_year = forms.CharField(label='/',\n max_length=4, \n widget=forms.TextInput(attrs={\n 'size': 4,\n 'maxlength': 4,\n 'data-conekta': 'card[exp_year]'}))\n\nclass PaymentMethodUpdateForm(forms.Form):\n name = forms.CharField(label=_('Nombre del tarjetahabiente'),\n max_length=25,\n widget=forms.TextInput(attrs={\n 'size': 25,\n 'maxlength': 25,\n 'data-conekta': 'card[name]'}))\n exp_month = forms.CharField(label='Fecha de expiracion (MM/AAAA)',\n max_length=2, \n widget=forms.TextInput(attrs={\n 'size': 2,\n 'maxlength': 2,\n 'data-conekta': 'card[exp_month]'}))\n exp_year = forms.CharField(label='/',\n max_length=4, \n widget=forms.TextInput(attrs={\n 'size': 4,\n 'maxlength': 4,\n 'data-conekta': 'card[exp_year]'}))\n\nclass ShippingContactForm(forms.Form):\n name = forms.CharField(max_length=50)\n phone = forms.CharField(max_length=50)\n between_streets = forms.CharField(max_length=100)\n street1 = forms.CharField(max_length=100)\n street2 = forms.CharField(max_length=100)\n city = forms.CharField(max_length=50)\n state = forms.CharField(max_length=50)\n country = forms.CharField(max_length=2)\n postalcode = forms.CharField(max_length=5)\n residential = forms.BooleanField()\n\nclass AddressForm(ModelForm):\n \n class Meta:\n model = Address\n fields = '__all__'\n\nclass CustomerForm(forms.Form):\n first_name = forms.CharField(label=_('first name'), max_length=30)\n last_name = forms.CharField(label=_('last name'), max_length=30)\n phone = forms.CharField(max_length=50, required=False)\n email = forms.EmailField(label=_('email address'))","sub_path":"peanut/store/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609978220","text":"# Copyright 2018 The Simons Foundation, Inc. - 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\nimport netket as nk\nfrom scipy.sparse.linalg import eigs\n\n# 1D Lattice\ng = nk.graph.Hypercube(length=14, n_dim=1, pbc=True)\n\n# Hilbert space of spins on the graph\nhi = nk.hilbert.Spin(s=0.5, graph=g)\n\n# Ising spin hamiltonian\nha = nk.operator.Ising(h=1.0, hilbert=hi)\n\n# Use scipy sparse diagonalization\nvals, vecs = eigs(ha.to_sparse(), k=3, which=\"SR\")\nprint(\"eigenvalues with scipy sparse:\", vals.real)\n\n# Use internal Lanczos Solver Instead\n# Perform Lanczos Exact Diagonalization to get lowest three eigenvalues\nres = nk.exact.lanczos_ed(ha, first_n=3, compute_eigenvectors=True)\n\n# Print eigenvalues\nprint(\"\\neigenvalues with internal solver:\", res.eigenvalues)\n\n# Compute energy of ground state\nprint(\"\\ng.s. energy:\", res.mean(ha, 0).real)\n\n# Compute energy of first excited state\nprint(\"\\nfirst excited energy:\", res.mean(ha, 1).real)\n","sub_path":"Examples/ExactDiag/ising1d.py","file_name":"ising1d.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127017699","text":"import json\nfrom django.conf import settings\n\nfrom scm.v1.ultilities import get_data\nfrom scm.v1.models import Projects\n\nclass ProjectsFunction:\n\n user = None\n\n def __init__(self, user):\n self.user = user\n\n def create(self, **kwargs):\n try:\n project_obj, created = Projects.objects.get_or_create(uuid=kwargs['uuid'],\n owner=self.user,\n name=kwargs['name'],\n key=kwargs['key'])\n print(project_obj)\n if project_obj and created is True:\n project_obj.description = kwargs['description']\n project_obj.is_private = kwargs['is_private']\n project_obj.created_date = kwargs['created']\n project_obj.modified_date = kwargs['updated']\n project_obj.save()\n return project_obj, True\n except Exception as ex:\n print(ex)\n return None, False\n\n\n def get_projects_from_bitbucket(self):\n try:\n url = settings.BITBUCKET_URL + '/' + settings.BITBUCKET_VER + \\\n '/teams/' + settings.BITBUCKET_TEAM + '/projects/'\n list_project = get_data(url)\n dict_project_name = {}\n if list_project is not None:\n json_project = json.loads(list_project)\n pagelen = int(json_project[\"pagelen\"])\n # size_br = int(json_branch[\"size\"])\n page_br = int(json_project[\"page\"])\n # page_next = json_branch[\"next\"]\n list_values_project = json_project[\"values\"]\n\n for project in list_values_project:\n data = {\n 'uuid': project['uuid'],\n 'repositories': project['links']['repositories']['href'],\n 'name': project[\"name\"],\n 'created': project['created_on'],\n 'updated': project['updated_on'],\n 'is_private': project['is_private'],\n 'description': project['description'],\n 'key': project[\"key\"],\n }\n project_obj, result = self.create(**data)\n if result is False:\n print(project)\n return True\n except Exception as ex:\n print(ex)\n return None\n\n\n def get(self):\n try:\n return Projects.objects.all()\n except Exception as ex:\n return None\n\n\n def get_by_key(self, key):\n try:\n return Projects.objects.get(key=key)\n except Exception as e:\n print(e)\n return None\n\n\n","sub_path":"controller/scm/v1/modules/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"94491835","text":"from __future__ import absolute_import\nfrom datetime import datetime, timedelta\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.http import HttpRequest\n\nimport logging\nfrom dimagi.utils.parsing import string_to_datetime\n\ndef wrap_with_dates():\n \"\"\"Wraps a request with dates based on url params or defaults and\n Checks date validity.\"\"\"\n # this is loosely modeled after example number 4 of decorator\n # usage here: http://www.python.org/dev/peps/pep-0318/\n def get_dates(f):\n def wrapped_func(*args, **kwargs):\n # wrap everything besides the function call in a try/except\n # block. we don't ever want this to prevent the \n # basic view functionality from working. \n # attempt to find the request object from all the argument\n # values, checking first the args and then the kwargs \n req = None\n for arg in args:\n if _is_http_request(arg):\n req = arg\n break\n if not req:\n for arg in kwargs.values():\n if _is_http_request(arg):\n req = arg\n break\n if req:\n dict = req.POST if req.method == \"POST\" else req.GET\n req.startdate = None\n req.enddate = None\n if \"startdate\" in dict:\n if \"enddate\" in dict:\n req.startdate = string_to_datetime(dict[\"startdate\"])\n req.enddate = string_to_datetime(dict[\"enddate\"])\n if req.enddate < req.startdate:\n raise Exception((\"You can't have an end date \"\n \"of %s after start date of %s\")\n % (req.enddate, req.startdate))\n else:\n # TODO: Be more graceful\n raise Exception(\"You have to specify both or 0 dates!\")\n else:\n # default to the current month\n now = datetime.now()\n first_of_next_month = datetime(now.year, now.month + 1, 1)\n req.enddate = first_of_next_month - timedelta(days=1)\n req.startdate = datetime(now.year, now.month, 1)\n \n return f(*args, **kwargs) \n if hasattr(f, \"func_name\"):\n wrapped_func.func_name = f.func_name\n return wrapped_func\n else:\n # this means it wasn't actually a view. \n return f \n return get_dates\n\ndef _is_http_request(obj):\n return obj and isinstance(obj, HttpRequest)\n\ndef _validate_timeouts(refresh_stale, cache_timeout):\n if not isinstance(cache_timeout, int):\n raise ValueError('Cache timeout should be an int. '\n 'It is the number of seconds until the cache expires.')\n if not isinstance(refresh_stale, int):\n raise ValueError('refresh_stale should be an int. '\n 'It is the number of seconds to wait until celery regenerates the cache.')\n\ndef cache_report(refresh_stale=1800, cache_timeout=3600):\n _validate_timeouts(refresh_stale, cache_timeout)\n def cacher(func):\n def retrieve_cache(report):\n # cache_overrides\n if report.request.GET.get('cache') == 'no':\n use_cache = False\n elif hasattr(settings, 'REPORT_CACHING'):\n use_cache = settings.REPORT_CACHING\n else:\n use_cache = True\n\n from corehq.apps.reports.generic import GenericReportView\n if not isinstance(report, GenericReportView):\n raise ValueError(\"The decorator 'cache_report' is only for reports that are instances of GenericReportView.\")\n\n if report._caching or use_cache is False:\n if use_cache is False:\n logging.info(\"Not using old cache for report %s.\" % report.name)\n\n context = None\n cache_key = report.generate_cache_key(func.__name__)\n\n cached_data = None\n try:\n cached_data = cache.get(cache_key)\n except Exception as e:\n logging.error(\"Could not fetch cache for report %s due to error: %s\" % (report.name, e))\n\n if isinstance(cached_data, dict) and use_cache is not False:\n data_key = report.queried_path\n context = cached_data.get(data_key)\n\n if context is None:\n context = func(report)\n\n try:\n from corehq.apps.reports.tasks import report_cacher\n report_cacher.delay(report, func.__name__, cache_key,\n current_cache=cached_data, refresh_stale=refresh_stale, cache_timeout=cache_timeout)\n except Exception as e:\n logging.error(\"Could not send <%s, %s> to report_cacher due to error: %s\" %\n (report.__class__.__name__, func.__name__, e))\n\n return context\n return retrieve_cache\n return cacher\n\ndef cache_users(refresh_stale=1800, cache_timeout=3600):\n _validate_timeouts(refresh_stale, cache_timeout)\n def cacher(func):\n def retrieve_cache(domain, **kwargs):\n if hasattr(settings, 'REPORT_CACHING'):\n use_cache = settings.REPORT_CACHING\n else:\n use_cache = True\n\n caching = kwargs.get('caching', False)\n simplified = kwargs.get('simplified', False)\n\n if caching or not simplified or use_cache is False:\n if use_cache is False:\n logging.info(\"Not caching users.\")\n return func(domain, **kwargs)\n\n individual = kwargs.get('individual')\n group = kwargs.get('group')\n user_filter = kwargs.get('user_filter')\n\n cache_key = \"%(domain)s:USERS:%(group)s:%(individual)s:%(filters)s\" % dict(\n domain=domain,\n group=group,\n individual=individual,\n filters=\".\".join([\"%s\" % f.type for f in user_filter if f.show])\n )\n\n cached_data = None\n try:\n cached_data = cache.get(cache_key)\n except Exception as e:\n logging.error('Could not fetch cached users list for domain %s due to error: %s' % (domain, e))\n\n user_list = None\n if isinstance(cached_data, dict):\n user_list = cached_data.get('data')\n\n if user_list is None:\n user_list = func(domain, **kwargs)\n\n try:\n from corehq.apps.reports.tasks import user_cacher\n user_cacher.delay(domain, cache_key, cached_data, refresh_stale, cache_timeout, caching=True, **kwargs)\n except Exception as e:\n logging.error(\"Could not send user list for domain %s to user_cacher due to error: %s\" % (domain, e))\n\n return user_list\n return retrieve_cache\n return cacher","sub_path":"corehq/apps/reports/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":7169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"575905429","text":"import pygame, sys\nfrom pygame.locals import *\n\ndef draw_grid():\n screen.fill(BLACK)\n for y in range(height, h, height):#horizontal lines\n pygame.draw.line(screen, bg, (width, y), (w - width, y), 1)\n for x in range(width, w, width):#vertical lines\n pygame.draw.line(screen, bg, (x, height), (x, h - height), 1)\n\ndef draw_player():\n pygame.draw.rect(screen, [255, 255, 55], [left, top, width, height], 0)\n\n# Mostra a tela final com a pontução obtida. Representa o placar final.\ndef mostra_pontuacao_final(screen, pokemonCount):\n sys.stdout.write(\"Capturas: \" + str(pokemonCount) + \" Pokemons \")\n\npygame.init()\nclock = pygame.time.Clock()\nw = 80\nh = 80\nleft = 20\ntop = 40\nwidth = 20\nheight = 20\nYELLOW = (255, 255, 55)\nbranco = (255, 255, 255)\nBLUE = (0, 0, 255)\nBLACK = (0, 0, 0)\nbg = (255, 255, 255)\nx = 0\ny = 0\nisFirstPokemon = True\nbulbassauro = 1\ncharmander = 1\nsquirtle = 1\npikachu = 1\npokemonCount = 0\nscreen = pygame.display.set_mode((600, 600))\ngameExit = False\nmostra_pontuacao_final(screen, pokemonCount)\n\nwhile not gameExit:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameExit = True\n if isFirstPokemon and top == 40 and left == 20:\n pokemonCount += 1\n isFirstPokemon = False\n bulbassauro -= 1\n if event.type == KEYDOWN:\n if event.key == K_DOWN and top < 40:\n print(\"Orientação: S\");\n if bulbassauro > 0 and top == 20 and left == 20: # Bulbassauro\n pokemonCount += 1\n bulbassauro -= 1\n elif charmander > 0 and top == 20 and left == 40: # charmander\n pokemonCount += 1\n charmander -= 1\n top += 20\n if event.key == K_UP and top > 20:\n print(\"Orientação: N\");\n if squirtle > 0 and top == 40 and left == 40: # squirtle\n pokemonCount += 1\n squirtle -= 1\n elif pikachu > 0 and top == 40 and left == 20: # pikachu\n pokemonCount += 1\n pikachu -= 1\n top -= 20\n if event.key == K_RIGHT and left < 40:\n print(\"Orientação: E\");\n if charmander > 0 and top == 40 and left == 20: # charmander\n pokemonCount += 1\n charmander -= 1\n elif squirtle > 0 and top == 20 and left == 20: # squirtle\n pokemonCount += 1\n squirtle -= 1\n left += 20\n if event.key == K_LEFT and left > 20:\n print(\"Orientação: O\");\n if bulbassauro > 0 and top == 40 and left == 40: # Bulbassauro\n pokemonCount += 1\n bulbassauro -= 1\n elif pikachu > 0 and top == 20 and left == 40: # pikachu\n pokemonCount += 1\n pikachu -= 1\n left -= 20\n mostra_pontuacao_final(screen, pokemonCount)\n\n\n draw_grid()\n draw_player()\n pygame.display.flip()\n\npygame.quit()\n","sub_path":"desafio.py","file_name":"desafio.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"234824984","text":"from django.urls import include, path\nfrom .import views\napp_name = \"authentication\"\nurlpatterns = [\n path('', views.home, name='home'),\n path('index/', views.index, name='index'),\n path('register/',views.register,name='register'),\n path('login/',views.login_,name='login'),\n path('logout/',views.logout_,name='logout'),\n path('activate/<uidb64>/<token>/',views.activate, name='activate'),\n]","sub_path":"authentication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"489258783","text":"from django.conf.urls import include, url\r\nfrom django.contrib import admin\r\nfrom views import *\r\n\r\nurlpatterns = [\r\n url(r'1', swift),\r\n url(r'^put_container/$', put_container),\r\n url(r'^delete_container/$', delete_container),\r\n url(r'^delete_object/$', delete_object),\r\n url(r'^put_object/$', put_object),\r\n url(r'^get_object/$', get_object),\r\n url(r'^put_objectfile/$', put_objectfile),\r\n url(r'^login/$', login),\r\n url(r'^loin/$', loin),\r\n\r\n]","sub_path":"cloud/swiftapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279252968","text":"from django.utils import timezone\nfrom django.conf import settings\n\nfrom .. import ActionTest\n\nimport pytz\nfrom datetime import timedelta\n\nclass ViewAccount(ActionTest):\n def setUp(self):\n super(ViewAccount, self).setUp()\n self.data = {\n u'Sequence': 2,\n u'Mobile': u'233542751610',\n u'SessionId': u'aeb67d5e6e6b48409ad19a43eaa62b91',\n u'ServiceCode': u'711*78',\n u'Operator': u'MTN',\n u'Message': u'4',\n u'Type': u'Response',\n u'first_name': u'Ola',\n u'last_name': u'Olu',\n u'is_agent': u'True',\n }\n self._set_session_menu_option(4)\n\n # Create check-ins\n self.p1 = self._create_parking(self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b84'),\n self.agent, 'AW13916', pytz.timezone('UTC').localize(timezone.datetime(2017, 1, 1, 4, 59, 10)), number_of_slots=2)\n self.p2 = self._create_parking(self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b85'),\n self.agent, 'AW13917', pytz.timezone('UTC').localize(timezone.datetime(2017, 1, 1, 5, 5, 10)), number_of_slots=1)\n self.p3 = self._create_parking(self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b86'),\n self.agent, 'AW13918', pytz.timezone('UTC').localize(timezone.datetime(2017, 1, 1, 5, 12, 10)), number_of_slots=1)\n self.p4 = self._create_parking(self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b87'),\n self.agent, 'AW13919', pytz.timezone('UTC').localize(timezone.datetime(2017, 1, 1, 5, 18, 10)), number_of_slots=1)\n\n # Check out\n hours = 4\n\n cs = self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b94')\n cs.succeeded = True\n cs.save()\n\n self.p1.checkout_session = cs\n self.p1.checkout_agent = self.agent\n self.p1.checkout_time = self.p1.checkin_time + timedelta(hours=hours)\n self.p1.hours = self.p1.number_of_slots * hours\n self.p1.charge = self.p1.hours * settings.CHARGE_PER_HOUR\n self.p1.save()\n\n # Create supervisor session\n self.session = self._create_session(\n session_id='aeb67d5e6e6b48409ad19a43eaa62b99', phone_number='0542751615',\n actor_first_name='Titi', actor_last_name='Lope'\n )\n self._set_session_menu_option(4, session_id='aeb67d5e6e6b48409ad19a43eaa62b99')\n\n # Create supervisor\n self.supervisor = self._create_agent('Titi', 'Lope', zone=self.zone)\n\n def tearDown(self):\n self.p1.delete()\n self.p2.delete()\n self.p3.delete()\n self.p4.delete()\n self.session.delete()\n self.supervisor.delete()","sub_path":"core/tests/views/4_view_account/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266826142","text":"listing = [\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"ELEVATOR\",\n \"INTERCOM\",\n \"BALCONY\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"AP14630\",\n \"usableAreas\": [\n 104\n ],\n \"description\": \"Apartamento com 3 dormitórios em Cerqueira César, planta funcional e pé direito alto são alguns dos atrativos deste imóvel. São 2 dormitórios ( podendo reverter 1) sendo 1 suíte com varanda frente a Oscar freire e closet espaçoso , área de serviço e dependência completa de empregada. Apartamento todo reformado com material de primeira linha , na suíte master mármore de carrara.<br>Excelente endereço, próximo ao Hospital das Clínicas, Incor e Emílio Ribas.<br>Toda infraestrutura que cerca a região da Oscar Freire ( Metro, padarias, supermercados, colégios e ainda com a vantagem de fazer tudo a pé. Venha conhecer pessoalmente. -\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento com 3 dormitórios em Cerqueira César. Condomínio seguro e próximo ao metro Oscar Frei\",\n \"createdAt\": \"2018-08-03T23:42:07.220Z\",\n \"publisherId\": 82425,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"10790\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1142103609\",\n \"11928982000\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1039360272\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-19T18:40:36.992Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Cerqueira César\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"01426000\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Centro>Cerqueira Cesar\",\n \"zone\": \"Centro\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"AP14630\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [\n 167\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"286\",\n \"price\": \"900000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/29a845a6f1cf450c238a7ced0b9d00dd.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/21e945e489a5c2acd69f2e1727dfbdad.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/987109372827048c236470daa2b1f8dd.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4bc0aff90081f0024ad829693e79b321.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ab235a2513273aac96423524d57fcbdf.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a03f06c05bec20a1e3d8f9543aa34739.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/16b28b8d2d2ad5ed94ddd4c985aaec85.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5ed3c5a71e29ccc9fe3cc12fd839c587.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0d57f4976d5b15e139f4a35e33aaa85a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e9b8782ffe8107854c9a79f6e8cd5aa7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e18a05e205d2f4aecd24a660682fcda3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ee1d723eb87e3c7679d31af27193ee0e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5818690c78b3c60b9042e005cda20cd3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7ab9a247a408d2648e3962f72b13e94f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/29f98ba5504023b579968da6231dc629.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/eeb2bbce42154f43537b21562d8c813f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5d75cdda2617ec129c32198e3eede1c2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/13b568b27c3878081e7a791c9d50c6c4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/783f5e5e82f5ad84d9d3c2215b18176f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f320466eb228e673ee6675c48ea59e23.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4d24008878ae92c606eb21001f291024.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/243ce4aeececf47e0d3e387de02f34f7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/25dfa42146293cd3c485f292dd3b7193.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/53f8d5bdafd44fc3a634b1658e7c0bd9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9388cec49c89d0c4cb9a4f327d4dfa4e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b2c37ddb05219a6240e0fb5aef62a117.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c4c770d46d912090f5b556fec75745ab.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"82425\",\n \"name\": \"RE/MAX URBAN IMOVEIS\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01427-000\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"1725\",\n \"zone\": \"\",\n \"street\": \"Rua Estados Unidos\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Jardim América\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11928982000\",\n \"alternative\": \"\",\n \"primary\": \"1142103609\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3a3d07db80e7863be5f9a59ada3a850d.jpg\",\n \"licenseNumber\": \"32734-J-SP\",\n \"websiteUrl\": \"http://www.remaxunion.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T22:26:33Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1039360272\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 104m²\",\n \"href\": \"/imovel/apartamento-3-quartos-cerqueira-cesar-centro-sao-paulo-com-garagem-104m2-venda-RS900000-id-1039360272/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/82425/re-max-urban-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [],\n \"feedsId\": \"23\",\n \"usableAreas\": [\n 104\n ],\n \"description\": \"Apartamento de 104 m². Sala para 2 ambientes, varanda, 3 dormitórios (1 suíte), cozinha americana, 3 banheiros, área de serviço, ar condicionado instalado, dependência de empregada, entrada de serviço independente e esquadrias com redução de ruído. O imóvel possui 1 vaga de garagem. O condomínio disponibiliza porteiro em tempo parcial e portaria remota. Localizado numa região com diversos supermercados, restaurantes e serviços. Tem como opções de lazer próximas a Praça Benedito Calixto (1,1 km), o Cine Belas Artes (1,4 km), o Conjunto Nacional (1,6 km) e o Shopping Center 3 (1,7 km). Está próximo às grandes avenidas Rebouças (200 m) e Doutor Arnaldo (800 m), o que permite fácil acesso à estação de metrô Oscar Freire e a inúmeras a linhas de ônibus.\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento de 3 dormitórios na Oscar Freire\",\n \"createdAt\": \"2019-05-10T02:20:45.187Z\",\n \"publisherId\": 494334,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"41598\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1155550175\",\n \"1155550175\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"2444101798\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-20T13:46:01.765Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"PREMIUM\",\n \"externalId\": \"23\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"3140\",\n \"price\": \"1000000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"494334\",\n \"name\": \"Imóvel.aí\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01310-933\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"2444\",\n \"zone\": \"\",\n \"street\": \"Avenida Paulista\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Bela Vista\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"1155550175\",\n \"alternative\": \"\",\n \"primary\": \"1155550175\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/854fd0c248b944cbd6af65c9b382194e.jpg\",\n \"licenseNumber\": \"33226-J-SP\",\n \"websiteUrl\": \"\",\n \"leadEmails\": [],\n \"createdDate\": \"2019-01-14T11:54:45Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"2444101798\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 104m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-104m2-venda-RS1000000-id-2444101798/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/494334/imovel-ai/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"BALCONY\",\n \"GARAGE\",\n \"KITCHEN\",\n \"HEATING\",\n \"PLAYGROUND\",\n \"GOURMET_BALCONY\",\n \"GREEN_SPACE\"\n ],\n \"feedsId\": \"km196\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apto muito amplo, 3 minutos do Metrô Oscar Freire (200 m), pertinho do corredor de ônibus da Rebouças e ao lado do comércio da rua mais charmosa de São Paulo. Pertinho do Hospital das Clínicas, dos melhores restaurantes, bares, supermercados. Salão 2 ambientes amplos com ampla cozinha integrada, 3 quartos com armários embutidos sendo 1 suíte com sacada e closet + escritório, lavabo, banheiro social com blindex, área de serviço + dependência de empregada . 1 Vaga de Garagem. <br> <br> <br> - Características: Ar Condicionado, Área de Serviço, Móveis Planejados, Aquecimento Central Individual, Dependncia de Empregada, Varanda, <br> <br> - No Condomínio: Jardins, Portaria 24h, <br> <br> - Proximidades: Bares e Restaurantes, Escola, Farmácia, Shopping Center, Supermercado, Bancos, Centros M��dicos, Hospitais, Lojas, Metrô, Padaria, Parque ou praça, Universidade,\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento para Venda em São Paulo, Pinheiros, 3 dormitórios, 1 suíte, 3 banheiros, 1 vaga\",\n \"createdAt\": \"2019-05-28T15:55:35.629Z\",\n \"publisherId\": 118942,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"17754\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"11940127505\",\n \"11949812349\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"2446243258\",\n \"parkingSpaces\": [\n 1\n ],\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"km196\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"0\",\n \"price\": \"1020000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1460\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a046f651a665c96de94efd71c8e2c8e0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f30cd08a601a5f51cc75ef7693e3f620.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0b115ffdfc489e45419ef3fa5ebb940c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7bf7fc238e0b267edae94b0bb6a75a93.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b34a234aacc3c59c4a949a56eacb63e2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3f90cf710d9e12d98db185acc281fcf5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/73e735a0976f2d3a2b1acdbde083d6b3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a2936d0bb5fc2e9d4c4232d7b9907a52.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9fec9f3ad5291c65c5fbb89271e3a7ea.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/54714c57b60c90b084642b24972fdd92.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/02b547e8da7fb5d28811eda6fa9f4364.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/579ea4527c3f79e07f73dd554c50f3ca.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ab37ceffd3c73eeb58c82d917e4c554f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1bf4d11d8dd9149ba1cedd95c8d32719.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/cfb157460c908b67a3f26bda67a27a4a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/729aa0084c6473e6094abbca34fc0eb8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8ea8cf1eea6e150aa84547051f5a48f3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fc16a5e1fac59db893bbb250a44877ae.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8e68c1657aa3bdb712c5d57e9e3e93ec.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/99898a13a601437e8e8c33bd9539fa63.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/09d99dc05b1746a095892e1f9dfc4ab6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0fb2ba420ce424ba4e6ed4e0504f8758.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/772b7dcd18005731c877053147795a7d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9cc3e8c7bd4d7de1f9f9fdf44ca4c512.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0dce216ba195739952e2f12b1f565020.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/67708dc6d0b49a1d6eca9095a288dc68.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e901b96ff91d78b515d3a06edb828772.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/55efb006ecdead2954d24ad1d758ec56.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"118942\",\n \"name\": \"KATIA MANCEBO AVILA DE REZENDE\",\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11949812349\",\n \"alternative\": \"\",\n \"primary\": \"11940127505\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/30b925098345d433e770c48f0ec08cb9.jpg\",\n \"licenseNumber\": \"155998-F-SP\",\n \"websiteUrl\": \"http://katiamancebo.com.br/\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T18:49:36Z\",\n \"showAddress\": False\n },\n \"url\": {\n \"id\": \"2446243258\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1020000-id-2446243258/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/118942/katia-mancebo-avila-de-rezende/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"ELEVATOR\",\n \"INTERCOM\",\n \"CABLE_TV\",\n \"SECURITY_24_HOURS\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"AP0886\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apartamento em bom estado de conservação, localizado em rua muito procurada , metragem diferenciada com planta bem distribuída , ao lado dos Jardins, poucos minutos a pé da estação Oscar Freire do METRO e próximo a todas as facilidades do bairro,Pronto para morar. -\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento residencial à venda, Pinheiros, São Paulo.\",\n \"createdAt\": \"2018-06-19T05:08:38.837Z\",\n \"publisherId\": 96828,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"19565\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1130313184\",\n \"11997143339\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1037912351\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-03T02:23:11.134Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409011\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558913,\n \"lon\": -46.673112\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"AP0886\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"270\",\n \"price\": \"1020000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"STREET\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/db14d72d126b7f598b5ee61dc15a19f2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/55e7f34ca042f2674ccd52217df7f861.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d94e880eb4dedfeca91c26294dda6bec.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/871763a0f8263284958d6ad7bd975dc7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/98cc97fdecfa27e1620c636533da3d91.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4f3b0c01f46ce9a44885a1dfb1744a00.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/467fca06b5775d19fbac8318f2530fc6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/41c68d582a6a1b18dd6e0621f4ff5bcc.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e6c87d0907c24bd6d106144898f130d1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/589c3b3872ef700417ac9f0187ae9d29.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/27743f267fdcbb5a4d9ba66c9248b3b4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9e072a3066cff081b1323023e62f6f30.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b0e35519a470e38e804b9d169c616d2c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/cd92a4e8eda8876fe6a2e4573dd9c43f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/82e49fae352970c1a540d0697ee1cfd7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e66a81df410cc83d89aa0e1cdb37c3f0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e3d70fa4f631df6ca49e116f4561e19d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c3d855e5a656e4db1915e432dd69f1c2.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"96828\",\n \"name\": \"Simons Imóveis\",\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11997143339\",\n \"alternative\": \"\",\n \"primary\": \"1130313184\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d1770efa6cc8981e08ffb767d9a3057b.jpg\",\n \"licenseNumber\": \"61905-F-SP\",\n \"websiteUrl\": \"\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-29T17:40:52Z\",\n \"showAddress\": False\n },\n \"url\": {\n \"id\": \"1037912351\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1020000-id-1037912351/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/96828/simons-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"ELEVATOR\",\n \"INTERCOM\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"AP0600\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apartamento perto da Estação Oscar Freire da Linha Amarela (4) do Metrô, com 3 dormitórios mais closet, sendo uma suíte, 2 banheiros, cozinha, sala de estar e área de serviço, com 1 vaga de garagem. -\",\n \"listingType\": \"USED\",\n \"title\": \"Apto à venda com 3 dormitórios (1 suíte) , 125 m² por R$ 1.028.000,00 - perto Metro Oscar Freire, P\",\n \"createdAt\": \"2019-05-30T02:15:57.394Z\",\n \"publisherId\": 227418,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"23119\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1125323747\",\n \"11941343747\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"2446522291\",\n \"parkingSpaces\": [\n 1\n ],\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"AP0600\",\n \"bathrooms\": [\n 2\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"3200\",\n \"price\": \"1028000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"STREET\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/41bb7b0fe7033ec32e1435c4664d4bf0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3f9b8f9e6b02a72a5fc13c61c66a3720.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0a9ac30e23d4bc5f36f7c59f37616a59.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/953b50d4a3815ac98d5d3d4fa774725b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f21fb59cbf049da37a18d2c922dd9381.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fa714a0751a75c7c5a6ea35156562a8a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/90f69a3c17c769383556306a78dc06c9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d0ab1cd361c3d9338acbb5a14db420ac.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ecdbf4d7f0833b4b66c809567f197aad.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6f0c4d7b86ada68e3778c238e958af68.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7b8c2acc0cd6adbb8a7f75f58a7fac9f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c143a179d6a9182f02b981421a1a8c57.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/677058ca7a5d15917a467914786153b8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/71d8ff1b5e3e4ee6dc152ae1b74af2af.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"227418\",\n \"name\": \"MAIS PADRAO INTERMEDIACOES IMOBILIARIAS LTDA.\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"05372-040\",\n \"city\": \"SAO PAULO\",\n \"streetNumber\": \"322\",\n \"zone\": \"\",\n \"street\": \"JOSE FELIPE DA SILVA\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SAO PAULO\",\n \"neighborhood\": \"JD ESTER\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11941343747\",\n \"alternative\": \"\",\n \"primary\": \"1125323747\"\n },\n \"logoUrl\": \"\",\n \"licenseNumber\": \"031350-J-SP\",\n \"websiteUrl\": \"http://www.maispadraoimoveis.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T18:23:44Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"2446522291\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1028000-id-2446522291/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/227418/mais-padrao-intermediacoes-imobiliarias-ltda/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"AIR_CONDITIONING\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"SH34724\",\n \"usableAreas\": [\n 105\n ],\n \"description\": \"Apartamento à venda em Pinheiros com áreas amplas, planta funcional e pé direito alto são alguns dos atrativos deste imóvel. Cozinha com armários planejados integrada à sala permite convívio familiar; além disso, são 3 dormitórios sendo 1 suíte com varanda e ar condicionado, closet espaçoso, área de serviço e dependência completa de empregada. <br>Excelente endereço, próximo ao Hospital das Clínicas, a estação de metrô e à mais famosa área comercial da cidade onde encontra as suas grifes favoritas.\",\n \"listingType\": \"USED\",\n \"title\": \"Conforto em uma das ruas mais conhecidas do bairro\",\n \"createdAt\": \"2018-09-12T01:25:07.715Z\",\n \"publisherId\": 69027,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"11319\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1143692406\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1041038046\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-05-21T05:10:44.259Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"SH34724\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"deliveredAt\": \"1996-02-24T06:19:28.843Z\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"260\",\n \"price\": \"1040000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f687e3fa96d076ebd510ddd8b024a563.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5d245996e02804a0123db17c4de85db0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f9f63bda62b541a668a5f0d0780ce389.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bfff39ed08860f8003e8081c965b7802.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2e23a4158d1b12312d06dc2841278309.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8c5d77d943389147fdc225607f48ea55.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c2c6f1704f29011e292ba6186e5fb61b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/cf20fe93d03e5b284fb87ad1e005048c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f9c39496f501163a0e38b8be2393475e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d143b5ea206207b94f3732ed267cc938.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7483d7c0c09a389c0edcb6d0755ab678.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bec6c29562049d8d85bff585a72e5e3b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/150bd10125e6c7506c714e70a8f6557e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/11d31ac2de2ba6e43a6023bd575ecf57.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/560f624e1449bee10b615f689447a252.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"69027\",\n \"name\": \"Sh Prime Imóveis\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"05019-010\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"794\",\n \"zone\": \"\",\n \"street\": \"Avenida Professor Alfonso Bovero\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Perdizes\"\n },\n \"phone\": {\n \"leadsPhone\": \"1143692406\",\n \"mobile\": None,\n \"alternative\": \"\",\n \"primary\": \"1143692406\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1992bd1b8345b300735cffeacfd90459.jpg\",\n \"licenseNumber\": \"25618-J-SP\",\n \"websiteUrl\": \"http://www.shprime.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T17:00:22Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1041038046\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 105m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-105m2-venda-RS1040000-id-1041038046/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/69027/sh-prime-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"PARTY_HALL\",\n \"SECURITY_24_HOURS\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"143840\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Living para 2 ambientes com lavabo, banheiro social reformado, 1 ampla suíte com varanda e closet + 2 dormitórios com armários, cozinha integrada toda planejada e repleta de armários, área de serviço, quarto de empregada. Em ótimo estado, espaçoso. Próximo ao Metrô Oscar Freire.\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento espaçoso reformado com 125m² de área útil. Próximo ao Metrô Oscar Freire\",\n \"createdAt\": \"2018-08-10T19:06:21.521Z\",\n \"publisherId\": 58736,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"75\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1130812251\",\n \"11998988044\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1039603986\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-08T02:26:52.483Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"143840\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"260\",\n \"price\": \"1050000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a9d0b38427f611808fd58ef814ae6590.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b71334bc78bf00adf14dbd388b5035b9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3652b9771cfa10a9c29bce478802aa2d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5a5d2954d9d0599e30e124fd219023e2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/114c8f3f781ec931e387bec7df1f37b6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ae09f1233a406b4e06648cc597c67f39.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/39d52c1f0229fa06039bf12ad55af821.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bfbe06bb06a72b6ae590795a00b56712.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/37aca7efaf401b25c037cb6a7b6a319d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5c0c95e96204a471558918b47655bbf8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9fdda00f8eee9e7c37ec4258b93972ff.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f39dd2de77d37f69d2b440a799d76ac3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/19f47e4131b17218ff2a740d4aa03cd5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0d71c3218ead7545b5075140b6d1e724.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/973f2a15445df995065fbd208982f690.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/00614a69bf8b6bbedd43e789fde0c894.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/54d0551efd34b66b320022c6ece7e7ab.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c4760c6326bc115527f749b06a1cbefd.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fb535c66062e32348449fec7dd76042a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/eb92ecd7931fc57f30c594d670ed8d58.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0ac8f482aca92a6aa3aea3347ca78b7e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/39814664a62ade3238694cdc348b2a7b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e38864b655b5203bd4c399331de5a3f4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/07eb83a48e3ceba9a6a6189a42083733.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1078bf12a696b74d262f203a1b66dc37.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fd7b5d40f65673859b139693c818636e.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"58736\",\n \"name\": \"A2 Jardins Negocios Imobiliários LTDA\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"05409-010\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"49\",\n \"zone\": \"\",\n \"street\": \"Rua Oscar Freire\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Pinheiros\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11998988044\",\n \"alternative\": \"\",\n \"primary\": \"1130812251\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2b9968eb59dfcfbdfc447a9fbea86130.jpg\",\n \"licenseNumber\": \"19948-J-SP\",\n \"websiteUrl\": \"http://www.a2jardins.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T22:38:43Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1039603986\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1050000-id-1039603986/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/58736/a2-jardins-negocios-imobiliarios-ltda/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"NEAR_SCHOOL\",\n \"PARTY_HALL\",\n \"SECURITY_24_HOURS\",\n \"BALCONY\",\n \"NEAR_ACCESS_ROADS\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"BR658\",\n \"usableAreas\": [\n 105\n ],\n \"description\": \"Excelente Apartamento em Pinheiros totalmente reformado. <br>Amplo, com tres dormitórios sendo uma suíte com armários, sala para dois ambientes. <br>Cozinha americana moderna. <br>Apartamento aconchegante. <br>Região nobre, rua com comércios de Grifes, restaurantes de diferentes culinárias. <br>Localização espetacular.\",\n \"listingType\": \"USED\",\n \"title\": \"Lindo Apartamento em Pinheiros!\",\n \"createdAt\": \"2018-05-27T18:03:17.552Z\",\n \"publisherId\": 227935,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"6911\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"11961936337\",\n \"11999469687\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1037278828\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-05-25T09:02:10.236Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"BR658\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [],\n \"logoUrl\": \"\",\n \"deliveredAt\": \"1996-02-24T04:02:23.414Z\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"2600\",\n \"price\": \"1050000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0e99159ea96e79a20f4c954c6fb86149.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e7aae2872e8a46d8627deeab48a97731.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/774c1e4c0615b4bde985c84d5e1f94bb.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5a86e6034b857277092ba1903e22fea7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ad5877f5f1990f1298f25aaa291b01eb.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/396c4f8b17175ab3c25cb850b9c95e16.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bb4f1783d6a3048fb4ee5ea05fdcd1f5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e50d4f766e210610e6559e37caa4c04c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6c18aacb49748f2cc7c1a7205c036f94.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b17384529a091af184074841e0778def.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d6d9b86851f71a8bfe4e9cddeca17a56.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/16bb384c42a5466636b0828ab0d66269.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e075bfc7491963be39d6ad41e7ef657b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/12d962dd04310bf3326a27883fbe1a64.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/99061dead6eaeeb3bd26d357a11be402.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/edb2e3f6328eb3d5c2e340d08e16f0d2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6da3a62d665223ab98aeed875bed54ae.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6edad5104738142b3d396fc8f2f62e74.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/83c1866e995583d695a39115d80c7359.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1350730485b7150f3b7075b5fef52976.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0782d2d312c42a8ded805e119b1382f6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c11f36307a122a1093bbce2c5bdeb83b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a8159ed1f7924affe5416001525f03a0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/23f370d0334565df12f5633d47151a43.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"227935\",\n \"name\": \"ELIZA BR7 IMÓVEIS\",\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11999469687\",\n \"alternative\": \"\",\n \"primary\": \"11961936337\"\n },\n \"logoUrl\": \"\",\n \"licenseNumber\": \"\",\n \"websiteUrl\": \"http://www.br7imoveis.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T23:16:59Z\",\n \"showAddress\": False\n },\n \"url\": {\n \"id\": \"1037278828\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 105m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-105m2-venda-RS1050000-id-1037278828/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/227935/eliza-br7-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"WATCHMAN\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"44984\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apartamento Próximo ao Metrô Oscar Freire - REF. 44984<br><br>Apto muito amplo, sala para 2 ambientes, cozinha, 3 quartos sendo 1 suíte e com Closet, área de serviço, lavabo, cozinha, 01 vaga de garagem.<br>Próximo ao metrô Oscar Freire (200 m), pertinho do corredor de ônibus da Rebouças e ao lado do comércio da rua mais charmosa de São Paulo. Pertinho do Hospital das Clínicas, dos melhores restaurantes, bares, supermercados.\",\n \"listingType\": \"USED\",\n \"title\": \"SAO PAULO - Padrão - PINHEIROS\",\n \"createdAt\": \"2018-10-19T06:10:14.860Z\",\n \"publisherId\": 35775,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"8139\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1131056300\",\n \"1131056300\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1042511632\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-08T01:13:36.425Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"44984\",\n \"bathrooms\": [\n 1\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"2650\",\n \"price\": \"1050000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"NEIGHBORHOOD\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/10937cb2ea7e2b1ac525917a5ba4362a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6efdf9b1f0863da0da6a3bc87cc1547e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/377ab75269b96b5ef8a2fe52c7b08856.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/81f49f783c1fab45d8e2566348f87f82.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9ec0d2798f928a59a4f0b6b03d49987c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/762ee48c059812ccd89f2c1a9ecc26d4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5801c83eecac98ad0de864fd437ac837.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/14d7d79a9d67b9a8b05529fc398a6c3d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c0ea30159378ae688f786d9a6cca39d5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5e16e25d5d564de0a1db45c75ea87c35.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9f9131ab1b585304a96b60cd0a16c65f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c8c669e196a3da7af7f11df7c149e110.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9b8769f4cd4c01ac7caf2607465af863.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/38d5d2c77549792693805181824c2aa1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/16ff5488b0133a5713f31e298f2266f0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4a3de9aad7b65ac102e1f721e0e5c71b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/666d3bb1638727b74a0d08004ea26781.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7c532f5d74c0e0adb94e35be7a0260d8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7b289dd63abf8f2472ea5b91373830f0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d5bb411998003850882e4673e63d34f4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8a62ec726cdbb44d1f243aa3bfee599b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fa394c9a70e9489761ec758cfa5a878d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ed4a1cd294ec4ba25c07ea8bda312a66.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/be1324fe2054777399927834b8be3671.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1513ca6c7bbd042f36112db67f6a18ac.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/62f6f53eb676227559000e604183bef9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2295350e922b99ab847dc26a6d42571e.jpg\"\n ],\n \"videos\": [\n \"https://www.youtube.com/watch?v=ZxzdCDZqroQ\"\n ]\n },\n \"publisher\": {\n \"id\": \"35775\",\n \"name\": \"M. Lara Negocios Imobiliarios Ltda.\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01002-001\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"185\",\n \"zone\": \"\",\n \"street\": \"Rua Álvares Penteado\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Centro\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"1131056300\",\n \"alternative\": \"\",\n \"primary\": \"1131056300\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e1f634ed8c9b97de0b51bd314ec41e47.jpg\",\n \"licenseNumber\": \"20816-J-SP\",\n \"websiteUrl\": \"http://www.marcelolara.com.br/\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T20:48:40Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1042511632\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1050000-id-1042511632/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/35775/m-lara-negocios-imobiliarios-ltda/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"INTERCOM\",\n \"POOL\",\n \"PLAYGROUND\",\n \"PARTY_HALL\",\n \"GARDEN\"\n ],\n \"feedsId\": \"KA4551\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apartamento 185 m² , 03 dormitórios,sendo 01 suíte, living para 02 ambientes,lavabo,areá de serviço e 01 vaga de garagem. <br>Será um prazer encontrar o seu imóvel! Todas as informações publicadas neste anúncio, incluindo preço, metragem do imóvel e valores são aproximadas e não garantidas, devendo ser confirmadas conforme o interesse do cliente. Somos uma imobiliária dinâmica que conta com a experiência de profissionais sedimentados no mercado há mais de 15 anos. Nosso foco está sempre direcionado ao cliente e nos resultados a serem alcançados, atuando com ética e responsabilidade.\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento a venda\",\n \"createdAt\": \"2018-09-28T07:31:54.913Z\",\n \"publisherId\": 97354,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"16476\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1145631800\",\n \"11938081800\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1041737287\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-05-15T23:01:11.260Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"KA4551\",\n \"bathrooms\": [\n 2\n ],\n \"totalAreas\": [\n 150\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"286\",\n \"price\": \"1060000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"STREET\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bbee539bb1ce08980aa5e8849d8fd39b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/788428bc30c203edfcde9efafd94917e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/62c6d37f5f6f599d20b5ebd98d1e8952.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/cb56e1a241970c9ac34b50cc75c96674.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/332f15699b1232889e6d07a31a0b84de.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a97ec2ef053b554780c846cde587d016.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/052fb6dfe4f87a21822f5f16e543bbee.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2f10e0c9d4e2e8bb23b65598d53cf7d6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6cef8261f0f67560d8d0f2739ae7acf9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2bd21765cf2c3a5715086818379815f8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c2ce5165a1015ddc9db63bd3748856ac.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/eb556e5f71684ad1ec1fe5915568b557.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c5979a536d7e408099157714497991a9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fb87c5d4fa917777773d2cf7cbdd109a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6eacce88253a2deeca524b957ba56ee2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/98d9c343aabfb519d7a44358ada8e7f1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/46467dcee4dfb5a810eb3e2f035c273f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e3a09078dd313b39836257c5c3f34eca.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4ba42d37ee7396ad07a45a339f0bd7f2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3bb06aeef813ec815e217abde5172f26.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/448a9c1251a2d926130378dd4d40d540.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1f7a0551827b7e1f0348e01051e81b43.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/be9ca3ad17e6c1d795702ff3f03a2a59.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0f379672a9623234a6ec40e748040821.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d62dc7030c29b0c60090f5d81e4b1175.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"97354\",\n \"name\": \"KASACOR IMOVEIS\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01240-001\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"1380\",\n \"zone\": \"\",\n \"street\": \"Av. Angelica\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Higienópolis\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11938081800\",\n \"alternative\": \"\",\n \"primary\": \"1145631800\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6c789e5c88aaf6bc12f717f2357e0039.jpg\",\n \"licenseNumber\": \"27037-J-SP\",\n \"websiteUrl\": \"http://www.kasacorimoveis.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T17:54:48Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1041737287\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1060000-id-1041737287/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/97354/kasacor-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"ELEVATOR\",\n \"GARDEN\",\n \"PARTY_HALL\",\n \"PLAYGROUND\",\n \"POOL\",\n \"BALCONY\",\n \"NEAR_ACCESS_ROADS\",\n \"NEAR_SHOPPING_CENTER\",\n \"GATED_COMMUNITY\",\n \"INTERCOM\",\n \"SECURITY_24_HOURS\",\n \"KITCHEN\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"O apartamento de 125 metros <br>Apartamento para a venda 125 m² é de frente, sendo 3 quartos com 1 suite,<br>cozinha balcão, lavabo, 1 vaga com armários e piso de madeira.<br>Áreas comuns:<br>- Jardim<br>- Piscina<br>- Playground <br>- Salão de festas<br>Localização:<br>- Próximo a Fundação Faculdade de Medicina<br>- Próximo ao Hospital Jardins <br>- Próximo a Estação Pinheiros de metro\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento para venda com 125 metros quadrados e 3 quartos em Pinheiros - São Paulo - SP.\",\n \"createdAt\": \"2018-09-22T23:56:03.195Z\",\n \"publisherId\": 136127,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"VIVAREAL\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"11981182245\",\n \"11981182245\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1041554133\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-03-28T21:05:29.122Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"0408\",\n \"bathrooms\": [\n 2\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"285\",\n \"price\": \"1100000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0732967f53018eb04e9f18f8216e883f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/378fba8984029f488e5e7fcedc3f7fcf.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d0fa2fba76b8aecd7bdf8130edb4d5fa.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c185e1c02c6d37bc2bdd5665868b4afc.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4555576c2980dbd8f5d15cfe2f3c1177.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/463943481565baeefc28b5fb124726d7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0dcacb01c7b8a4cbec39e92ff26fde3a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/649550dd6e0d98953165720cc77e7c1e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e88851a7cd2f2cf406bb81d857574bb5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e846960fae743c995519fcf1cd3c71e8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2772d2e61088ca3ac99dd682bbd28421.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f5a933a036cf168a412003d08ef907bf.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/25cf82b9971d994487e92d0f0f3da875.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0dbf72f9dc53055f048d56e246a80161.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2ba123e84f6df359d0b54926eabea117.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d47a4c239af8f0135f26e8f8ec55a724.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/09daf5f7124604cd69d333df02926f1e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/831a37d5c92f038275825b220b17798f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a93130ed46257df6e210c7d9a820825e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d76bfbd12b1dd4ac5da8ac19001b8ff0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ba25727ce85706400f7f926d25043ea1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ff2439a7276e536f275266a1632982a2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/73c021da98c14a47164e0f5026a63280.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a964f85f00fc56f7a5a4957087b927af.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/597253533f8c4cb2951815b6ce581891.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"136127\",\n \"name\": \"Elaine Pedroso de Oliveira\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"04286-000\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"1379\",\n \"zone\": \"\",\n \"street\": \"Rua Coronel Francisco Inácio\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Vila Moinho Velho\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11981182245\",\n \"alternative\": \"\",\n \"primary\": \"11981182245\"\n },\n \"logoUrl\": \"\",\n \"licenseNumber\": \"133870-F-SP\",\n \"websiteUrl\": \"\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T19:22:50Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1041554133\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1100000-id-1041554133/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/136127/elaine-pedroso-de-oliveira/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [],\n \"feedsId\": \"PE7352\",\n \"usableAreas\": [\n 100\n ],\n \"description\": \"As informações contidas neste anúncio, tais como valor do imóvel, do condomínio e IPTU, poderão sofrer alterações.\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento, Pinheiros - São Paulo\",\n \"createdAt\": \"2018-09-06T05:28:31.952Z\",\n \"publisherId\": 51664,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"15460\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1138233545\",\n \"1138233545\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1040842685\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-07T22:46:39.645Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULL<Sao Paulo>Zona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"PE7352\",\n \"bathrooms\": [\n 2\n ],\n \"totalAreas\": [\n 120\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"370\",\n \"price\": \"1200000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"STREET\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/475ffc182149abcc9692c3cf34e63c4b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/44830d9a2344f74a6b6f49188b0fe1d7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/19c63b4d5279b1777a0888b69515e420.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a025e8e7a8315d8ae0515160568be317.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/af61906757a23bd7e9ed460e29390fb4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2d3a547bf3bddafe776f0450b06887cd.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8adeae7f8ea7c29aa3e90430d36e3871.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6ef76e9c490bedc7c532ab2b7bdda70b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/900cc1ee7337512003c7e9b2726a992d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/30e83bdc3f5e1c29f7ea18e24ee32d55.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/22cbb81501f9e9ab7312943fdfa358cb.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bd80e202e71200e25b28f5b3c1a0d9a6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a2d745f51b869692796ca5724e0286d2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4800b08bfd579fb7be4ddb7b1ca9f4c1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/78009fd1bcf53c4771580fbab1f7dd34.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a602ef3e52d7e27322de62d6e98caf35.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a1cf516b6d146ef4cb5f43456ced926d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8a44791aff9f2e79d0fac5e8657a77c6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4c83efd130a4ffd7750b34b8d3eaeb08.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5512eb81bfaa0c30ec6bc2456f38ad8f.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"51664\",\n \"name\": \"JAIME ADMINISTRACAO DE BENS E CONDOMINIOS LTDA\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01243-001\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"51664\",\n \"zone\": \"\",\n \"street\": \"Rua Sergipe\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Consolação\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"1138233545\",\n \"alternative\": \"\",\n \"primary\": \"1138233545\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1db36cde5c31c37c2e1265b00d67e73f.jpg\",\n \"licenseNumber\": \"015908-J-SP\",\n \"websiteUrl\": \"http://www.jaime.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T17:06:14Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1040842685\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 100m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-100m2-venda-RS1200000-id-1040842685/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/51664/jaime-administracao-de-bens-e-condominios-ltda/\",\n \"rel\": \"\"\n }\n }\n }\n ]","sub_path":"app/services/crawler_data_territorio/mocks/listing_filtered.py","file_name":"listing_filtered.py","file_ext":"py","file_size_in_byte":95791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"476277067","text":"import datetime\nimport calendar\nimport wx\nimport wx.grid\n\n\ndef calendarText():\n \"\"\"example return:\n\n January 2016\n Mo Tu We Th Fr Sa Su\n 1 2 3\n 4 5 6 7 8 9 10\n 11 12 13 14 15 16 17\n 18 19 20 21 22 23 24\n 25 26 27 28 29 30 31\n \"\"\"\n\n now = datetime.datetime.now()\n x=\"%d\" %now.year\n y=\"%d\" %now.month\n\n yy=int(x)\n mm=int(y)\n return (calendar.month(yy,mm))\n\ndef calendarTextToListForGrid(text):\n \"\"\"example return:\n [' January 2016',\n ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'],\n [' ', ' ', ' ', ' ', ' 1', ' 2', ' 3'],\n [' 4', ' 5', ' 6', ' 7', ' 8', ' 9', ' 10'],\n ['11', ' 12', ' 13', ' 14', ' 15', ' 16', ' 17'],\n ['18', ' 19', ' 20', ' 21', ' 22', ' 23', ' 24'],\n ['25', ' 26', ' 27', ' 28', ' 29', ' 30', ' 31'],\n ['']]\n\n \"\"\"\n array = text.split(\"\\n\")\n output = []\n output.append(array[0])\n output.append(array[1].split(\" \"))\n for i in range(2, len(array)):\n listHelp = []\n string = array[i]\n listHelp.append(string[0:2])\n for j in range(2, len(string), 3):\n listHelp.append(string[j:j+3])\n output.append(listHelp)\n return output\n\n# uncomment these to test code:\n#test calendarTextToListForGrid(text)\n#print calendarTextToListForGrid(calendarText())\n\n\n\ncalendarList = calendarTextToListForGrid(calendarText())\nclass SimpleCalendarGrid(wx.grid.Grid):\n def __init__(self, parent):\n wx.grid.Grid.__init__(self, parent, -1)\n\n self.CreateGrid(5, 7)\n for j in range(7):\n self.SetColLabelValue(j, calendarList[1][j])\n for i in range(5):\n week = \"week \"+str(i+1)\n self.SetRowLabelValue(i, week)\n try:\n for j in range(7):\n cellValue = calendarList[i+2][j]\n self.SetCellValue(i, j, cellValue)\n except IndexError:\n for j in range(7):\n cellValue = calendarList[i+1][j]\n self.SetCellValue(i, j, cellValue)\n\nclass TestFrame(wx.Frame):\n def __init__(self, parent):\n frameTitle = calendarList[0]\n testFrame = wx.Frame.__init__(self, parent, -1, frameTitle, size=(650, 160), style=wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.CAPTION)\n\n #load application's icon\n self.icon = wx.Icon('mediaFilesPackage/calendar.ico', wx.BITMAP_TYPE_ICO)\n self.SetIcon(self.icon)\n\n grid = SimpleCalendarGrid(self)\n\n\nappCalendar = wx.App()\nframe = TestFrame(None)\nframe.Show(True)\nappCalendar.MainLoop()\n","sub_path":"codeFilesPackage/calendarSimpleText.pyw","file_name":"calendarSimpleText.pyw","file_ext":"pyw","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"294719027","text":"# 使下列代码循环执行,按e键退出\nwhile True:\n season = input(\"请输入:\")\n if season == \"春\":\n print(\"1月2月3月\")\n elif season == \"夏\":\n print(\"4月5月6月\")\n elif season == \"秋\":\n print(\"7月8月9月\")\n elif season == \"冬\":\n print(\"10月11月12月\")\n if input(\"输入e键退出:\") == \"e\":\n break # 退出循环体\n","sub_path":"study/1905/month01/code/Stage1/day03/exercise08.py","file_name":"exercise08.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302339313","text":"\"\"\"\n\n选择排序\n 选择排序(Selection-sort)是一种简单直观的排序算法。它的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,\n 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。\n\n 算法描述\n n个记录的直接选择排序可经过n-1趟直接选择排序得到有序结果。具体算法描述如下:\n\n 初始状态:无序区为R[1..n],有序区为空;\n 第i趟排序(i=1,2,3…n-1)开始时,当前有序区和无序区分别为R[1..i-1]和R(i..n)。该趟排序从当前无序区中-选出关键字最小的记录 R[k],将它与无序区的第1个记录R交换,使R[1..i]和R[i+1..n)分别变为记录个数增加1个的新有序区和记录个数减少1个的新无序区;\n n-1趟结束,数组有序化了。\n\n 算法分析\n 表现最稳定的排序算法之一,因为无论什么数据进去都是O(n2)的时间复杂度,所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。\n 理论上讲,选择排序可能也是平时排序一般人想到的最多的排序方法了吧。\n\n\"\"\"\n\n\nclass Solution:\n def select_sort(self, nums: list) -> list:\n length = len(nums)\n if length == 0:\n return nums\n\n variant_index = 0\n while variant_index < length:\n min_value_index = variant_index\n\n for i in range(variant_index, length):\n if nums[i] < nums[min_value_index]:\n min_value_index = i\n\n if min_value_index != variant_index:\n temp = nums[min_value_index]\n nums[min_value_index] = nums[variant_index]\n nums[variant_index] = temp\n\n variant_index += 1\n\n return nums\n\n\nif __name__ == '__main__':\n array = [1, 323, 4, 1, 5, 6, 8, 9, 113]\n solution = Solution()\n print(solution.select_sort(array))\n","sub_path":"python/sort/select_sort.py","file_name":"select_sort.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"562949970","text":"import h5py\nfrom dlgo.encoders import oneplane\nfrom dlgo.networks import large\nfrom dlgo.agent import pg\nfrom dlgo.agent import naive\nfrom dlgo import goboard_slow as goboard\nfrom dlgo import gotypes\nfrom dlgo import scoring\nfrom dlgo.rl import experience\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Activation\n\nimport time\n\nboard_size = (19,19)\n\nencoder = oneplane.OnePlaneEncoder(board_size)\nmodel = Sequential()\nfor layer in large.layers(encoder.shape()):\n model.add(layer)\nmodel.add(Dense(encoder.num_points()))\nmodel.add(Activation('softmax'))\n\n\nagent1 = pg.PolicyAgent(model, encoder)\nagent2 = pg.PolicyAgent(model, encoder)\ncollector1 = experience.ExperienceCollector()\ncollector2 = experience.ExperienceCollector()\nagent1.set_collector(collector1)\nagent2.set_collector(collector2)\n\nwith h5py.File('/home/bart/output_file1.h5', 'w') as outf:\n agent1.serialize(outf)\nwith h5py.File('/home/bart/output_file2.h5', 'w') as outf:\n agent2.serialize(outf)\n\n\na = []\n\nCOLS = 'ABCDEFGHJKLMNOPQRST'\nSTONE_TO_CHAR = {\nNone: ' . ',\ngotypes.Player.black: ' x ',\ngotypes.Player.white: ' o ',\n}\n\n\ndef print_move(player, move):\n if move.is_pass:\n move_str = 'passes'\n elif move.is_resign:\n move_str = 'resigns'\n else:\n move_str = '%s%d' % (COLS[move.point.col - 1], move.point.row)\n print('%s %s' % (player, move_str))\n \ndef print_board(board):\n for row in range(board.num_rows, 0, -1):\n bump = \" \" if row <= 9 else \"\"\n line = []\n for col in range(1, board.num_cols + 1):\n stone = board.get(gotypes.Point(row=row, col=col))\n line.append(STONE_TO_CHAR[stone])\n print('%s%d %s' % (bump, row, ''.join(line)))\n print(' ' + ' '.join(COLS[:board.num_cols]))\n\ndef main():\n board_size = 19\n game = goboard.GameState.new_game(board_size)\n bots = {\n #gotypes.Player.black: naive.RandomBot(),\n gotypes.Player.black: agent1,\n gotypes.Player.white: agent2,\n \n }\n while not game.is_over():\n time.sleep(0.3) # <1>\n\n print(chr(27) + \"[2J\") # <2>\n print_board(game.board)\n bot_move = bots[game.next_player].select_move(game)\n print_move(game.next_player, bot_move)\n game = game.apply_move(bot_move)\n \n game_result = scoring.compute_game_result(game)\n print(\"and the winner is:\",game_result.winner)\n a.append(game_result.winner)\n return game_result.winner\n\n\nnum_games = 1\n\nfor i in range(num_games):\n collector1.begin_episode()\n collector2.begin_episode()\n \n game_record = main()\n\n if a[0] == 'Player.black':\n collector1.complete_episode(reward=1)\n collector2.complete_episode(reward=-1)\n else:\n collector2.complete_episode(reward=1)\n collector1.complete_episode(reward=-1)\n\nexp = experience.combine_experience([collector1,collector2])\n\nwith h5py.File('/home/bart/experience_file.h5', 'w') as experience_outf:\n exp.serialize(experience_outf)\n\n\n\n","sub_path":"ReinforcementLearning/rl/go.py","file_name":"go.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366509605","text":"from ScanQRcodePyGame import getQRCode\nfrom AttendanceSheet import Sheet\nfrom GroupList import GroupList\nfrom QRList import QRList\nimport pifacecad\nimport time\nimport sys\n\nWAITING, SELECTING_GROUP, ASK_FOR_DOWNLOAD, ATTENDANCE_SCANNING, PRESENTATION_SCANNING = range(0, 5)\nstate = WAITING\nselectedGroup = 0\n\ndef update_pin(event):\n\tglobal state\n\tglobal selectedGroup\n\tglobal groupList\n\tglobal qrList\n\tglobal sheet\n\tprint(\"main pressed \"+str(state)+\" \"+str(event.pin_num))\n\tif state == ASK_FOR_DOWNLOAD and event.pin_num == 0:\n\t\tevent.chip.lcd.clear()\n\t\tevent.chip.lcd.write(\"Downloading...\")\n\t\tgroupList.download()\n\t\tqrList.download()\n\t\tstate = SELECTING_GROUP\n\t\tupdate_group_selection()\n\t\treturn\n\tif state == ASK_FOR_DOWNLOAD and event.pin_num == 1:\n\t\tgroupList.load()\n\t\tqrList.load()\n\t\tstate = SELECTING_GROUP\n\t\tupdate_group_selection()\n\t\treturn\n\n\tif state == SELECTING_GROUP and event.pin_num == 0:\n\t\tselectedGroup = (selectedGroup+1)%len(groupList.getGroups())\n\t\tupdate_group_selection()\n\t\treturn\n\tif state == SELECTING_GROUP and event.pin_num == 1:\n\t\tevent.chip.lcd.clear()\n\t\tevent.chip.lcd.write(str(groupList.getGroups()[selectedGroup])+\"!\")\n\t\ttime.sleep(2)\n\t\tstop_scanning()\n\t\treturn\n\n\tif state == WAITING and event.pin_num == 0:\n\t\tprint(\"att scan\")\n\t\tstate = ATTENDANCE_SCANNING\n\t\thandle_scanning()\n\t\treturn\n\tif state == WAITING and event.pin_num == 1:\n\t\tprint(\"pres scan\")\n\t\tstate = PRESENTATION_SCANNING\n\t\thandle_scanning()\n\t\treturn\n\tif state == WAITING and event.pin_num == 2:\n\t\tevent.chip.lcd.clear()\n\t\tevent.chip.lcd.set_cursor(0,0)\n\t\tevent.chip.lcd.write(\"Uploading...\")\n\t\tif sheet.upload():\n\t\t\tevent.chip.lcd.clear()\n\t\t\tevent.chip.lcd.write(\"Upload successful\")\n\t\telse:\n\t\t\tevent.chip.lcd.clear()\n\t\t\tevent.chip.lcd.write(\"Upload failed\")\n\t\ttime.sleep(2)\n\t\tstop_scanning()\n\t\treturn\n\n\tif state == WAITING and event.pin_num == 3:\n\t\tsheet.save()\n\t\texit()\n\ndef update_group_selection():\n\tcad.lcd.clear()\n\tcad.lcd.write(str(groupList.getGroups()[selectedGroup])+\"?\")\n\tcad.lcd.set_cursor(0,1)\n\tcad.lcd.write(\"0:change 1:select\")\t\n\ndef handle_scanning():\n\tglobal state\n\tglobal sheet\n\tif state == ATTENDANCE_SCANNING:\n\t\twhile True:\n\t\t\tqrCode = getQRCode(\"attend.\");\n\t\t\tif qrCode == \"-1\":\n\t\t\t\tstop_scanning()\n\t\t\t\tbreak\n\t\t\tif qrCode is not \"0\":\n\t\t\t\tcad.lcd.clear()\n\t\t\t\tcad.lcd.set_cursor(0,0)\n\t\t\t\tif is_qr_valid(qrCode):\n\t\t\t\t\tcad.lcd.write(\"QR code valid\")\n\t\t\t\t\tprint(qrCode + \" is valid\")\n\t\t\t\t\tsheet.addAttendance(str(qrCode).split(\";\")[1])\n\t\t\t\telse:\n\t\t\t\t\tcad.lcd.write(\"QR code invalid\")\n\t\t\t\t\tprint(qrCode +\" is invalid\")\n\t\t\t\ttime.sleep(2)\n\n\tif state == PRESENTATION_SCANNING:\n\t\twhile True:\n\t\t\tqrCode = getQRCode(\"pres.\");\n\t\t\tif qrCode == \"-1\":\n\t\t\t\tstop_scanning()\n\t\t\t\tbreak\n\t\t\tif qrCode is not \"0\":\n\t\t\t\tcad.lcd.clear()\n\t\t\t\tcad.lcd.set_cursor(0,0)\n\t\t\t\tif is_qr_valid(qrCode):\n\t\t\t\t\tcad.lcd.write(\"QR code valid\")\n\t\t\t\t\tprint(qrCode + \" is valid\")\n\t\t\t\t\tsheet.addPresentation(str(qrCode).split(\";\")[1])\n\t\t\t\telse:\n\t\t\t\t\tcad.lcd.write(\"QR code invalid\")\n\t\t\t\t\tprint(qrCode +\" is invalid\")\n\t\t\t\ttime.sleep(2)\n\t\t\t\tstop_scanning()\n\t\t\t\tbreak\n\n\ndef stop_scanning():\n\tglobal state\n\tprint(\"Scanning stopped\")\n\tcad.lcd.clear()\n\tcad.lcd.set_cursor(0,0)\n\tcad.lcd.write(\"0:att. 1:pres.\")\n\tcad.lcd.set_cursor(0,1)\n\tcad.lcd.write(\"2:upload\")\n\tstate = WAITING\n\ndef is_qr_valid(qr):\n\treturn qr.split(\";\")[2] == groupList.getGroups()[selectedGroup] and qrList.is_qr_valid(qr)\n\ncad = pifacecad.PiFaceCAD()\ncad.lcd.backlight_on()\n\nlistener = pifacecad.SwitchEventListener(chip=cad)\nfor i in range(8):\n\tlistener.register(i, pifacecad.IODIR_FALLING_EDGE, update_pin)\nlistener.activate()\n\n#groupList = getGroupList()\ncad.lcd.write(\"Download files?\")\ncad.lcd.set_cursor(0,1)\ncad.lcd.write(\"0:yes 1:no\")\ncad.lcd.set_cursor(0,0)\nstate = ASK_FOR_DOWNLOAD\n\nsheet = Sheet()\ngroupList = GroupList()\nqrList = QRList()","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"152219812","text":"# -*- coding: utf-8 -*-\nimport os,sys\nimport pandas as pd\nimport numpy as np\n#import pandas.io.data as web\nimport time\n#from datetime import*\n#可以循环获得你想要的股票代码的行情数据,只是近3年的数据\ndef yahoodatasettlement():\n code_list = []\n for root, dirs, files in os.walk('./stockdata/yahoo/'):# 注意:这里请填写数据文件在您电脑中的路径\n if files:\n for f in files:\n if '.csv' in f:\n code_list.append(f.split('.csv')[0])\n for code in code_list:\n filename='./stockdata/yahoo/'+code+'.csv'\n stock_data = pd.read_csv(filename, parse_dates=['Date'])\n stock_data.sort('Date', inplace=True)\n stock_data['p_change']=(stock_data['Adj Close']/stock_data['Adj Close'].shift(1)-1)*100\n stock_data.columns = ['date','open','high','low','close','volume','adj_close','p_change']\n stock_data.to_csv(filename,index=False)\n return\n \nyahoodatasettlement()\n","sub_path":"jiaoben/yahoodatasettle.py","file_name":"yahoodatasettle.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68470977","text":"parent = [('parent', 'manjur', 'sohel'), ('parent', 'manjur', 'tufel'),\n ('parent', 'manjur', 'jerin'), ('parent', 'manjur', 'najnin'),\n ('parent', 'tufel', 'rifat'), ('parent', 'jerin', 'raaj')]\n\nmale = [('male', 'manjur'), ('male', 'sohel'),\n ('male', 'tufel'), ('male', 'rifat'), ('male', 'raaj')]\n\nfemale = [('female', 'jerin'), ('female', 'najnin')]\n\ndef findBr(): #brother\n X = str(input(\"Sibling:\\n\"))\n print('Brother:', end='\\n')\n bl = True\n for i in range(len(parent)):\n if (parent[i][0] == 'parent') & (parent[i][2] == X):\n for j in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][1] == parent[i][1]) & (parent[i][2]!=parent[j][2]):\n for k in range(len(male)):\n if(male[k][0]=='male') & (male[k][1]==parent[j][2]):\n print(male[k][1])\n bl = False\n if (bl):\n print('N\\A')\n\ndef findSr(): #sister\n X = str(input(\"Sibling:\\n\"))\n print('Sister:', end='\\n')\n bl = True\n for i in range(len(parent)):\n if (parent[i][0] == 'parent') & (parent[i][2] == X):\n for j in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][1] == parent[i][1]) & (parent[i][2]!=parent[j][2]):\n for k in range(len(female)):\n if(female[k][0]=='female') & (female[k][1]==parent[j][2]):\n print(female[k][1])\n bl = False\n if(bl):\n print('N\\A')\n\ndef findUl(): #uncle\n X = str(input(\"Nephew:\\n\"))\n print('Uncle:', end='\\n')\n bl = True\n for i in range(len(parent)):\n if(parent[i][0]=='parent') & (parent[i][2]==X):#parent[i][1] parent\n for j in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][2]==parent[i][1]):#parent[j][1] grandparent\n for k in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][1] == parent[k][1]) & (parent[i][1]!=parent[k][2]): #parent[k][2] parent's sibling\n for l in range(len(male)):\n if(male[l][0]=='male') & (male[l][1]==parent[k][2]): #male[l][1] uncle\n print(male[l][1])\n bl = False\n if(bl):\n print('N/A')\n\ndef findUt(): #aunt\n X = str(input(\"Nephew:\\n\"))\n print('Aunt:', end='\\n')\n bl = True\n for i in range(len(parent)):\n if(parent[i][0]=='parent') & (parent[i][2]==X):#parent[i][1] parent\n for j in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][2]==parent[i][1]):#parent[j][1] grandparent\n for k in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][1] == parent[k][1]) & (parent[i][1]!=parent[k][2]): #parent[k][2] parent's sibling\n for l in range(len(female)):\n if(female[l][0]=='female') & (female[l][1]==parent[k][2]): #female[l][1] aunt\n print(female[l][1])\n bl = False\n if(bl):\n print('N/A')\n\ndef Print():\n print('1: Brother, 2: Sister, 3: Uncle, 4: Aunt, Other character: Exit')\n x = input(\"press a character:\\n\")\n return x\n\nx = Print()\nwhile (1):\n if x == '1':\n findBr() #brother\n elif x == '2':\n findSr() #sister\n elif x == '3':\n findUl() #uncle\n elif x == '4':\n findUt() #aunt\n else:\n break\n x = Print()\n","sub_path":"AI/Python/Assignment_01_Q2.py","file_name":"Assignment_01_Q2.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"218721494","text":"from dictionary import *\n\n\ndef encrypt(message):\n cipher = ''\n for letter in message:\n if letter != ' ':\n cipher += code[letter] + ' '\n else:\n cipher += ' '\n return cipher\n\n\ndef decrypt(message):\n message += ' '\n\n decipher = ''\n citext = ''\n for letter in message:\n if letter != ' ':\n i = 0\n citext += letter\n else:\n i += 1\n if i == 2:\n decipher += ' '\n else:\n decipher += list(code.keys()\n )[list(code.values()).index(citext)]\n citext = ''\n return decipher\n","sub_path":"py/Morse/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"620366721","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nurlpatterns = patterns('ffsq.views',\n url(r'^$', 'index', name='home'),\n url(r'^search/$', 'search', name='search'),\n url(r'^ranking/$', 'ranking', name='ranking'),\n url(r'^how_to_use/$', 'how_to_use', name='how_to_use'),\n url(r'^search_parks/$', 'search_parks', name='search_parks'),\n url(r'^parks/(?P<park_id>\\d+)/$', 'park_detail', name='park_detail'),\n url(r'^parks/(?P<park_id>\\d+)/review/$', 'park_review', name=\"park_review\"),\n url(r'^reviews/(?P<review_id>\\d+)/$', 'review_edit', name=\"review_edit\"),\n url(r'^login$', 'login', name='login'),\n)\n\nurlpatterns += patterns('',\n url(r'^logout/$', 'django.contrib.auth.views.logout', {\n 'template_name': 'ffsq/logged_out.html'\n }, name='logout'),\n url(r'', include('social_auth.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"ffsq/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"301117048","text":"\"\"\"alex_project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', 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: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import re_path\nfrom .views import PostListView, PostDetailView, CategorieListView\n\nurlpatterns = [\n re_path(r'^blog/home/(?P<page>\\d+)$', PostListView.as_view(),\n name='blog_home_page'),\n re_path(r'^blog/categorie/(?P<categorie>\\w+)/(?P<page>\\d+)$',\n CategorieListView.as_view(), name='blog_custom_page'),\n re_path(\n r'^blog/post/(?P<slug>.+)-(?P<pk>\\d+)$',\n PostDetailView.as_view(),\n name='detail_post'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"559961265","text":"# -*- coding:utf-8 -*-\n\n# #\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (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, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110- 1301, USA.\n#\n# \n# <pep8 compliant>\n\n# Copyright (c) 2004-2011 Bruno Postle <bruno@postle.net>.\n\n# ----------------------------------------------------------\n# Author: Bruno Postle <bruno@postle.net>\n# Python translation: Stephen Leger (s-leger)\n#\n# ----------------------------------------------------------\n\n'''\nUrb::Boundary - A division within a quadrilateral space\n\nModels a division within an Urb::Quad object and child quads that share this boundary\n\nA boundary is a division of a quad or the edge of the root quad, it is always a\nstraight line. It has various leafnode quads attached to it. The boundary\nobject is a list of references to these leafnodes in no particular order.\n\n'''\n\n\nfrom math import pi\nfrom .math import distance_2d, angle_2d\n\n\nclass Boundary(list):\n\n def __init__(self):\n list.__init__(self)\n\n\n def add_edges(self, quad, id_edge):\n '''Attach a quad to this boundary, indicate which edge of the quad (0,1,2 or 3) is attached:\n boundary->Add_Edge ($quad, 2);\n '''\n self.append({quad: quad, id_edge: id_edge})\n\n @property\n def _id(self):\n '''Query the Id of the quad of which this boundary is a division\n :return: boundary_id\n '''\n if len(self) < 1:\n return\n ed = self[0]\n return ed['quad'].boundary_id(ed['id_edge'])\n\n @property\n def length_total(self):\n '''Query the total length of this boundary\n :return: length_total\n '''\n quad_parent = self[0]['quad'].by_id(self._id)\n return distance_2d(quad_parent.coordinate_a, quad_parent.coordinate_b)\n\n @property\n def is_valid(self):\n '''Check some internal consistency\n :return: boolean validate_id\n '''\n _id = self._id\n for item in self:\n if _id != item['quad'].boundary_id(item['id_edge']):\n return False\n return True\n\n def _find_edges(self, quad_a, quad_b):\n edge_a, edge_b = None, None\n for item in self:\n if item['quad'] is quad_a:\n edge_a = item['id_edge']\n if item['quad'] is quad_b:\n edge_b = item['id_edge']\n return edge_a, edge_b\n\n def overlap(self, quad_a, quad_b):\n '''Given two quads, find out how much they overlap on this boundary, if at all\n :param quad_a:\n :param quad_b:\n :return: distance = boundary->Overlap (quad_a, quad_b)\n '''\n edge_a, edge_b = self._find_edges(quad_a, quad_b)\n if edge_a is None or edge_b is None:\n return 0.0\n\n if not self._id in {'a', 'b', 'c', 'd'}:\n return 0.0\n\n _id = self._id\n\n if quad_a.boundary_id(edge_a) != _id or \\\n quad_b.boundary_id(edge_b) != _id:\n return 0.0\n\n length_a = quad_a.length(edge_a)\n length_b = quad_b.length(edge_b)\n ca0, ca1 = quad_a.coordinate(edge_a), quad_a.coordinate(edge_a + 1)\n cb0, cb1 = quad_b.coordinate(edge_b), quad_b.coordinate(edge_b + 1)\n\n d = max(\n distance_2d(ca0, cb0),\n distance_2d(ca0, cb1),\n distance_2d(ca1, cb0),\n distance_2d(ca1, cb1)\n )\n\n if d <= length_b:\n return length_a\n\n if d <= length_a:\n return length_b\n\n return length_a + length_b - d\n\n def coordinates(self, quad_a, quad_b):\n '''Query coordinates of the segment shared by two overlapping quads\n :param quad_a:\n :param quad_b:\n :return: xy1 xy2 or None\n '''\n edge_a, edge_b = self._find_edges(quad_a, quad_b)\n if edge_a is None or edge_b is None:\n return\n _id = self._id\n if quad_a.boundary_id(edge_a) != _id or \\\n quad_b.boundary_id(edge_b) != _id:\n return\n if self.overlap(quad_a, quad_b) <= 0:\n return\n length_a = quad_a.length(edge_a)\n length_b = quad_b.length(edge_b)\n ca0, ca1 = quad_a.coordinate(edge_a), quad_a.coordinate(edge_a + 1)\n cb0, cb1 = quad_b.coordinate(edge_b), quad_b.coordinate(edge_b + 1)\n\n length = distance_2d(ca0, cb0)\n ea, eb = edge_a + 1, edge_b + 1\n qa, qb = quad_a, quad_b\n\n d = distance_2d(ca0, cb1)\n if d > length:\n length = d\n ea, eb = edge_a + 1, edge_b\n\n d = distance_2d(ca1, cb0)\n if d > length:\n length = d\n ea, eb = edge_a, edge_b + 1\n\n d = distance_2d(ca1, cb1)\n if d > length:\n length = d\n ea, eb = edge_a, edge_b\n\n # edge_a is contained entirely within edge_b\n if length < length_b:\n ea, eb = edge_a, edge_a + 1\n qb = quad_a\n\n # edge_a is contained entirely within edge_a\n if length < length_a:\n ea, eb = edge_b, edge_b + 1\n qa = quad_b\n\n # otherwise edge_a and edge_b partially overlap so we want the two inner points\n c0, c1 = qa.coordiates(ea), qb.coordinates(eb)\n rad_quads = angle_2d(quad_a.centroid, quad_b.centroid)\n rad_edge = angle_2d(c1, c0)\n rad = rad_edge - rad_quads\n if rad > pi:\n return c0, c1\n else:\n return c1, c0\n\n def bearing(self, quad_a, quad_b):\n '''Query perpendicular bearing between centre quad and boundary with other quad,\n i.e. if this boundary is a wall, which direction does it face (east = 0.0, north = 1.57):\n :param quad_a:\n :param quad_b:\n :return: radians\n '''\n coor_a, coor_b = self.coordinates(quad_a, quad_b)\n centroid = quad_a.centroid\n angle_a = angle_2d(centroid, coor_a)\n angle_b = angle_2d(centroid, coor_b)\n\n angle = (angle_a - angle_b) % (2 * pi)\n # TODO: check for the % method\n angle_wall = angle_2d(coor_a, coor_b) % (2 * pi)\n if angle < pi / 2:\n angle_wall = angle_2d(coor_b, coor_a) % (2 * pi)\n return angle_wall\n\n def middle(self, quad_a, quad_b):\n '''Query the mid point of an edge half way up\n :param quad_a:\n :param quad_b:\n :return: tuple coor 3d\n '''\n coor_a, coor_b = self.coordinates(quad_a, quad_b)\n return 0.5 * (coor_a[0] + coor_b[0]), 0.5 * (coor_a[1] + coor_b[1]), quad_a.elevation + 0.5 * quad_a.height\n\n @property\n def pairs(self):\n '''Get a list of all pairs of quads that have a segment that is part of this boundary\n :return: list of pairs of quads\n '''\n if self._id is None or not not self._id in {'a', 'b', 'c', 'd'}:\n return []\n pairs = []\n for index_a, item_a in enumerate(self[:-1]):\n quad_a = item_a['quad']\n for item_b in self[index_a + 1:]:\n quad_b = item_b['quad']\n if self.overlap(quad_a, quad_b) > 0:\n pairs.append([quad_a, quad_b])\n return pairs\n\n @property\n def pairs_by_length(self):\n '''Get a list of all pairs as with Pairs(), but sorted by length of shared segment\n :return: list of pairs of quads\n '''\n pairs = self.pairs\n pairs.sort(key=lambda x: self.overlap(x[0], x[1]))\n return pairs\n","sub_path":"urb/boundary.py","file_name":"boundary.py","file_ext":"py","file_size_in_byte":7992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"319204591","text":"import numpy as np\nimport time\nimport matplotlib.pyplot as plt\nimport warnings\nimport sys\n\n\n#Imports relacionados con Machine Learning, métricas,preprocesado de datos..clasificadores.\nfrom sklearn.preprocessing import normalize\nfrom sklearn.model_selection import cross_val_score, cross_val_predict, ShuffleSplit, train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import zero_one_loss\nfrom sklearn.ensemble import AdaBoostClassifier\n\n#Datos de la base de datos para realizar la clasificación\ndatos = np.genfromtxt('muestra_datos.csv', delimiter = ';')\ndigitos = normalize(datos[:, :-1])\netiquetas = datos[:, -1]\n\nx_train, x_eval, y_train, y_eval = train_test_split(digitos, etiquetas, test_size=0.3,\n train_size=0.7,\n random_state=1982)\nn_estimators = 400\n\n#Instancias de los clasificadores y entrenamiento\nclf_stump = DecisionTreeClassifier(max_depth=1, min_samples_leaf=1) #Stump significa tocón\nclf_stump.fit(x_train, y_train)\nclf_stump_err = 1-clf_stump.score(x_eval, y_eval)\nprint('Error del tocón'+str(clf_stump_err))\nclf_tree = DecisionTreeClassifier(max_depth=9, min_samples_leaf=1)\nclf_tree.fit(x_train, y_train)\nclf_tree_err = 1-clf_tree.score(x_eval, y_eval)\nprint('Error del árbol de decisión'+str(clf_tree_err))\nclf_adaBoostdis = AdaBoostClassifier(base_estimator=clf_stump, learning_rate=1, n_estimators=n_estimators, algorithm=\"SAMME\") #AdaBoost discreto\nclf_adaBoostreal = AdaBoostClassifier(base_estimator=clf_stump, learning_rate=1, n_estimators=n_estimators, algorithm=\"SAMME.R\")\nclf_adaBoostdis.fit(x_train, y_train)\nclf_adaBoostreal.fit(x_train, y_train)\n\n#plots\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot([1, n_estimators], [clf_stump_err] * 2, 'k-',\n label='Decision stump Error')\nax.plot([1, n_estimators], [clf_tree_err] * 2, 'k--',\n label='Decision Tree Error')\n\n#Errores del AdaBoost real y discreto para los valores de entrenamiento y de testeo\nada_discrete_err = np.zeros((n_estimators,))\nfor i, y_pred in enumerate(clf_adaBoostdis.staged_predict(x_eval)):\n ada_discrete_err[i] = zero_one_loss(y_pred, y_eval)\n#print('AdaBdiscrete eval'+str(ada_discrete_err))\nada_discrete_err_train = np.zeros((n_estimators,))\nfor i, y_pred in enumerate(clf_adaBoostdis.staged_predict(x_train)):\n ada_discrete_err_train[i] = zero_one_loss(y_pred, y_train)\n#print(('AdaBdiscrete train'+str(ada_discrete_err_train)))\nada_real_err = np.zeros((n_estimators,))\nfor i, y_pred in enumerate(clf_adaBoostreal.staged_predict(x_eval)):\n ada_real_err[i] = zero_one_loss(y_pred, y_eval)\n#print('AdaBreal eval'+str(ada_real_err))\nada_real_err_train = np.zeros((n_estimators,))\nfor i, y_pred in enumerate(clf_adaBoostreal.staged_predict(x_train)):\n ada_real_err_train[i] = zero_one_loss(y_pred, y_train)\n\n#print('AdaBreal train'+str(ada_real_err_train))\nax.plot(np.arange(n_estimators) + 1, ada_discrete_err,\n label='Discrete AdaBoost Test Error',\n color='red')\nax.plot(np.arange(n_estimators) + 1, ada_discrete_err_train,\n label='Discrete AdaBoost Train Error',\n color='blue')\nax.plot(np.arange(n_estimators) + 1, ada_real_err,\n label='Real AdaBoost Test Error',\n color='orange')\nax.plot(np.arange(n_estimators) + 1, ada_real_err_train,\n label='Real AdaBoost Train Error',\n color='green')\n\nax.set_ylim((0.0, 1))\nax.set_xlabel('n_estimators')\nax.set_ylabel('error rate')\n\nleg = ax.legend(loc='upper right', fancybox=True)\nleg.get_frame().set_alpha(0.7)\n\nplt.show()\n","sub_path":"libs/pruebasboost.py","file_name":"pruebasboost.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"267870542","text":"import os\nimport ROOT\nimport json\nimport sys\nfrom collections import OrderedDict\nimport numpy as np\nimport math\n\nplotdir = \"/eos/user/t/tihsu/DataAnalysis/Charge_Flip_woSB_nanoaod/\"\ntag = 'combine'\nori_detail = False\n# Read Files\nworkdir = os.getcwd()\ntargetdir = os.path.join(\"/eos/user/t/tihsu/output_ntuple_2/\")\nAllfile = os.listdir(targetdir)\n\n# Read json Files\njsonfile = open(os.path.join(workdir+\"/../samples_2017_nanoaod.json\"))\nsamplesList = json.load(jsonfile,encoding = 'utf-8', object_pairs_hook=OrderedDict).items()\njsonfile.close()\n\n# Basic Setting\npt_region = np.array(( 20.0, 50.0, 100., 300.))\neta_region = np.array((0.0, 0.8, 1.479, 2.4))\npt_bins = len(pt_region)-1\neta_bins = len(eta_region)-1\nchannel = ['MC_os','MC_ss','data_os','data_ss','back_os','back_ss']\nNumber = dict()\nPij = dict()\nVij = dict()\nP_fit = dict()\n\nN_MC = 0.\nN_data = 0.\n\nfor ch in channel:\n Number[ch] = [[[[0. for i in range(eta_bins)] for j in range(pt_bins)] for ii in range(eta_bins)] for jj in range(pt_bins)]\n\n#skip_list = [\"MC13TeV_2017_QCDEM_120to170_2.root\", \"MC13TeV_2017_QCDEM_120to170_1.root\", \"MC13TeV_2017_QCDEM_80to120_1.root\",\"MC13TeV_2017_QCDEM_80to120_3.root\",\"MC13TeV_2017_QCDEM_120to170_4.root\",\"MC13TeV_2017_WJets_mlm_49.root\"]\nskip_list = []\n# Run Through All files\nfor s ,desc in samplesList:\n weight = desc[0]*41.5*1000\n for ff in Allfile:\n if s in ff:\n try:\n inf = ROOT.TFile.Open(os.path.join(targetdir+ff))\n try:\n t = inf.Get(\"TreeInput\")\n except:\n t = inf.Get(\"Chunks/\"+ff+\"/TreeInput\")\n n_entry = t.GetEntries()\n if \"MC\" in s and (desc[3] == \"DY\" or desc[3]==\"t#bar{t}\"):\n print(\"Signal: \"+ff)\n t.GetEntry(0)\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n Number['MC_ss'][i][j][ii][jj] += t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]*weight\n Number['MC_os'][i][j][ii][jj] += t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]*weight\n if (math.isnan(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):\n print(\"******* \"+str(jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i)+str(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]))\n N_MC += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight + float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight\n elif \"Data\" in s:\n print(\"Data: \"+ff)\n t.GetEntry(0)\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n Number['data_ss'][i][j][ii][jj] += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])\n Number['data_os'][i][j][ii][jj] += float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])\n N_data += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]) + float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])\n if (math.isnan(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):\n print(\"******* \"+str(jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i)+str(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]))\n elif(ff not in skip_list):\n print(\"Background: \"+ff)\n t.GetEntry(0)\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n #if (math.isnan(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):continue\n #if (math.isnan(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):continue\n Number['back_ss'][i][j][ii][jj] += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight\n Number['back_os'][i][j][ii][jj] += float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight\n if (math.isnan(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):\n print(\"******* \"+str(jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i)+str(float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])))\n N_MC += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight + float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight\n inf.Close()\n except:\n print(ff+\"-->Trigger exception\")\nprint(N_data)\nprint(N_MC)\nnormscale = 1.\n\"\"\"for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n N_MC += Number['MC_ss'][i][j][ii][jj]\n N_MC += Number['MC_os'][i][j][ii][jj]\n N_data += Number['data_ss'][i][j][ii][jj]\n N_data += Number['data_os'][i][j][ii][jj]\n N_MC += Number['back_ss'][i][j][ii][jj]\n N_MC += Number['back_os'][i][j][ii][jj]\n\"\"\"\nprint(N_data)\nprint(N_MC)\nnormscale = N_data/N_MC\nprint(normscale)\nnormscale = 1.\nfor i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n Number['MC_ss'][i][j][ii][jj]*=normscale\n Number['MC_os'][i][j][ii][jj]*=normscale\n Number['data_ss'][i][j][ii][jj]-=Number['back_ss'][i][j][ii][jj]*normscale\n Number['data_os'][i][j][ii][jj]-=Number['back_os'][i][j][ii][jj]*normscale\n\n# Combine symmetric result\nfor h in Number:\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n if(ii>i or jj>j):\n Number[h][ii][jj][i][j]+=Number[h][i][j][ii][jj]\n Number[h][i][j][ii][jj] = 0\n\n# Combine 100-200GeV with 200 GeV up\nif(tag=='combine' and ori_detail):\n pt_region = np.array(( 20.0, 50.0, 100.0, 300.))\n eta_region = np.array((0.0,0.8,1.479, 2.4))\n pt_bins = len(pt_region)-1\n eta_bins = len(eta_region)-1\n for h in Number:\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n if(i==pt_bins-1 and ii==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i+1][j][ii+1][jj]\n Number[h][i+1][j][ii+1][jj] = 0\n if(i==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i+1][j][ii][jj]\n Number[h][i+1][j][ii][jj] = 0\n if(ii==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i][j][ii+1][jj]\n Number[h][i][j][ii+1][jj] = 0\nif(tag=='combine' and ori_detail):\n pt_region = np.array(( 20.0, 50.0, 100.0, 300.))\n eta_region = np.array((0.0, 1.479, 2.4))\n pt_bins = len(pt_region)-1\n eta_bins = len(eta_region)-1\n for h in Number:\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n if(i==pt_bins-1 and ii==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i+1][j][ii+1][jj]\n Number[h][i+1][j][ii+1][jj] = 0\n if(i==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i+1][j][ii][jj]\n Number[h][i+1][j][ii][jj] = 0\n if(ii==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i][j][ii+1][jj]\n Number[h][i][j][ii+1][jj] = 0\n\nP_fit['data'] = [[0. for i in range(eta_bins)] for j in range(pt_bins)]\nP_fit['MC'] = [[0. for i in range(eta_bins)] for j in range(pt_bins)]\nSF = [[0. for i in range(eta_bins)] for j in range(pt_bins)]\n\n# Calculate Probability\nDvMC = ['data','MC']\nfor h in DvMC:\n Pij[h] = [[[[0. for i in range(eta_bins)] for j in range(pt_bins)] for ii in range(eta_bins)] for jj in range(pt_bins)]\n Vij[h] = [[[[0. for i in range(eta_bins)] for j in range(pt_bins)] for ii in range(eta_bins)] for jj in range(pt_bins)]\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n# print(\"l1_pt = \" + str(pt_region[i]) + \" l1_eta = \" + str(eta_region[j]) + \" l2_pt = \" + str(pt_region[ii]) + \" l2_eta = \" + str(eta_region[jj]))\n# print('ss : '+str(Number[h+'_ss'][i][j][ii][jj])+' os : '+str(Number[h+'_os'][i][j][ii][jj]))\n if(1):\n N_ss = Number[h+'_ss'][i][j][ii][jj]\n N_T = N_ss + Number[h+'_os'][i][j][ii][jj] \n if(N_T>0. and N_ss>0.):\n Pij[h][i][j][ii][jj] = N_ss/N_T\n Vij[h][i][j][ii][jj] = N_ss/(N_T**2)+(N_ss**2)/(N_T**3)-2*(N_ss**1.5)/(N_T**2.5)\n# Vij[h][i][j][ii][jj] = N_ss/(N_T**2)+(N_ss**2)/(N_T**3) # without consider covariance \n else:\n print(\"raise Number counting error\")\n pass\nfor i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n print(str(i)+str(j)+str(ii)+str(jj)+\" : data: \"+str(Pij['data'][i][j][ii][jj])+\" MC: \"+str(Pij['MC'][i][j][ii][jj]))\n print(str(Number['data_os'][i][j][ii][jj])+\" \"+str(Number['MC_os'][i][j][ii][jj]))\n\n\n# Use chi2 to fit\n \nfor h in DvMC:\n print(Pij[h])\n gMinuit = ROOT.TMinuit(pt_bins*eta_bins)\n\n def fcn(npar, gin, f, par, iflag):\n chi2 = 0. \n Likelihood = 0.\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n if (not Vij[h][i][j][ii][jj]==0.) and Number[h+'_os'][i][j][ii][jj]>200. and Number[h+'_ss'][i][j][ii][jj]>1.:\n P1 = par[i*eta_bins+j]\n P2 = par[ii*eta_bins+jj]\n eP = P1+P2-2.*P1*P2\n N = int(round(Number[h+'_os'][i][j][ii][jj]+Number[h+'_ss'][i][j][ii][jj]))\n Nsc = int(round(Number[h+'_ss'][i][j][ii][jj]))\n chi2 += ((Pij[h][i][j][ii][jj]-(P1+P2-2.*P1*P2))**2)/(Vij[h][i][j][ii][jj])\n Likelihood += Nsc*np.math.log((N*(eP)))-N*(eP)-np.math.log(np.math.factorial(Nsc))\n\n f[0] = -1.*Likelihood\n\n gMinuit.SetFCN(fcn)\n for i in range(pt_bins):\n for j in range(eta_bins):\n init_val = 0.0001\n if Number[h+'_os'][i][j][i][j]>5000:\n init_val = 1.-(1.-Pij[h][i][j][i][j])**0.5\n print(init_val)\n gMinuit.DefineParameter(i*eta_bins+j,\"P\"+str(i)+str(j),init_val,0.00000001,0.,0.1) \n gMinuit.Command(\"Minuit2\")\n# r = gMinuit.save()\n# Result Plot\n w = 600;\n he = 600;\n c = ROOT.TCanvas(h+'c','c',10,10,w,he)\n ROOT.gStyle.SetOptStat(\"kFALSE\")\n ROOT.gStyle.SetPaintTextFormat(\".2e\");\n ROOT.gStyle.SetPalette(69);\n ROOT.gStyle.SetCanvasBorderSize(0)\n ROOT.gStyle.SetCanvasBorderMode(0)\n ROOT.gStyle.SetFrameBorderMode(0)\n c.SetRightMargin(0.15);\n c.SetTopMargin(0.15);\n \n# r.correlationHist(h).Draw('colz')\n c.Update()\n c.SaveAs(plotdir+h+'_CorrelationHist_SB_combine_Cov.png')\n \n h_chargeflip = ROOT.TH2F(h+\"_CFRate\",\";P_{T}[GeV] ; |\\eta|};\",pt_bins,pt_region,eta_bins,eta_region)\n\n result = [[0. for j in range(eta_bins)] for i in range(pt_bins)]\n error = [[0. for j in range(eta_bins)] for i in range(pt_bins)]\n\n for i in range(pt_bins):\n for j in range(eta_bins):\n result = ROOT.double(0.)\n error = ROOT.double(0.)\n gMinuit.GetParameter(i*eta_bins+j,result,error)\n P_fit[h][i][j] = result\n h_chargeflip.SetBinContent(i+1,j+1,result)\n h_chargeflip.SetBinError(i+1,j+1,error)\n if h=='data':\n h_data = h_chargeflip.Clone()\n else:\n h_MC = h_chargeflip.Clone()\n c.SetLogx()\n c.SetLogz()\n h_chargeflip.Draw('COLZTEXT e')\n c.Update()\n c.SaveAs(plotdir+h+'_CFRate_MLE_SB_'+tag+'_Cov.png')\n c.SaveAs(plotdir+h+'_CFRate_MLE_SB_'+tag+'_Cov.pdf')\n\nFout = ROOT.TFile.Open(\"ChargeFlipProbability_2017_MLE.root\",\"Recreate\")\nh_data.Write()\nh_MC.Write()\nFout.Close()\n\nc.SetLogz(0) \nh_SF = h_data.Clone()\nh_SF.Divide(h_SF,h_MC)\nh_SF.Draw('COLZTEXT e')\nc.Update()\nc.SaveAs(plotdir+'CFRate_MLE_MDRatio_SB_'+tag+'_Cov.png')\nc.SaveAs(plotdir+'CFRate_MLE_MDRatio_SB_'+tag+'_Cov.pdf')\n\n\nfor i in range(pt_bins):\n for j in range(eta_bins):\n SF[i][j] = P_fit['data'][i][j]/P_fit['MC'][i][j]\n\nprint(P_fit['MC'])\nprint(SF)\n\ngenfile = os.path.join(workdir+\"/../analysis_2017_chargeflip_genmatching/genCFrate.root\")\nfin = ROOT.TFile.Open(genfile)\nh_gen = fin.Get(\"genCFRate\")\nh_MCvgen = h_gen.Clone()\nh_MCvgen.Divide(h_MCvgen,h_MC)\nh_MCvgen.Draw('COLZTEXT e')\nc.Update()\nc.SaveAs(plotdir+'CFRate_MLE_genvMC_'+tag+'_Cov.png')\nfin.Close()\n","sub_path":"TopAnalysis/ChargeFlipStudy/ChargeFlipRate.py","file_name":"ChargeFlipRate.py","file_ext":"py","file_size_in_byte":12754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446913495","text":" # -*- coding: utf-8 -*-\nimport sys\nimport math\nimport time\nimport mymodule\nfrom tkinter import *\n\ndef read_tsp(filename):\n tsp=mymodule.smart.produce(filename)\n dist_x=tsp[0]\n dist_y=tsp[1]\n N=len(dist_x)\n buff=[]\n for i in range(N):\n buff.append((dist_x[i],dist_y[i]))\n return buff\n\n# 距離の計算\ndef distance(p1, p2):\n dx = p1[0] - p2[0]\n dy = p1[1] - p2[1]\n return math.sqrt(dx * dx + dy * dy)\n\n# 経路の距離を求める\ndef path_length(path):\n global distance_table\n n = 0\n i = 1\n for i in range(1, len(path)):\n n += distance(path[i - 1], path[i])\n n += distance(path[0], path[-1])\n return n\n\n# 分割する方向を決定する\ndef divide_direction(buff):\n x1 = min(map(lambda x: x[0], buff))\n y1 = min(map(lambda x: x[1], buff))\n x2 = max(map(lambda x: x[0], buff))\n y2 = max(map(lambda x: x[1], buff))\n return x2 - x1 > y2 - y1\n\n# 分割する\ndef divide(buff, axis):\n print (len(buff))\n buff.sort(key=lambda x:x[axis])\n n = len(buff) // 2\n buff1 = buff[0:(n+1)]\n buff2 = buff[n:]\n return buff[n], buff1, buff2\n\n# 差分を計算する\ndef differ(p, c, q):\n return distance(p, c) + distance(c, q) - distance(p, q)\n\n# 共有点を探す\ndef search(x, buff):\n for i in range(len(buff)):\n if buff[i] == x:\n if i == 0: return len(buff) - 1, i, i + 1\n if i == len(buff) - 1: return i - 1, i, 0\n return i - 1, i, i + 1\n\n# 挿入するための新しい経路を作る\ndef make_new_path(buff, c, succ):\n path = []\n i = c + succ\n while True:\n if i < 0: i = len(buff) - 1\n elif i >= len(buff): i = 0\n if i == c: break\n path.append(buff[i])\n i += succ\n return path\n\n# 併合する\n# buff1 = [a, b, c, d, e]\n# buff2 = [f, g, c, h, i]\n# (1) b - g => [a, b, g, f, i, h, c, d, e]\n# (2) d - h => [a, b, c, g, f, i, h, d, e]\n# (3) b - h => [a, b, h, i, f. g. c, d, e]\n# (4) d - g => [a, b. c. h, i, f, g, d, e]\ndef merge(buff1, buff2, p):\n #共有ポイントを探す\n p1, i1, n1 = search(p, buff1)\n p2, i2, n2 = search(p, buff2)\n # 差分を計算\n d1 = differ(buff1[p1], p, buff2[p2])\n d2 = differ(buff1[n1], p, buff2[n2])\n d3 = differ(buff1[p1], p, buff2[n2])\n d4 = differ(buff1[n1], p, buff2[p2])\n # 差分が一番大きいものを選択\n d = max(d1, d2, d3, d4)\n if d1 == d:\n # (1)\n buff1[i1:i1] = make_new_path(buff2, i2, -1)\n elif d2 == d:\n # (2)\n buff1[n1:n1] = make_new_path(buff2, i2, -1)\n elif d3 == d:\n # (3)\n buff1[i1:i1] = make_new_path(buff2, i2, 1)\n else:\n # (4)\n buff1[n1:n1] = make_new_path(buff2, i2, 1)\n return buff1\n\n# 分割統治法による解法\ndef divide_merge(buff):\n if len(buff) < 3:\n # print buff\n return buff\n else:\n if divide_direction(buff):\n p, b1, b2 = divide(buff, 0)\n else:\n p, b1, b2 = divide(buff, 1)\n b3 = divide_merge(b1)\n b4 = divide_merge(b2)\n return merge(b3, b4, p)\n\n\"\"\"\n# テスト\ndef divide_test(buff):\n if len(buff) < 26:\n draw_path(buff)\n else:\n if divide_direction(buff): #縦が長いときx座標を基準にソー\n p, b1, b2 = divide(buff, 0)\n else: #横が長いときy座標を基準にソート\n p, b1, b2 = divide(buff, 1)\n divide_test(b1)\n divide_test(b2)\n\"\"\"\n#経路の表示\ndef draw_path(path):\n x0, y0 = path[0][0]*a , path[0][1]*b\n for i in range(1, len(path)):\n x1, y1 = path[i][0]*a ,path[i][1]*b\n c0.create_line(x0, y0, x1, y1)\n x0, y0 = x1, y1\n c0.create_line(x0, y0, path[0][0]*a, path[0][1]*b)\n for x, y in path:\n c0.create_oval(x*a- 4 ,y*b- 4, x*a + 4, y*b + 4, fill = \"green\")\n\npoint_table = read_tsp(\"tsp/eil51.tsp\")\npath= divide_merge(point_table)\nprint(path_length(path))\n\ne = time.clock()\nmax_x = 800\nmax_y = 600\na= max_x // (max(map(lambda x: x[0], point_table)) +10)\nb= max_y // (max(map(lambda x: x[1], point_table)) +10)\n\nroot = Tk()\nc0 = Canvas(root, width = max_x, height = max_y, bg = \"white\")\nc0.pack()\n\ndraw_path(path)\n\nroot.mainloop()\n","sub_path":"aco/material/divide.py","file_name":"divide.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"351385879","text":"from invoke import task\nfrom os.path import join\nfrom tasks.lammps.data import upload as lammps_data_upload\nfrom tasks.util.env import (\n KERNELS_FAASM_FUNCS,\n KERNELS_FAASM_USER,\n KERNELS_WASM_DIR,\n LAMMPS_DOCKER_WASM,\n LAMMPS_FAASM_USER,\n LAMMPS_FAASM_FUNC,\n)\nfrom tasks.util.upload import upload_wasm\n\n\n@task()\ndef upload(ctx):\n \"\"\"\n Upload the MPI functions to Granny\n \"\"\"\n wasm_file_details = [\n {\n \"wasm_file\": LAMMPS_DOCKER_WASM,\n \"wasm_user\": LAMMPS_FAASM_USER,\n \"wasm_function\": LAMMPS_FAASM_FUNC,\n \"copies\": 1,\n },\n ]\n\n for kernel in KERNELS_FAASM_FUNCS:\n wasm_file_details.append(\n {\n \"wasm_file\": join(\n KERNELS_WASM_DIR, \"mpi_{}.wasm\".format(kernel)\n ),\n \"wasm_user\": KERNELS_FAASM_USER,\n \"wasm_function\": kernel,\n \"copies\": 1,\n }\n )\n\n upload_wasm(wasm_file_details)\n\n # LAMMPS also needs some extra data files\n lammps_data_upload(\n ctx, [\"compute\", \"compute-xl\", \"compute-xxl\", \"network\"]\n )\n","sub_path":"tasks/mpi/wasm.py","file_name":"wasm.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"502729392","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 15 14:49:33 2017\n\n@author: nb\n\"\"\"\n\nimport unittest\n\n\nimport numpy as np\n\nfrom .context import viroconcom\n\nfrom viroconcom.params import ConstantParam, FunctionParam\nfrom viroconcom.distributions import (WeibullDistribution, LognormalDistribution, NormalDistribution,\n KernelDensityDistribution,\n MultivariateDistribution)\n\nclass MultivariateDistributionTest(unittest.TestCase):\n \"\"\"\n Create a example MultivariateDistribution\n \"\"\"\n\n #define dependency tuple\n dep1 = (None, 0, None)\n dep2 = (0, None, 0)\n\n #define parameters\n shape = ConstantParam(1.471)\n loc = ConstantParam(0.8888)\n scale = ConstantParam(2.776)\n par1 = (shape, loc, scale)\n\n shape = FunctionParam(0.0400, 0.1748, -0.2243, \"f2\")\n loc = None\n scale = FunctionParam(0.1, 1.489, 0.1901, \"f1\")\n par2 = (shape, loc, scale)\n\n del shape, loc, scale\n\n #create distributions\n dist1 = WeibullDistribution(*par1)\n dist2 = LognormalDistribution(*par2)\n\n distributions = [dist1, dist2]\n dependencies = [dep1, dep2]\n\n\n def test_add_distribution_err_msg(self):\n \"\"\"\n tests if the right exception is raised when distribution1 has a\n dependency\n \"\"\"\n\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, self.dependencies)\n\n\n def test_add_distribution_iter(self):\n \"\"\"\n tests if an exception is raised by the function add_distribution when\n distributions isn't iterable but dependencies is and the other way around\n \"\"\"\n\n distributions = 1\n with self.assertRaises(ValueError):\n MultivariateDistribution(distributions, self.dependencies)\n dependencies = 0\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, dependencies)\n\n def test_add_distribution_length(self):\n \"\"\"\n tests if an exception is raised when distributions and dependencies\n are of unequal length\n \"\"\"\n\n dep3 = (0, None, None)\n dependencies = [self.dep1, self.dep2, dep3]\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, dependencies)\n\n def test_add_distribution_dependencies_length(self):\n \"\"\"\n tests if an exception is raised when a tuple in dependencies\n has not length 3\n \"\"\"\n\n dep1 = (None, None)\n dependencies = [dep1, self.dep2]\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, dependencies)\n\n def test_add_distribution_dependencies_value(self):\n \"\"\"\n tests if an exception is raised when dependencies has an invalid value\n \"\"\"\n\n dep1 = (-3, None, None)\n dependencies = [dep1, self.dep2]\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, dependencies)\n\n\n\n def test_add_distribution_not_iterable(self):\n \"\"\"\n tests the function when both distributions and dependencies\n are not iterable\n \"\"\"\n\n distributions = 1\n dependencies = 2\n with self.assertRaises(ValueError):\n MultivariateDistribution(distributions, dependencies)\n\n\n\nclass ParametricDistributionTest(unittest.TestCase):\n\n def test_distribution_shape_None(self):\n \"\"\"\n tests if shape is set to default when it has value 'None'\n \"\"\"\n\n #define parameters\n shape = None\n loc = ConstantParam(0.8888)\n scale = ConstantParam(2.776)\n par1 = (shape, loc, scale)\n rv_values = [0.8, 1, 8]\n dependencies = (0, 1, 1)\n\n dist = NormalDistribution(*par1)\n shape_test = dist._get_parameter_values(rv_values, dependencies)[0]\n self.assertEqual(shape_test, 1)\n\n\n def test_distribution_loc_None(self):\n \"\"\"\n tests if loc is set to default when it has value 'None'\n \"\"\"\n\n #define parameters\n shape = ConstantParam(0.8888)\n loc = None\n scale = ConstantParam(2.776)\n par1 = (shape, loc, scale)\n rv_values = [0.8, 1, 8]\n dependencies = (0, 1, 1)\n\n dist = WeibullDistribution(*par1)\n loc_test = dist._get_parameter_values(rv_values, dependencies)[1]\n self.assertEqual(loc_test, 0)\n\n\n def test_distribution_loc_scale(self):\n \"\"\"\n tests if scale is set to default when it has value 'None'\n \"\"\"\n\n #define parameters\n shape = ConstantParam(0.8888)\n loc = ConstantParam(2.776)\n scale = None\n par1 = (shape, loc, scale)\n rv_values = [0.8, 1, 8]\n dependencies = (0, 1, 1)\n\n dist = NormalDistribution(*par1)\n scale_test = dist._get_parameter_values(rv_values, dependencies)[2]\n self.assertEqual(scale_test, 1)\n\n\n def test_check_parameter_value(self):\n \"\"\"\n tests if the right exception is raised when the given parameters are\n not in the valid range of numbers\n \"\"\"\n\n shape = None\n loc = ConstantParam(0.8888)\n scale = ConstantParam(-2.776)\n par1 = (shape, loc, scale)\n\n dist = WeibullDistribution(*par1)\n\n with self.assertRaises(ValueError):\n dist._check_parameter_value(2, -2.776)\n with self.assertRaises(ValueError):\n dist._check_parameter_value(2, np.inf)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/test_distributions.py","file_name":"test_distributions.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"454089451","text":"import inspect\n\nfrom pepys_import.core.store import sqlite_db\n\n\ndef row_to_dict(table_object, data_store):\n \"\"\"Converts all entities of a table into a dict of {column_name: value}s.\n\n :param table_object: A table object\n :type table_object: sqlalchemy.ext.declarative.DeclarativeMeta\n :param data_store: A :class:`DataStore` object\n :type data_store: DataStore\n :return: Returns a dictionary with values\n :rtype: Dict\n \"\"\"\n with data_store.session_scope():\n values = data_store.session.query(table_object).all()\n objects = list()\n for row in values:\n d = {column.name: getattr(row, column.name) for column in row.__table__.columns}\n objects.append(d)\n return objects\n\n\ndef find_sqlite_table_object(table_object, data_store):\n \"\"\"Finds and returns a SQLite Base class which will be used to create and insert values.\n\n :param table_object: A table object\n :type table_object: sqlalchemy.ext.declarative.DeclarativeMeta\n :param data_store: A :class:`DataStore` object\n :type data_store: DataStore\n :return: Returns a table object\n :rtype: sqlalchemy.ext.declarative.DeclarativeMeta\n \"\"\"\n if data_store.db_type == \"postgres\":\n for name, obj in inspect.getmembers(sqlite_db):\n if inspect.isclass(obj) and name == table_object.__name__:\n return obj\n else:\n return table_object\n\n\ndef export_reference_tables(source_store, destination_store, table_objects):\n \"\"\"Copies table objects from :code:`source_store` to :code:`destination_store`.\n\n :param source_store: A :class:`DataStore` object to fetch objects\n :type source_store: DataStore\n :param destination_store: A :class:`DataStore` object to copy the objects from source_store\n :type destination_store: DataStore\n :param table_objects: A list of table objects\n :type table_objects: List\n :return:\n \"\"\"\n for table_object in table_objects:\n dict_values = row_to_dict(table_object, source_store)\n object_ = find_sqlite_table_object(table_object, source_store)\n with destination_store.session_scope():\n destination_store.session.bulk_insert_mappings(object_, dict_values)\n\n\ndef export_metadata_tables(source_store, destination_store, privacy_ids):\n \"\"\"Copies :code:`Platform`, :code:`Sensor` and :code:`Synonym` objects from\n :code:`source_store` to :code:`destination_store`.\n\n :param source_store: A :class:`DataStore` object to fetch objects\n :type source_store: DataStore\n :param destination_store: A :class:`DataStore` object to copy the objects from source_store\n :type destination_store: DataStore\n :param privacy_ids: A list of Privacy ID's which is used to filter Platform and Sensor objects\n :type privacy_ids: List\n :return:\n \"\"\"\n for table_object in [\n source_store.db_classes.Platform,\n source_store.db_classes.Sensor,\n source_store.db_classes.Synonym,\n ]:\n with source_store.session_scope():\n dict_values = list()\n if table_object.__name__ == \"Platform\":\n values = (\n source_store.session.query(table_object)\n .filter(table_object.privacy_id.in_(privacy_ids))\n .all()\n )\n platform_ids = [row.platform_id for row in values]\n elif table_object.__name__ == \"Sensor\":\n values = (\n source_store.session.query(table_object)\n .filter(table_object.host.in_(platform_ids))\n .filter(table_object.privacy_id.in_(privacy_ids))\n .all()\n )\n sensor_ids = [row.sensor_id for row in values]\n else:\n all_ids = list()\n all_ids.extend(platform_ids)\n all_ids.extend(sensor_ids)\n values = (\n source_store.session.query(source_store.db_classes.Synonym)\n .filter(source_store.db_classes.Synonym.entity.in_(all_ids))\n .all()\n )\n for row in values:\n d = {column.name: getattr(row, column.name) for column in row.__table__.columns}\n dict_values.append(d)\n\n object_ = find_sqlite_table_object(table_object, source_store)\n with destination_store.session_scope():\n destination_store.session.bulk_insert_mappings(object_, dict_values)\n","sub_path":"pepys_admin/snapshot_helpers.py","file_name":"snapshot_helpers.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"216571109","text":"import os\nimport sys\n\ndef computeTrueCase(filename, output_file='output_files'):\n log = ''\n try:\n print ('Converting to PDF...')\n\n if not os.path.exists(output_file):\n os.makedirs(output_file)\n\n log = os.popen('pdflatex --output-directory={0} {1}'.format(output_file, filename)).read()\n\n # Uncomment to open pdf after build completes\n # os.popen('open {0}'.format('{0}/{1}pdf'.format(output_file, filename[:-3]))).read()\n\n print(log)\n print ('Done!')\n except:\n print(log)\n print('Ooops! Something went wrong. Does the folder name you provided exist?')\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Please provide filename and output directory')\n print('i.e. python toPDF.py HW0.tex')\n exit()\n if len(sys.argv) > 2:\n print('Too many arguments provided')\n exit()\n print(os.getcwd())\n if not os.path.exists(sys.argv[1]):\n print('Tex file you provided does not exist.')\n exit()\n\n computeTrueCase(sys.argv[1])\n","sub_path":"WrittenHW/buildPDF.py","file_name":"buildPDF.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"416291066","text":"from flask import Flask, render_template, session, redirect, url_for, flash, request\nfrom flask_bootstrap import Bootstrap\nfrom flask_moment import Moment\nfrom flask_wtf import FlaskForm\nfrom wtforms import TextField, IntegerField, TextAreaField\nfrom wtforms import SubmitField, RadioField, SelectField\nfrom wtforms import validators, ValidationError\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired\nfrom flask_script import Manager\nfrom frame import Frame\n\nfrom threading import Thread, Lock\nfrom hksSer import serThread, serVar\nimport time\n\nmySer = serThread()\nmySerVar = serVar\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'hard to guess string'\n\nbootstrap = Bootstrap(app)\nmoment = Moment(app)\nmanager = Manager(app)\n\nclass ControlForm(FlaskForm):\n gid = IntegerField(\"Group Id: \",[validators.Required(\"Please enter your name.\")])\n pid = IntegerField(\"Private Id: \",[validators.Required(\"Please enter your name.\")])\n level = IntegerField(\"Level: \",[validators.Required(\"Please enter your name.\")])\n sub = RadioField('Command', choices=[('103','Control'),\n ('104','NewSet'), ('109','Alternative'), ('110','Status'), ('101','Power')])\n submit = SubmitField(\"Send\")\n\nclass NameForm(FlaskForm):\n name = StringField('What is your name?', validators=[DataRequired()])\n submit = SubmitField('Submit')\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n form = NameForm()\n if form.validate_on_submit():\n old_name = session.get('name')\n if old_name is not None and old_name != form.name.data:\n flash('Looks like you have changed your name!')\n session['name'] = form.name.data\n return redirect(url_for('index'))\n return render_template('index.html', form=form, name=session.get('name'))\n\n@app.route('/test', methods=['GET', 'POST'])\ndef test():\n form = ControlForm()\n if form.validate_on_submit():\n print('validate_on_submit')\n myFrame = Frame()\n myFrame.setFrame()\n print(myFrame.getFrame())\n print('bsl frame test')\n return render_template('control.html', form=form)\n\nclass testThread(Thread):\n def __init__(self):\n print('Start testThread')\n Thread.__init__(self)\n def run(self):\n while True:\n time.sleep(1) #for thread, very important\n if mySer.myVar.readFlag:\n mySer.myVar.readFlag = False\n print('var:{}'.format(mySerVar.readFlag))\n mySer.send(mySer.readStr)\n print('self.myVar.readFlag')\n print('End of testThread')\n\n\ntestThreadFirstFlag = True\n@app.route('/new', methods=['GET', 'POST'])\ndef new():\n form = ControlForm()\n global testThreadFirstFlag\n if testThreadFirstFlag:\n print('Generate testThread')\n testThreadFirstFlag = False\n myThread = testThread()\n myThread.start()\n return render_template('control.html', form=form)\n\n@app.route('/stop', methods=['GET', 'POST'])\ndef stop():\n form = ControlForm()\n if mySer.getSerAlive():\n mySer.send('Quit Serial')\n else:\n print('at start Finished Serial')\n return render_template('control.html', form=form)\n\n@app.route('/start', methods=['GET', 'POST'])\ndef startSer():\n form = ControlForm()\n if mySer.serFirstFlag:\n mySer.serFirstFlag = False\n mySer.start()\n print('Now start my Serial')\n time.sleep(1)\n return render_template('control.html', form=form)\n\n@app.route('/', methods=['GET', 'POST'])\ndef control():\n startSer()\n form = ControlForm()\n if request.method == 'POST':\n if form.validate() == False:\n flash('All fields are required.')\n print('form.validate() == False:')\n return render_template('control.html', form=form)\n else:\n myFrame = Frame()\n gid = request.form['gid']\n pid = request.form['pid']\n level = request.form['level']\n sub = request.form['sub']\n print('gid:{}, pid:{}, level:{}, sub:{}'.format(gid, pid, level, sub))\n myFrame.setGid(int(gid)); myFrame.setPid(int(pid)); myFrame.setLevel(int(level));\n myFrame.setSub(int(sub))\n myFrame.setFrame()\n mySer.send(myFrame.getFrame())\n return render_template('control.html', form=form)\n\n elif request.method == 'GET':\n print('request.method == GET ')\n return render_template('control.html', form=form)\n\nif __name__ == '__main__':\n app.run(debug=True)\n print('Now Run')\n # manager.run()\n# python3 hello.py runserver --host 0.0.0.0\n","sub_path":"project/serverTest/bsl.py","file_name":"bsl.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"78992798","text":"# Copyright 2018 luozhouyang\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 os\n\nimport tensorflow as tf\n\nfrom naivenmt.utils import get_dict_from_collection\nfrom naivenmt.utils import get_predictions\n\n\nclass SaveEvaluationPredictionsHook(tf.train.SessionRunHook):\n \"\"\"Do evaluation and save prediction results to file.\"\"\"\n\n def __init__(self,\n out_dir,\n eos=\"</s>\",\n subword_option=\"\",\n post_evaluation_fn=None):\n \"\"\"Init.\n\n Args:\n out_dir: model's dir\n eos: eos of params\n subword_option: subword options of params\n post_evaluation_fn: a callback fn with signature (global_steps, predictions_file),\n called after saving predictions\n \"\"\"\n self.eos = eos\n self.subword_option = subword_option\n self.output_file = os.path.join(out_dir, \"output_dev\")\n self.post_evaluation_fn = post_evaluation_fn\n self.predictions = None\n self.global_steps = None\n\n def begin(self):\n self.predictions = get_dict_from_collection(\"predictions\")\n self.global_steps = tf.train.get_global_step()\n\n def before_run(self, run_context):\n if not self.predictions:\n raise ValueError(\"Model does not define predictions.\")\n if not self.global_steps:\n raise ValueError(\"Not created global steps.\")\n return tf.train.SessionRunArgs([self.predictions, self.global_steps])\n\n def after_run(self,\n run_context, # pylint: disable=unused-argument\n run_values):\n predictions, self.global_steps = run_values.results\n self.output_file = self.output_file + \".\" + self.global_steps\n predictions = get_predictions(predictions, self.eos, self.subword_option)\n\n with open(self.output_file, mode=\"a\", encoding=\"utf8\") as f:\n if isinstance(predictions, str):\n f.write(predictions + \"\\n\")\n elif isinstance(predictions, list):\n for p in predictions:\n f.write(p + \"\\n\")\n\n def end(self, session):\n tf.logging.info(\"Evaluation predictions saved to %s\" % self.output_file)\n if self.post_evaluation_fn:\n self.post_evaluation_fn(self.global_steps, self.output_file)\n","sub_path":"naivenmt/hooks/eval_hooks.py","file_name":"eval_hooks.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"646413931","text":"#!/usr/bin/env python\n\nfrom os.path import basename\n\nimport six\n\nfrom .core import Multipart, Field\n\n\ndef encode(fields):\n field_list = []\n\n for name, value in six.iteritems(fields):\n explicit_filename = ''\n if isinstance(value, (tuple, list)):\n value, explicit_filename = value\n\n if hasattr(value, 'read'):\n # Quacks like a file\n field_list.append(\n Field(name, fileobj=value, filename=(explicit_filename or basename(value.name)))\n )\n\n else:\n field_list.append(Field(name, value))\n\n return Multipart(field_list)\n","sub_path":"multipart/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"608147197","text":"#! /usr/bin/env python3\n\nimport argparse\nimport logging\nimport os\nimport subprocess\nimport sys\n\ndef getRunNumber(inputstring: str):\n delim = inputstring.find(\"_\")\n if delim < 0:\n return -1\n runnostring = inputstring[:delim]\n if runnostring.isdigit():\n return int(runnostring)\n return -1\n\nif __name__ == \"__main__\":\n scriptdir = os.path.dirname(os.path.abspath(sys.argv[0]))\n submitter = os.path.join(scriptdir, \"submitMergeMCDatasets.py\")\n parser = argparse.ArgumentParser(\"submitMergeSamples.py\", description=\"Launch merging of single dataset merging\")\n parser.add_argument(\"inputdir\", metavar=\"INPUTDIR\", type=str, help=\"Input directory\")\n parser.add_argument(\"-f\", \"--file\", metavar=\"FILE\", type=str, default=\"AnalysisResults.root\", help=\"\")\n parser.add_argument(\"-p\", \"--partition\", metavar=\"PARTITION\", type=str, default=\"vip\", help=\"Partition of the 587 cluster\")\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", help=\"Debug mode\")\n args = parser.parse_args()\n\n loglevel = logging.INFO\n if args.debug:\n loglevel = logging.DEBUG\n logging.basicConfig(format=\"%(levelname)s: %(message)s\", level=loglevel)\n\n samples = [x for x in os.listdir(os.path.abspath(args.inputdir)) if \"LHC\" in x]\n if not len(samples):\n # check if runwise\n samples = [x for x in os.listdir(os.path.abspath(args.inputdir)) if x.isdigit()]\n for sample in samples:\n logging.info(\"Submitting %s ...\", sample)\n fullsamplepath = os.path.join(args.inputdir, sample)\n submitcmd = \"{EXE} {SAMPLEDIR} -f {FILE} -p {PARTITION}\".format(EXE=submitter, SAMPLEDIR=fullsamplepath, FILE=args.file, PARTITION=args.partition)\n subprocess.call(submitcmd, shell=True)","sub_path":"merge/submitMergeSamplesDataset.py","file_name":"submitMergeSamplesDataset.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"191870468","text":"\"\"\"\nURLconf for registration and activation, based on django-registration's\ndefault backend.\n\n\"\"\"\n\nfrom django.conf.urls.defaults import *\nfrom django.views.generic.simple import direct_to_template\n\nfrom corehq.apps.registration.user_registration_backend import activate_by_form\n\nurlpatterns = patterns('',\n url(r'^register/closed/$',\n direct_to_template,\n { 'template': 'registration/backend/registration_closed.html' },\n name='registration_disallowed'), \n\n # Activation keys get matched by \\w+ instead of the more specific\n # [a-fA-F0-9]{40} because a bad activation key should still get to the view;\n # that way it can return a sensible \"invalid key\" message instead of a\n # confusing 404.\n # Because our main activation workflow relies on the user adding new data\n # at activation time, we can't use the default 'activate.' Had to rewrite it. \n url(r'^activate/user_inputs_data/(?P<activation_key>\\w+)/$',\n activate_by_form,\n { 'backend': 'corehq.apps.registration.user_registration_backend.UserRegistersSelfBackend' },\n name='registration_activate_user_inputs_data'), \n \n url(r'^activate/complete(?:/(?P<caller>\\w+))?(?:/(?P<account>\\w+))?/$',\n direct_to_template,\n { 'template': 'registration/backend/activation_complete.html' },\n name='registration_activation_complete') \n )\n","sub_path":"corehq/apps/registration/user_registration_backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52162049","text":"\nimport speech_recognition #Speech to text chuyển giọng nói thành văn bản Tiếng việt\nfrom gtts import gTTS #Chuyển văn bản thành giọng nói Tiếng Việt\nimport os #Thực thi câu lệnh trong CMD\nfrom playsound import playsound #Chạy âm thanh mp3\nimport datetime #Lấy ngày hiện tại\nfrom selenium import webdriver #Mô phỏng thao tác click chuột trên Browser\nfrom time import sleep #Nghỉ\nfrom pynput.keyboard import Key, Controller #Tự động sử dụng bàn phím\nfrom selenium.webdriver.common.keys import Keys\nimport xlrd\nimport xlwt\n\nkeyboard = Controller() #Khởi tạo bàn phím ảo\nbot_brain= \"\" #Khởi tạo biến suy nghĩ của robot\nbot_ear = speech_recognition.Recognizer() #Khởi tạo biến bot_ear bằng Giọng nói người thật truyền vào chuyển thành văn bản dưới dạng chuỗi\nfile_location = \"output.xls\"\nwb = xlrd.open_workbook(file_location)\nsheet1 = wb.sheet_by_index(0)\nhang = sheet1.nrows\ncot = sheet1.ncols\nprint('số hàng trong Excel:')\nprint(sheet1.nrows)\nprint('số cột trong Excel:')\nprint(sheet1.ncols)\ni=0\ndem=0\nworkbook = xlrd.open_workbook('driendlist.xlsx')\nsheet = workbook.sheet_by_index(0)\ndata = [sheet.cell_value(0, 1) for col in range(sheet.ncols)]\nworkbook = xlwt.Workbook()\nsheet = workbook.add_sheet('Friend')\nmangtim = []\nlinktim = []\n\nwhile True: #Biến vô tận\n with speech_recognition.Microphone() as mic: #Chờ đợi sử dụng Mic để chuyển thành văn bản\n print(\"\\nSiri: I'm listening\")\n #audio = bot_ear.listen(mic)\n audio = bot_ear.record(mic, duration= 5) #Sau khi nghe từ Mic, nhận biến audio là sound\n print(\"\\nSiri: ....\")\n try:\n you = bot_ear.recognize_google(audio,language='vi-VN').upper() #truyền biến audio lên API GG, nhận về chuỗi kí tự theo giọng nói\n print(\"\\nYou: \"+you)\n except:\n you=\"\"\n print(\"\\nSiri: \"+you)\n if \"XIN CHÀO\" in you:\n bot_brain = \"Xin chào Dũng\"\n elif you == \"\":\n bot_brain =\"\"\n elif \"GIỎI\" in you:\n bot_brain =\"Cảm ơn nhé ! Đó là điều tôi nên làm\"\n elif \"BẠN CÓ THỂ GIÚP GÌ\" in you:\n bot_brain = \"Tôi có thể giúp bạn tìm kiếm thông tin, chơi nhạc, chụp ảnh\"\n elif \"GỌI\" in you:\n bot_brain = \"Gọi cho ai\"\n tts = gTTS(text=bot_brain, lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n os.remove(\"Siri.mp3\")\n with speech_recognition.Microphone() as mic:\n print(\"\\nSiri: I'm listening\")\n # audio = bot_ear.listen(mic)\n audio = bot_ear.record(mic, duration=5)\n print(\"\\nSiri: ....\")\n try:\n you = bot_ear.recognize_google(audio, language='vi-VN').upper()\n print(\"\\nYou: \" + you)\n except:\n you = \"\"\n print(\"\\nSiri: \" + you)\n if you == \"\":\n bot_brain = \"Google đây, bạn tự tìm lấy nhé\"\n os.system(\"start www.google.com\")\n # chrome_options = webdriver.ChromeOptions()\n # chrome_options.add_argument(\"--incognito\")\n # browser = webdriver.Chrome(chrome_options=chrome_options)\n # browser.get(\"https://www.facebook.com/videocall/incall/?peer_id=100006131910859\")\n # sleep(1)\n # mail = browser.find_element_by_id('email')\n # mail.send_keys('phantridungdz')\n # password = browser.find_element_by_id('pass')\n # password.send_keys('buonthicukhocdi123')\n # password.send_keys(Keys.ENTER)\n # sleep(2)\n # browser.get(\"https://www.facebook.com/messages/t/100006131910859\")\n # doit = browser.find_element_by_xpath(\n # '/html/body/div[1]/div[1]/div[1]/div/div/div/div[2]/span/div[1]/ul/li[1]/a')\n # doit.click()\n else:\n tencantim = you\n while i < hang:\n nickname = sheet1.cell_value(i, 0).upper()\n link = sheet1.cell_value(i, 1)\n b = nickname.split()\n count = len(b)\n if tencantim in b:\n d = ' '.join(b)\n link1 = link.lstrip('https://www.faceboo')\n link2 = link1.lstrip('k.com')\n link3 = link2.lstrip('/')\n kiemtra = link3.startswith('profile.php?id=')\n if kiemtra == True:\n link4 = link3.lstrip('profile.php?id=')\n mangtim.append(d)\n linktim.append(link4)\n i += 1\n # soketqua = len(mangtim)\n # bot_brain = \"có \"+ str(soketqua) + \" \"+ tencantim + \" trong danh sách bạn bè, bạn muốn gọi \" + tencantim +\" mấy?\"\n # tts = gTTS(text=bot_brain, lang='vi')\n # tts.save(\"Siri.mp3\")\n # playsound(\"Siri.mp3\")\n # os.remove(\"Siri.mp3\")\n\n bot_brain = \"đang gọi \"+ mangtim[1]\n tts = gTTS(text=bot_brain, lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n os.remove(\"Siri.mp3\")\n\n os.system(\"start www.facebook.com/videocall/incall/?peer_id=\"+linktim[1])\n sleep(4)\n keyboard.press(Key.tab)\n keyboard.release(Key.tab)\n keyboard.press(Key.tab)\n keyboard.release(Key.tab)\n keyboard.press(Key.enter)\n keyboard.release(Key.enter)\n\n\n elif \"chụp ảnh\"in you:\n bot_brain =\"Cười lên nào !\"\n os.system(\"start microsoft.windows.camera:\")\n sleep(2)\n keyboard.press(Key.enter)\n keyboard.release(Key.enter)\n bot_brain = \"Xong rồi đó, một bức ảnh tuyệt đẹp!\"\n elif \"thời tiết\" in you:\n bot_brain = \" Hôm nay trời nhiều mây\"\n elif \"Facebook\" in you:\n os.system(\"start www.facebook.com\")\n bot_brain = \"Em mở facebook cho anh rồi nhé\"\n elif \"Youtube\" in you:\n os.system(\"start www.youtube.com\")\n bot_brain = \"Em mở youtube cho anh rồi nhé\"\n elif \"Google\" in you:\n os.system(\"start www.google.com\")\n bot_brain = \"Em mở Google cho anh rồi nhé\"\n\n elif \"ngày\" in you:\n bot_brain = datetime.datetime.now().strftime(\"%A\") #=Monday\n elif \"Mở nhạc\" in you:\n bot_brain = \"Bạn muốn nghe bài gì ?\"\n tts = gTTS(text=bot_brain, lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n os.remove(\"Siri.mp3\")\n with speech_recognition.Microphone() as mic:\n print(\"\\nSiri: I'm listening\")\n # audio = bot_ear.listen(mic)\n audio = bot_ear.record(mic, duration=5)\n print(\"\\nSiri: ....\")\n try:\n you = bot_ear.recognize_google(audio, language='vi-VN')\n print(\"\\nYou: \" + you)\n except:\n you = \"\"\n print(\"\\nSiri: \" + you)\n if you == \"\":\n bot_brain = \"Google đây, bạn tự tìm lấy nhé\"\n os.system(\"start www.google.com\")\n else:\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(\"--incognito\")\n browser = webdriver.Chrome(chrome_options=chrome_options)\n browser.get(\"http://youtube.com/\")\n doit = browser.find_element_by_xpath('/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input')\n doit.send_keys(you)\n doit = browser.find_element_by_xpath('/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/button')\n doit.click()\n sleep(3)\n doit = browser.find_element_by_xpath('/html/body/ytd-app/div/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-video-renderer[1]/div[1]/ytd-thumbnail/a/yt-img-shadow')\n doit.click()\n bot_brain = \"Chúc bạn nghe nhạc vui vẻ\"\n elif \"tìm\" in you:\n bot_brain = \"Bạn muốn tìm gì ?\"\n tts = gTTS(text=bot_brain, lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n os.remove(\"Siri.mp3\")\n with speech_recognition.Microphone() as mic:\n print(\"\\nSiri: I'm listening\")\n # audio = bot_ear.listen(mic)\n audio = bot_ear.record(mic, duration=5)\n print(\"\\nSiri: ....\")\n try:\n you = bot_ear.recognize_google(audio, language='vi-VN')\n print(\"\\nYou: \" + you)\n except:\n you = \"\"\n print(\"\\nSiri: \" + you)\n if you == \"\":\n bot_brain = \"Google đây, bạn tự tìm lấy nhé\"\n else:\n os.system(\"start www.google.com/search?q=\"+you.replace(' ','+'))\n bot_brain = \"Đây là kết quả tôi tìm được\"\n\n else:\n os.system(\"start www.google.com/search?q=\" + you.replace(' ', '+'))\n bot_brain = \"Đây là kết quả tìm kiếm trên google !\"\n print(\"\\nSiri: \" + bot_brain)\n try:\n tts = gTTS(text = bot_brain,lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n\n except:\n bot_brain=\"\"","sub_path":"Nghetiengviet.py","file_name":"Nghetiengviet.py","file_ext":"py","file_size_in_byte":9246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"18891095","text":"#!/usr/bin/env python3\n\"\"\" Python Flask Module \"\"\"\n\n\nfrom flask import Flask, render_template\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n \"\"\"Index page\"\"\"\n return render_template('0-index.html')\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"0x0A-i18n/0-app.py","file_name":"0-app.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"217137688","text":"import pytest\nfrom selenium import webdriver\n\n@pytest.fixture(scope=\"class\")\ndef setUp(request):\n driver = webdriver.Chrome(executable_path=\"/Users/kashirol/Downloads/chromedriver\")\n driver.get(\"https://rahulshettyacademy.com/seleniumPractise/\")\n driver.maximize_window()\n request.cls.driver = driver\n yield\n driver.close()","sub_path":"PythonTestFramework/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"402222930","text":"# -*- coding: utf-8 -*- #\n# 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\"\"\"Utils for GKE Hub commands.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.util import waiter\nfrom googlecloudsdk.command_lib.container.hub import kube_util\nfrom googlecloudsdk.core import exceptions\n\n# The CustomResourceDefinition for the Membership Resource. It is created on an\n# as needed basis when registering a cluster to the hub.\nMEMBERSHIP_CRD_MANIFEST = \"\"\"\\\napiVersion: apiextensions.k8s.io/v1beta1\nkind: CustomResourceDefinition\nmetadata:\n name: memberships.hub.gke.io\nspec:\n group: hub.gke.io\n scope: Cluster\n names:\n plural: memberships\n singular: membership\n kind: Membership\n versions:\n - name: v1beta1\n served: true\n storage: true\n validation:\n openAPIV3Schema:\n required:\n - spec\n properties:\n metadata:\n type: object\n properties:\n name:\n type: string\n pattern: '^(membership|test-.*)$'\n spec:\n type: object\n properties:\n owner:\n type: object\n properties:\n id:\n type: string\n description: Membership owner ID. Should be immutable.\"\"\"\n\n# The Membership Resource that enforces cluster exclusivity. It specifies the\n# hub project that the cluster is registered to. During registration, it is used\n# to ensure a user does not register a cluster to multiple hub projects.\nMEMBERSHIP_CR_TEMPLATE = \"\"\"\\\nkind: Membership\napiVersion: hub.gke.io/v1beta1\nmetadata:\n name: membership\nspec:\n owner:\n id: projects/{project_id}\"\"\"\n\n\ndef GetMembershipCROwnerID(kube_client):\n \"\"\"Returns the project id of the hub the cluster is a member of.\n\n The Membership Custom Resource stores the project id of the hub the cluster\n is registered to in the `.spec.owner.id` field.\n\n Args:\n kube_client: A KubernetesClient.\n\n Returns:\n a string, the project id\n None, if the Membership CRD or CR do not exist on the cluster.\n\n Raises:\n exceptions.Error: if the Membership resource does not have a valid owner id\n \"\"\"\n\n owner_id = kube_client.GetMembershipOwnerID()\n if owner_id is None:\n return None\n id_prefix = 'projects/'\n if not owner_id.startswith(id_prefix):\n raise exceptions.Error(\n 'Membership .spec.owner.id is invalid: {}'.format(owner_id))\n return owner_id[len(id_prefix):]\n\n\ndef ApplyMembershipResources(kube_client, project):\n \"\"\"Creates or updates the Membership CRD and CR with the hub project id.\n\n Args:\n kube_client: A KubernetesClient.\n project: The project id of the hub the cluster is a member of.\n\n Raises:\n exceptions.Error: if the Membership CR or CRD couldn't be applied.\n \"\"\"\n\n membership_cr_manifest = MEMBERSHIP_CR_TEMPLATE.format(project_id=project)\n kube_client.ApplyMembership(MEMBERSHIP_CRD_MANIFEST, membership_cr_manifest)\n\n\ndef DeleteMembershipResources(kube_client):\n \"\"\"Deletes the Membership CRD.\n\n Due to garbage collection all Membership resources will also be deleted.\n\n Args:\n kube_client: A KubernetesClient.\n \"\"\"\n\n try:\n succeeded, error = waiter.WaitFor(\n kube_util.KubernetesPoller(),\n MembershipCRDeleteOperation(kube_client),\n 'Deleting membership CR in the cluster',\n pre_start_sleep_ms=kube_util.NAMESPACE_DELETION_INITIAL_WAIT_MS,\n max_wait_ms=kube_util.NAMESPACE_DELETION_TIMEOUT_MS,\n wait_ceiling_ms=kube_util.NAMESPACE_DELETION_MAX_POLL_INTERVAL_MS,\n sleep_ms=kube_util.NAMESPACE_DELETION_INITIAL_POLL_INTERVAL_MS)\n except waiter.TimeoutError:\n # waiter.TimeoutError assumes that the operation is a Google API\n # operation, and prints a debugging string to that effect.\n raise exceptions.Error('Timeout deleting membership CR from cluster.')\n\n if not succeeded:\n raise exceptions.Error(\n 'Could not delete membership CR from cluster. Error: {}'.format(error))\n\n\nclass MembershipCRDeleteOperation(object):\n \"\"\"An operation that waits for a membership CR to be deleted.\"\"\"\n\n def __init__(self, kube_client):\n self.kube_client = kube_client\n self.done = False\n self.succeeded = False\n self.error = None\n\n def __str__(self):\n return '<deleting membership CR>'\n\n def Update(self):\n \"\"\"Updates this operation with the latest membership CR deletion status.\"\"\"\n err = self.kube_client.DeleteMembership()\n\n # The first delete request should succeed.\n if not err:\n return\n\n # If deletion is successful, the delete command will return a NotFound\n # error.\n if 'NotFound' in err:\n self.done = True\n self.succeeded = True\n else:\n self.error = err\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/container/hub/exclusivity_util.py","file_name":"exclusivity_util.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"470367116","text":"__author__ = \"Jayde Yue\"\n# Website: www.jaydeyue.com\n\n\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport threading\n\n\nclass DictWorker(threading.Thread):\n\n def __init__(self, dict, scanner, dict_number):\n threading.Thread.__init__(self)\n self.dict = dict\n self.scanner = scanner\n self.dict_number = dict_number\n\n def request_with_retrys(self, session):\n retry = Retry(\n total=self.scanner.max_retrys,\n read=self.scanner.max_retrys,\n connect=self.scanner.max_retrys,\n backoff_factor=0.3,\n status_forcelist=(500, 502, 504),\n )\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\n def procese_valid_url(self, request_url, response):\n print(request_url + \": \" + str(response.status_code))\n self.scanner.dict_stats[self.dict_number] +=1\n if not self.scanner.allow_overlap:\n self.scanner.all_trys[request_url[len(self.scanner.base_url):]] = 1\n\n def run(self):\n while not self.dict.empty():\n try:\n request_url = self.scanner.base_url + self.dict.get_nowait()\n session = requests.Session()\n if self.scanner.user != '':\n session.auth = (self.scanner.user, self.scanner.pwd)\n session.headers.update({\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',\n 'Referer': self.scanner.referer,\n 'Cookie': self.scanner.cookie,\n })\n response = self.request_with_retrys(session).get(request_url, timeout=self.scanner.time_out, allow_redirects=self.scanner.allow_redirect)\n if response.status_code != 404:\n if self.scanner.allow_redirect:\n if len(response.history) > 0:\n if response.url not in self.scanner.redirect_list:\n self.scanner.redirect_list[response.url] = [request_url]\n else:\n self.scanner.redirect_list[response.url].append(request_url)\n # self.scanner.dict_stats[self.dict_number] +=1\n else:\n self.procese_valid_url(request_url, response)\n elif response.status_code != 302 and response.status_code != 301:\n self.procese_valid_url(request_url, response)\n except Exception as e:\n print(e)\n break\n","sub_path":"Scanner/DictWorker.py","file_name":"DictWorker.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"307350310","text":"# LocalDotfile\nimport os\nimport simplejson as json\nPLUGIN_LOG_TITLE = 'Local Dotfile' # Log Title\n\nVERSION_NO = '2016.04.10.1'\n\n# Delay used when requesting HTML, may be good to have to prevent being banned\n# from the site\nREQUEST_DELAY = 0\n\n\ndef Start():\n HTTP.CacheTime = CACHE_1WEEK\n HTTP.Headers['User-agent'] = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows ' \\\n 'NT 6.2; Trident/4.0; SLCC2; .NET ' \\\n 'CLR 2.0.50727; .NET CLR 3.5.30729; ' \\\n '.NET CLR 3.0.30729; Media Center PC 6.0)'\n\n\nclass LocalDotfile(Agent.Movies):\n name = 'Local Dotfile'\n languages = [Locale.Language.NoLanguage, Locale.Language.English]\n primary_provider = False\n contributes_to = ['com.plexapp.agents.cockporn']\n\n def Log(self, message, *args):\n if Prefs['debug']:\n Log(PLUGIN_LOG_TITLE + ' - ' + message, *args)\n\n def search(self, results, media, lang, manual):\n self.Log('------------------------------------------------------------'\n '-----------')\n self.Log('SEARCH CALLED v.%s', VERSION_NO)\n self.Log('SEARCH - media.title - %s', media.title)\n self.Log('SEARCH - media.items[0].parts[0].file - %s',\n media.items[0].parts[0].file)\n self.Log('SEARCH - media.primary_metadata.title - %s',\n media.primary_metadata.title)\n self.Log('SEARCH - media.items - %s', media.items)\n self.Log('SEARCH - media.filename - %s', media.filename)\n self.Log('SEARCH - lang - %s', lang)\n self.Log('SEARCH - manual - %s', manual)\n\n if media.items[0].parts[0].file is not None:\n path_and_file = media.items[0].parts[0].file\n self.Log('SEARCH - File Path: %s' % path_and_file)\n filename = os.path.basename(path_and_file)\n dirname = os.path.dirname(path_and_file)\n\n metadata_file = os.path.join(dirname, '.' + filename + '.metadata')\n if os.path.isfile(metadata_file):\n self.Log('SEARCH - Exact Match \"%s\" == \"%s\"' %\n (filename, metadata_file))\n results.Append(MetadataSearchResult(id=metadata_file,\n name=filename,\n score=100, lang=lang))\n return\n\n def update(self, metadata, media, lang, force=False):\n self.Log('UPDATE CALLED')\n\n if media.items[0].parts[0].file is not None:\n file_path = media.items[0].parts[0].file\n self.Log('UPDATE - File Path: %s' % file_path)\n self.Log('UPDATE - metadata.id: %s' % metadata.id)\n\n metadata_dict = json.loads(Data.Load(metadata.id))\n\n # Set tagline to URL\n metadata.tagline = metadata_dict[\"description_url\"]\n video_title = metadata_dict[\"title\"]\n\n self.Log('UPDATE - video_title: \"%s\"' % video_title)\n\n # Update thumbnail and cover data\n valid_image_names = []\n i = 0\n self.Log(\"UPDATE - video_image_list\")\n try:\n coverPrefs = int(Prefs['cover'])\n except ValueError:\n coverPrefs = None\n\n try:\n for thumb_url, poster_url in \\\n metadata_dict[\"posters\"].iteritems():\n if coverPrefs and i > coverPrefs:\n break\n self.Log('UPDATE - thumb_url: \"%s\"' % thumb_url)\n self.Log('UPDATE - poster_url: \"%s\"' % poster_url)\n valid_image_names.append(poster_url)\n if poster_url not in metadata.posters:\n try:\n i += 1\n metadata.posters[poster_url] = \\\n Proxy.Preview(HTTP.Request(thumb_url),\n sort_order=i)\n except:\n pass\n metadata.posters.validate_keys(valid_image_names)\n except Exception as e:\n self.Log('UPDATE - Error getting posters: %s' % e)\n pass\n\n # Try to get description text\n about_text = metadata_dict[\"description\"]\n self.Log('UPDATE - About Text: %s', about_text)\n metadata.summary = about_text\n\n # Try to get release date\n # TODO: Release Date?\n\n # Try to get and process the video cast\n metadata.roles.clear()\n if \"actor\" in metadata_dict[\"roles\"]:\n actors = metadata_dict[\"roles\"][\"actor\"]\n self.Log('UPDATE - cast: \"%s\"' % actors)\n for actor in actors:\n actor = actor.strip()\n if (len(actor) > 0):\n role = metadata.roles.new()\n role.name = actor\n\n # Try to get and process the video genres\n metadata.genres.clear()\n genres = metadata_dict[\"categories\"]\n self.Log('UPDATE - video_genres: \"%s\"' % genres)\n for genre in genres:\n genre = genre.strip()\n if (len(genre) > 0):\n metadata.genres.add(genre)\n\n metadata.rating = metadata_dict[\"user_rating\"]\n metadata.content_rating = metadata_dict[\"content_rating\"]\n metadata.title = video_title\n metadata.studio = \"Bel Ami\"\n","sub_path":"LocalDotfile.bundle/Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"170281998","text":"class Node:\n def __init__(self, id):\n self.id = id\n self.parent = None\n self.left = None\n self.right = None\n self.height = None\n self.depth = None\n\n def type(self):\n if self.parent is None:\n return \"root\"\n if self.left is None and self.right is None:\n return \"leaf\"\n return \"internal node\"\n \n def get_parent_id(self):\n if self.parent is None:\n return -1\n return self.parent.id\n \n def get_sibling_id(self):\n if self.parent is None:\n return -1\n if self.parent.left is not None and self.parent.left.id != self.id:\n return self.parent.left.id\n if self.parent.right is not None and self.parent.right.id != self.id:\n return self.parent.right.id\n return -1\n \n def get_degree(self):\n degree = 0\n if self.left is not None:\n degree += 1\n if self.right is not None:\n degree += 1\n return degree\n \n def get_height(self):\n if self.height is not None:\n return self.height\n \n height = 0\n if self.left is not None:\n height = self.left.get_height() + 1\n if self.right is not None:\n right_height = self.right.get_height() + 1\n if height < right_height:\n height = right_height\n self.height = height\n return height\n\n def get_depth(self):\n if self.depth is not None:\n return self.depth\n depth = 0\n if self.parent is not None:\n depth = self.parent.get_depth() + 1\n self.depth = depth\n return depth\n\n def __str__(self):\n return \"node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}\".format(\n self.id, self.get_parent_id(), self.get_sibling_id(), self.get_degree(), self.get_depth(), self.get_height(), self.type()\n )\n\n\n# ALDS1_7_A: 2分木\ndef main():\n n = int(input())\n nodes = [ Node(i) for i in range(0, n)]\n for _ in range(0, n):\n items = [int(v) for v in input().split(\" \")]\n id = items[0]\n left = items[1]\n right = items[2]\n node = nodes[id]\n if left != -1:\n left_node = nodes[left]\n left_node.parent = node\n node.left = left_node\n if right != -1:\n right_node = nodes[right]\n right_node.parent = node\n node.right = right_node\n for n in nodes:\n print(str(n))\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"aoj/src/ALDS1_7_B/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397723966","text":"'''\nUnit2 Lesson3: Linear Regression and Correlation\n'''\n\nimport pandas as pd\nimport plots\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nimport numpy as np\n\nds_loans = pd.read_csv(\"loansData.csv\")\n# print(ds_loans.head(5))\nprint(ds_loans.info())\nds_loans = ds_loans.dropna()\n\nfico = \"FICO.Score\"\nfico_name = fico.replace(\".\", \" \")\nint_rate = \"Interest.Rate\"\nint_rate_name = int_rate.replace(\".\", \" \")\nlength = \"Loan.Length\"\nlength_name = length.replace(\".\", \" \")\namt_req = \"Amount.Requested\"\namt_req_name = amt_req.replace(\".\", \" \")\nincome = \"Monthly.Income\"\nincome_name = income.replace(\".\", \" \")\n\nds_loans[fico] = ds_loans[\"FICO.Range\"].map(lambda x: int(str(x).rstrip().split(\"-\")[0]))\nds_loans[int_rate] = ds_loans[int_rate].map(lambda x: float(str(x).rstrip()[:-1])/100)\nds_loans[length] = ds_loans[length].map(lambda x: int(str(x).rstrip().split(\" \")[0]))\n\nds_loans.to_csv(\"loansData_clean.csv\", header=True, index=False)\n\n# for col in [fico, int_rate, length]:\n # print(ds_loans[col][:5])\ndef base_data_plots():\n # plots.all_plots(ds_loans[fico], \"Fico Scores\", \"no unit\")\n # plots.all_plots(ds_loans[int_rate], \"Interest Rates\", \"%\")\n # plots.all_plots(ds_loans[length], \"Loan Length\", \"months\")\n fig = plt.figure(\"Base data\")\n ax1 = fig.add_subplot(221)\n ax1.hist(ds_loans[fico])\n ax1.set_title(\"FICO scores\")\n ax2 = fig.add_subplot(222)\n ax2.hist(ds_loans[int_rate])\n ax2.set_title(\"Interest Rate\")\n ax3 = fig.add_subplot(223)\n ax3.hist(ds_loans[length])\n ax3.set_title(\"Loan Length (months)\")\n plt.show()\n\n# base_data_plots()\n\ndef scatter_matrix_plot():\n # spm = pd.scatter_matrix(ds_loans, figsize=(10,10), diagonal='hist', alpha=0.05)\n spm_reduced = pd.scatter_matrix(ds_loans[[fico, int_rate, length, amt_req, income]], figsize=(10,10), diagonal='hist', alpha=0.05)\n plt.show()\n \n# scatter_matrix_plot()\n\n#y=interest rate, x1=FICO score, x2=Loan amount\n#transpose to have data in a vertical vector form\ny = np.matrix(ds_loans[int_rate]).transpose()\nx1 = np.matrix(ds_loans[fico]).transpose()\nx2 = np.matrix(ds_loans[amt_req]).transpose()\n#create a single matrix from x1 and x2\nx = np.column_stack([x1, x2])\n#add a constant to x to have the full equation: y = a1*x1 + a2*x2 + b\nX = sm.add_constant(x)\n\n#create the linear model and fit\nmodel = sm.OLS(y, X).fit() #OLS: Ordinary Least Square\nprint(\"\\nInterest_Rate = Cst + a1*Fico + a2*Loan_Amount:\\n\")\nprint(model.summary())\n# print(dir(model))\n\n#get model parameters\n(cst, a1, a2) = (model.params[0], model.params[1], model.params[2])\nprint(\"\\nInterest_Rate = Cst + a1*Fico + a2*Loan_Amount\")\nprint(\"\\nModel parameters:\\n\\tCst = {0}\\n\\ta1 = {1}\\n\\ta2 = {2}\".format(cst, a1, a2))\n\n#create a modeled interest rate\nds_loans[\"Predicted_interest_rate\"] = cst + a1*x1 + a2*x2\n# int_rate_model = cst + a1*x1 + a2*x2\ndef scatter_data_vs_model(predicted, ylabel):\n plt.scatter(ds_loans[int_rate], predicted)\n # plt.plot(ds_loans[int_rate], ds_loans[int_rate], color='r')\n plt.plot([0, 0.3], [0, 0.3], color='r', linewidth=2)\n plt.xlim([0, 0.3])\n plt.ylim([0, 0.3])\n plt.xlabel(\"Interest rate from data\")\n plt.ylabel(ylabel)\n\n# scatter_data_vs_model(ds_loans[\"Predicted_interest_rate\"], \"Model1\")\n# plt.show()\n \n#Linear regression with one more input: monthly income\nx3 = np.matrix(ds_loans[income]).transpose()\nx_2 = np.column_stack([x1, x2, x3])\nX_2 = sm.add_constant(x_2)\nmodel_2 = sm.OLS(y, X_2).fit()\nprint(model_2.summary())\n(cst_2, a1_2, a2_2, a3_2) = (model_2.params[0], model_2.params[1], model_2.params[2], model_2.params[3])\nprint(\"\\nInterest_Rate = Cst + a1*Fico + a2*Loan_Amount + a3*Montthly_Income\")\nprint(\"\\nModel parameters:\\n\\tCst = {0}\\n\\ta1 = {1}\\n\\ta2 = {2}\\n\\ta3 = {3}\".format(cst_2, a1_2, a2_2, a3_2))\nds_loans[\"Predicted_interest_rate_2\"] = cst_2 + a1_2*x1 + a2_2*x2 + a3_2*x3\n# scatter_data_vs_model(ds_loans[\"Predicted_interest_rate_2\"], \"Model2\")\n# plt.show()\n# print(model_2.)\n\nfig = plt.figure()\nplt.subplot(1,2,1)\nscatter_data_vs_model(ds_loans[\"Predicted_interest_rate\"], \"Model1 - LR(FICO, Loan Amount)\")\nfig.text(.15, .83, \"R^2 = {0}\".format(round(model.rsquared, 4)))\nplt.subplot(1,2,2)\nscatter_data_vs_model(ds_loans[\"Predicted_interest_rate_2\"], \"Model2 - LR(FICO, Loan Amount, Monthly Income)\")\nfig.text(.58, .83, \"R^2 = {0}\".format(round(model_2.rsquared, 4)))\nplt.show()","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"421401364","text":"import scrapy\nimport json\nimport re\nimport io\n\n\nclass QuotesSpider(scrapy.Spider):\n name = \"quotes\"\n\n start_urls = []\n\n baseurl = 'https://www.margonem.pl/?task=profile&id='\n\n json_file = open('./tutorial/general_stats/id_list_total.json')\n json_str = json_file.read()\n json_data = json.loads(json_str)\n\n last_id_from_json = json_data[-1]\n\n for i in json_data:\n start_urls.append(baseurl+str(i))\n\n for i in range(last_id_from_json+1,9130000):\n start_urls.append(baseurl+str(i))\n\n def parse(self, response):\n page = response.url.split(\"=\")[-1]\n\n wsp = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[7]/div/text()').get()\n wsp = wsp[-len(wsp):-4] # removing unnecessary \" [?]\"\n\n posts = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[5]/div/text()').get()\n\n function = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[1]/div/text()').get()\n \n rep = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[6]/div/text()').get()\n\n created = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[3]/div/text()').get()\n created = created.split(\" \")[0]\n\n lastlogin = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[4]/div/text()').get()\n\n nick = response.xpath('//p[@id=\"nick\"]/@tip').get()\n\n text = response.xpath('//body').extract()\n\n #bany\n found_or_no = [m.start() for m in re.finditer('\"color:red\">Konto czasowo zablokowane', str(text))]\n if not found_or_no:\n status = \" \"\n else:\n status = \"temp ban\"\n\n found_or_no = [m.start() for m in re.finditer('\"color:red\">Konto zablokowane', str(text))]\n if found_or_no:\n status = \"perm ban\"\n\n found_or_no = [m.start() for m in re.finditer('\"color:red\">Aktywny knebel na forum', str(text))]\n if found_or_no:\n status = \"knebel\"\n\n #kb\n found_or_no = [m.start() for m in re.finditer('<div id=\"inside_kb\"', str(text))]\n if not found_or_no:\n kb = 0\n else:\n kb = 1\n\n found_or_no = [m.start() for m in re.finditer('style=\"background-image: url\\(\\\\\\\\\\'/obrazki/postacie//crimson', str(text))]\n if found_or_no:\n kb = 1\n\n yield{\n 'id': int(page),\n 'posts': int(posts),\n 'rep': int(rep),\n 'wsp': float(wsp),\n 'created': created, \n 'nick': nick, \n 'function': function,\n 'status': status,\n 'kb': kb,\n 'lastlogin': lastlogin,\n }\n\n","sub_path":"tutorial/spiders/profile_scraper.py","file_name":"profile_scraper.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53246524","text":"\"\"\"\n pygments.lexers.shell\n ~~~~~~~~~~~~~~~~~~~~~\n\n Lexers for various shells.\n\n :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\n\nfrom pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, \\\n include, default, this, using, words, line_re\nfrom pygments.token import Punctuation, Whitespace, \\\n Text, Comment, Operator, Keyword, Name, String, Number, Generic\nfrom pygments.util import shebang_matches\n\n__all__ = ['BashLexer', 'BashSessionLexer', 'TcshLexer', 'BatchLexer',\n 'SlurmBashLexer', 'MSDOSSessionLexer', 'PowerShellLexer',\n 'PowerShellSessionLexer', 'TcshSessionLexer', 'FishShellLexer',\n 'ExeclineLexer']\n\n\nclass BashLexer(RegexLexer):\n \"\"\"\n Lexer for (ba|k|z|)sh shell scripts.\n\n .. versionadded:: 0.6\n \"\"\"\n\n name = 'Bash'\n aliases = ['bash', 'sh', 'ksh', 'zsh', 'shell']\n filenames = ['*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass',\n '*.exheres-0', '*.exlib', '*.zsh',\n '.bashrc', 'bashrc', '.bash_*', 'bash_*', 'zshrc', '.zshrc',\n '.kshrc', 'kshrc',\n 'PKGBUILD']\n mimetypes = ['application/x-sh', 'application/x-shellscript', 'text/x-shellscript']\n\n tokens = {\n 'root': [\n include('basic'),\n (r'`', String.Backtick, 'backticks'),\n include('data'),\n include('interp'),\n ],\n 'interp': [\n (r'\\$\\(\\(', Keyword, 'math'),\n (r'\\$\\(', Keyword, 'paren'),\n (r'\\$\\{#?', String.Interpol, 'curly'),\n (r'\\$[a-zA-Z_]\\w*', Name.Variable), # user variable\n (r'\\$(?:\\d+|[#$?!_*@-])', Name.Variable), # builtin\n (r'\\$', Text),\n ],\n 'basic': [\n (r'\\b(if|fi|else|while|in|do|done|for|then|return|function|case|'\n r'select|break|continue|until|esac|elif)(\\s*)\\b',\n bygroups(Keyword, Whitespace)),\n (r'\\b(alias|bg|bind|builtin|caller|cd|command|compgen|'\n r'complete|declare|dirs|disown|echo|enable|eval|exec|exit|'\n r'export|false|fc|fg|getopts|hash|help|history|jobs|kill|let|'\n r'local|logout|popd|printf|pushd|pwd|read|readonly|set|shift|'\n r'shopt|source|suspend|test|time|times|trap|true|type|typeset|'\n r'ulimit|umask|unalias|unset|wait)(?=[\\s)`])',\n Name.Builtin),\n (r'\\A#!.+\\n', Comment.Hashbang),\n (r'#.*\\n', Comment.Single),\n (r'\\\\[\\w\\W]', String.Escape),\n (r'(\\b\\w+)(\\s*)(\\+?=)', bygroups(Name.Variable, Whitespace, Operator)),\n (r'[\\[\\]{}()=]', Operator),\n (r'<<<', Operator), # here-string\n (r'<<-?\\s*(\\'?)\\\\?(\\w+)[\\w\\W]+?\\2', String),\n (r'&&|\\|\\|', Operator),\n ],\n 'data': [\n (r'(?s)\\$?\"(\\\\.|[^\"\\\\$])*\"', String.Double),\n (r'\"', String.Double, 'string'),\n (r\"(?s)\\$'(\\\\\\\\|\\\\[0-7]+|\\\\.|[^'\\\\])*'\", String.Single),\n (r\"(?s)'.*?'\", String.Single),\n (r';', Punctuation),\n (r'&', Punctuation),\n (r'\\|', Punctuation),\n (r'\\s+', Whitespace),\n (r'\\d+\\b', Number),\n (r'[^=\\s\\[\\]{}()$\"\\'`\\\\<&|;]+', Text),\n (r'<', Text),\n ],\n 'string': [\n (r'\"', String.Double, '#pop'),\n (r'(?s)(\\\\\\\\|\\\\[0-7]+|\\\\.|[^\"\\\\$])+', String.Double),\n include('interp'),\n ],\n 'curly': [\n (r'\\}', String.Interpol, '#pop'),\n (r':-', Keyword),\n (r'\\w+', Name.Variable),\n (r'[^}:\"\\'`$\\\\]+', Punctuation),\n (r':', Punctuation),\n include('root'),\n ],\n 'paren': [\n (r'\\)', Keyword, '#pop'),\n include('root'),\n ],\n 'math': [\n (r'\\)\\)', Keyword, '#pop'),\n (r'\\*\\*|\\|\\||<<|>>|[-+*/%^|&<>]', Operator),\n (r'\\d+#[\\da-zA-Z]+', Number),\n (r'\\d+#(?! )', Number),\n (r'0[xX][\\da-fA-F]+', Number),\n (r'\\d+', Number),\n (r'[a-zA-Z_]\\w*', Name.Variable), # user variable\n include('root'),\n ],\n 'backticks': [\n (r'`', String.Backtick, '#pop'),\n include('root'),\n ],\n }\n\n def analyse_text(text):\n if shebang_matches(text, r'(ba|z|)sh'):\n return 1\n if text.startswith('$ '):\n return 0.2\n\n\nclass SlurmBashLexer(BashLexer):\n \"\"\"\n Lexer for (ba|k|z|)sh Slurm scripts.\n\n .. versionadded:: 2.4\n \"\"\"\n\n name = 'Slurm'\n aliases = ['slurm', 'sbatch']\n filenames = ['*.sl']\n mimetypes = []\n EXTRA_KEYWORDS = {'srun'}\n\n def get_tokens_unprocessed(self, text):\n for index, token, value in BashLexer.get_tokens_unprocessed(self, text):\n if token is Text and value in self.EXTRA_KEYWORDS:\n yield index, Name.Builtin, value\n elif token is Comment.Single and 'SBATCH' in value:\n yield index, Keyword.Pseudo, value\n else:\n yield index, token, value\n\n\nclass ShellSessionBaseLexer(Lexer):\n \"\"\"\n Base lexer for shell sessions.\n\n .. versionadded:: 2.1\n \"\"\"\n\n _bare_continuation = False\n _venv = re.compile(r'^(\\([^)]*\\))(\\s*)')\n\n def get_tokens_unprocessed(self, text):\n innerlexer = self._innerLexerCls(**self.options)\n\n pos = 0\n curcode = ''\n insertions = []\n backslash_continuation = False\n\n for match in line_re.finditer(text):\n line = match.group()\n\n venv_match = self._venv.match(line)\n if venv_match:\n venv = venv_match.group(1)\n venv_whitespace = venv_match.group(2)\n insertions.append((len(curcode),\n [(0, Generic.Prompt.VirtualEnv, venv)]))\n if venv_whitespace:\n insertions.append((len(curcode),\n [(0, Text, venv_whitespace)]))\n line = line[venv_match.end():]\n\n m = self._ps1rgx.match(line)\n if m:\n # To support output lexers (say diff output), the output\n # needs to be broken by prompts whenever the output lexer\n # changes.\n if not insertions:\n pos = match.start()\n\n insertions.append((len(curcode),\n [(0, Generic.Prompt, m.group(1))]))\n curcode += m.group(2)\n backslash_continuation = curcode.endswith('\\\\\\n')\n elif backslash_continuation:\n if line.startswith(self._ps2):\n insertions.append((len(curcode),\n [(0, Generic.Prompt,\n line[:len(self._ps2)])]))\n curcode += line[len(self._ps2):]\n else:\n curcode += line\n backslash_continuation = curcode.endswith('\\\\\\n')\n elif self._bare_continuation and line.startswith(self._ps2):\n insertions.append((len(curcode),\n [(0, Generic.Prompt,\n line[:len(self._ps2)])]))\n curcode += line[len(self._ps2):]\n else:\n if insertions:\n toks = innerlexer.get_tokens_unprocessed(curcode)\n for i, t, v in do_insertions(insertions, toks):\n yield pos+i, t, v\n yield match.start(), Generic.Output, line\n insertions = []\n curcode = ''\n if insertions:\n for i, t, v in do_insertions(insertions,\n innerlexer.get_tokens_unprocessed(curcode)):\n yield pos+i, t, v\n\n\nclass BashSessionLexer(ShellSessionBaseLexer):\n \"\"\"\n Lexer for Bash shell sessions, i.e. command lines, including a\n prompt, interspersed with output.\n\n .. versionadded:: 1.1\n \"\"\"\n\n name = 'Bash Session'\n aliases = ['console', 'shell-session']\n filenames = ['*.sh-session', '*.shell-session']\n mimetypes = ['application/x-shell-session', 'application/x-sh-session']\n\n _innerLexerCls = BashLexer\n _ps1rgx = re.compile(\n r'^((?:(?:\\[.*?\\])|(?:\\(\\S+\\))?(?:| |sh\\S*?|\\w+\\S+[@:]\\S+(?:\\s+\\S+)' \\\n r'?|\\[\\S+[@:][^\\n]+\\].+))\\s*[$#%]\\s*)(.*\\n?)')\n _ps2 = '> '\n\n\nclass BatchLexer(RegexLexer):\n \"\"\"\n Lexer for the DOS/Windows Batch file format.\n\n .. versionadded:: 0.7\n \"\"\"\n name = 'Batchfile'\n aliases = ['batch', 'bat', 'dosbatch', 'winbatch']\n filenames = ['*.bat', '*.cmd']\n mimetypes = ['application/x-dos-batch']\n\n flags = re.MULTILINE | re.IGNORECASE\n\n _nl = r'\\n\\x1a'\n _punct = r'&<>|'\n _ws = r'\\t\\v\\f\\r ,;=\\xa0'\n _nlws = r'\\s\\x1a\\xa0,;='\n _space = r'(?:(?:(?:\\^[%s])?[%s])+)' % (_nl, _ws)\n _keyword_terminator = (r'(?=(?:\\^[%s]?)?[%s+./:[\\\\\\]]|[%s%s(])' %\n (_nl, _ws, _nl, _punct))\n _token_terminator = r'(?=\\^?[%s]|[%s%s])' % (_ws, _punct, _nl)\n _start_label = r'((?:(?<=^[^:])|^[^:]?)[%s]*)(:)' % _ws\n _label = r'(?:(?:[^%s%s+:^]|\\^[%s]?[\\w\\W])*)' % (_nlws, _punct, _nl)\n _label_compound = r'(?:(?:[^%s%s+:^)]|\\^[%s]?[^)])*)' % (_nlws, _punct, _nl)\n _number = r'(?:-?(?:0[0-7]+|0x[\\da-f]+|\\d+)%s)' % _token_terminator\n _opword = r'(?:equ|geq|gtr|leq|lss|neq)'\n _string = r'(?:\"[^%s\"]*(?:\"|(?=[%s])))' % (_nl, _nl)\n _variable = (r'(?:(?:%%(?:\\*|(?:~[a-z]*(?:\\$[^:]+:)?)?\\d|'\n r'[^%%:%s]+(?::(?:~(?:-?\\d+)?(?:,(?:-?\\d+)?)?|(?:[^%%%s^]|'\n r'\\^[^%%%s])[^=%s]*=(?:[^%%%s^]|\\^[^%%%s])*)?)?%%))|'\n r'(?:\\^?![^!:%s]+(?::(?:~(?:-?\\d+)?(?:,(?:-?\\d+)?)?|(?:'\n r'[^!%s^]|\\^[^!%s])[^=%s]*=(?:[^!%s^]|\\^[^!%s])*)?)?\\^?!))' %\n (_nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl))\n _core_token = r'(?:(?:(?:\\^[%s]?)?[^\"%s%s])+)' % (_nl, _nlws, _punct)\n _core_token_compound = r'(?:(?:(?:\\^[%s]?)?[^\"%s%s)])+)' % (_nl, _nlws, _punct)\n _token = r'(?:[%s]+|%s)' % (_punct, _core_token)\n _token_compound = r'(?:[%s]+|%s)' % (_punct, _core_token_compound)\n _stoken = (r'(?:[%s]+|(?:%s|%s|%s)+)' %\n (_punct, _string, _variable, _core_token))\n\n def _make_begin_state(compound, _core_token=_core_token,\n _core_token_compound=_core_token_compound,\n _keyword_terminator=_keyword_terminator,\n _nl=_nl, _punct=_punct, _string=_string,\n _space=_space, _start_label=_start_label,\n _stoken=_stoken, _token_terminator=_token_terminator,\n _variable=_variable, _ws=_ws):\n rest = '(?:%s|%s|[^\"%%%s%s%s])*' % (_string, _variable, _nl, _punct,\n ')' if compound else '')\n rest_of_line = r'(?:(?:[^%s^]|\\^[%s]?[\\w\\W])*)' % (_nl, _nl)\n rest_of_line_compound = r'(?:(?:[^%s^)]|\\^[%s]?[^)])*)' % (_nl, _nl)\n set_space = r'((?:(?:\\^[%s]?)?[^\\S\\n])*)' % _nl\n suffix = ''\n if compound:\n _keyword_terminator = r'(?:(?=\\))|%s)' % _keyword_terminator\n _token_terminator = r'(?:(?=\\))|%s)' % _token_terminator\n suffix = '/compound'\n return [\n ((r'\\)', Punctuation, '#pop') if compound else\n (r'\\)((?=\\()|%s)%s' % (_token_terminator, rest_of_line),\n Comment.Single)),\n (r'(?=%s)' % _start_label, Text, 'follow%s' % suffix),\n (_space, using(this, state='text')),\n include('redirect%s' % suffix),\n (r'[%s]+' % _nl, Text),\n (r'\\(', Punctuation, 'root/compound'),\n (r'@+', Punctuation),\n (r'((?:for|if|rem)(?:(?=(?:\\^[%s]?)?/)|(?:(?!\\^)|'\n r'(?<=m))(?:(?=\\()|%s)))(%s?%s?(?:\\^[%s]?)?/(?:\\^[%s]?)?\\?)' %\n (_nl, _token_terminator, _space,\n _core_token_compound if compound else _core_token, _nl, _nl),\n bygroups(Keyword, using(this, state='text')),\n 'follow%s' % suffix),\n (r'(goto%s)(%s(?:\\^[%s]?)?/(?:\\^[%s]?)?\\?%s)' %\n (_keyword_terminator, rest, _nl, _nl, rest),\n bygroups(Keyword, using(this, state='text')),\n 'follow%s' % suffix),\n (words(('assoc', 'break', 'cd', 'chdir', 'cls', 'color', 'copy',\n 'date', 'del', 'dir', 'dpath', 'echo', 'endlocal', 'erase',\n 'exit', 'ftype', 'keys', 'md', 'mkdir', 'mklink', 'move',\n 'path', 'pause', 'popd', 'prompt', 'pushd', 'rd', 'ren',\n 'rename', 'rmdir', 'setlocal', 'shift', 'start', 'time',\n 'title', 'type', 'ver', 'verify', 'vol'),\n suffix=_keyword_terminator), Keyword, 'follow%s' % suffix),\n (r'(call)(%s?)(:)' % _space,\n bygroups(Keyword, using(this, state='text'), Punctuation),\n 'call%s' % suffix),\n (r'call%s' % _keyword_terminator, Keyword),\n (r'(for%s(?!\\^))(%s)(/f%s)' %\n (_token_terminator, _space, _token_terminator),\n bygroups(Keyword, using(this, state='text'), Keyword),\n ('for/f', 'for')),\n (r'(for%s(?!\\^))(%s)(/l%s)' %\n (_token_terminator, _space, _token_terminator),\n bygroups(Keyword, using(this, state='text'), Keyword),\n ('for/l', 'for')),\n (r'for%s(?!\\^)' % _token_terminator, Keyword, ('for2', 'for')),\n (r'(goto%s)(%s?)(:?)' % (_keyword_terminator, _space),\n bygroups(Keyword, using(this, state='text'), Punctuation),\n 'label%s' % suffix),\n (r'(if(?:(?=\\()|%s)(?!\\^))(%s?)((?:/i%s)?)(%s?)((?:not%s)?)(%s?)' %\n (_token_terminator, _space, _token_terminator, _space,\n _token_terminator, _space),\n bygroups(Keyword, using(this, state='text'), Keyword,\n using(this, state='text'), Keyword,\n using(this, state='text')), ('(?', 'if')),\n (r'rem(((?=\\()|%s)%s?%s?.*|%s%s)' %\n (_token_terminator, _space, _stoken, _keyword_terminator,\n rest_of_line_compound if compound else rest_of_line),\n Comment.Single, 'follow%s' % suffix),\n (r'(set%s)%s(/a)' % (_keyword_terminator, set_space),\n bygroups(Keyword, using(this, state='text'), Keyword),\n 'arithmetic%s' % suffix),\n (r'(set%s)%s((?:/p)?)%s((?:(?:(?:\\^[%s]?)?[^\"%s%s^=%s]|'\n r'\\^[%s]?[^\"=])+)?)((?:(?:\\^[%s]?)?=)?)' %\n (_keyword_terminator, set_space, set_space, _nl, _nl, _punct,\n ')' if compound else '', _nl, _nl),\n bygroups(Keyword, using(this, state='text'), Keyword,\n using(this, state='text'), using(this, state='variable'),\n Punctuation),\n 'follow%s' % suffix),\n default('follow%s' % suffix)\n ]\n\n def _make_follow_state(compound, _label=_label,\n _label_compound=_label_compound, _nl=_nl,\n _space=_space, _start_label=_start_label,\n _token=_token, _token_compound=_token_compound,\n _ws=_ws):\n suffix = '/compound' if compound else ''\n state = []\n if compound:\n state.append((r'(?=\\))', Text, '#pop'))\n state += [\n (r'%s([%s]*)(%s)(.*)' %\n (_start_label, _ws, _label_compound if compound else _label),\n bygroups(Text, Punctuation, Text, Name.Label, Comment.Single)),\n include('redirect%s' % suffix),\n (r'(?=[%s])' % _nl, Text, '#pop'),\n (r'\\|\\|?|&&?', Punctuation, '#pop'),\n include('text')\n ]\n return state\n\n def _make_arithmetic_state(compound, _nl=_nl, _punct=_punct,\n _string=_string, _variable=_variable,\n _ws=_ws, _nlws=_nlws):\n op = r'=+\\-*/!~'\n state = []\n if compound:\n state.append((r'(?=\\))', Text, '#pop'))\n state += [\n (r'0[0-7]+', Number.Oct),\n (r'0x[\\da-f]+', Number.Hex),\n (r'\\d+', Number.Integer),\n (r'[(),]+', Punctuation),\n (r'([%s]|%%|\\^\\^)+' % op, Operator),\n (r'(%s|%s|(\\^[%s]?)?[^()%s%%\\^\"%s%s]|\\^[%s]?%s)+' %\n (_string, _variable, _nl, op, _nlws, _punct, _nlws,\n r'[^)]' if compound else r'[\\w\\W]'),\n using(this, state='variable')),\n (r'(?=[\\x00|&])', Text, '#pop'),\n include('follow')\n ]\n return state\n\n def _make_call_state(compound, _label=_label,\n _label_compound=_label_compound):\n state = []\n if compound:\n state.append((r'(?=\\))', Text, '#pop'))\n state.append((r'(:?)(%s)' % (_label_compound if compound else _label),\n bygroups(Punctuation, Name.Label), '#pop'))\n return state\n\n def _make_label_state(compound, _label=_label,\n _label_compound=_label_compound, _nl=_nl,\n _punct=_punct, _string=_string, _variable=_variable):\n state = []\n if compound:\n state.append((r'(?=\\))', Text, '#pop'))\n state.append((r'(%s?)((?:%s|%s|\\^[%s]?%s|[^\"%%^%s%s%s])*)' %\n (_label_compound if compound else _label, _string,\n _variable, _nl, r'[^)]' if compound else r'[\\w\\W]', _nl,\n _punct, r')' if compound else ''),\n bygroups(Name.Label, Comment.Single), '#pop'))\n return state\n\n def _make_redirect_state(compound,\n _core_token_compound=_core_token_compound,\n _nl=_nl, _punct=_punct, _stoken=_stoken,\n _string=_string, _space=_space,\n _variable=_variable, _nlws=_nlws):\n stoken_compound = (r'(?:[%s]+|(?:%s|%s|%s)+)' %\n (_punct, _string, _variable, _core_token_compound))\n return [\n (r'((?:(?<=[%s])\\d)?)(>>?&|<&)([%s]*)(\\d)' %\n (_nlws, _nlws),\n bygroups(Number.Integer, Punctuation, Text, Number.Integer)),\n (r'((?:(?<=[%s])(?<!\\^[%s])\\d)?)(>>?|<)(%s?%s)' %\n (_nlws, _nl, _space, stoken_compound if compound else _stoken),\n bygroups(Number.Integer, Punctuation, using(this, state='text')))\n ]\n\n tokens = {\n 'root': _make_begin_state(False),\n 'follow': _make_follow_state(False),\n 'arithmetic': _make_arithmetic_state(False),\n 'call': _make_call_state(False),\n 'label': _make_label_state(False),\n 'redirect': _make_redirect_state(False),\n 'root/compound': _make_begin_state(True),\n 'follow/compound': _make_follow_state(True),\n 'arithmetic/compound': _make_arithmetic_state(True),\n 'call/compound': _make_call_state(True),\n 'label/compound': _make_label_state(True),\n 'redirect/compound': _make_redirect_state(True),\n 'variable-or-escape': [\n (_variable, Name.Variable),\n (r'%%%%|\\^[%s]?(\\^!|[\\w\\W])' % _nl, String.Escape)\n ],\n 'string': [\n (r'\"', String.Double, '#pop'),\n (_variable, Name.Variable),\n (r'\\^!|%%', String.Escape),\n (r'[^\"%%^%s]+|[%%^]' % _nl, String.Double),\n default('#pop')\n ],\n 'sqstring': [\n include('variable-or-escape'),\n (r'[^%]+|%', String.Single)\n ],\n 'bqstring': [\n include('variable-or-escape'),\n (r'[^%]+|%', String.Backtick)\n ],\n 'text': [\n (r'\"', String.Double, 'string'),\n include('variable-or-escape'),\n (r'[^\"%%^%s%s\\d)]+|.' % (_nlws, _punct), Text)\n ],\n 'variable': [\n (r'\"', String.Double, 'string'),\n include('variable-or-escape'),\n (r'[^\"%%^%s]+|.' % _nl, Name.Variable)\n ],\n 'for': [\n (r'(%s)(in)(%s)(\\()' % (_space, _space),\n bygroups(using(this, state='text'), Keyword,\n using(this, state='text'), Punctuation), '#pop'),\n include('follow')\n ],\n 'for2': [\n (r'\\)', Punctuation),\n (r'(%s)(do%s)' % (_space, _token_terminator),\n bygroups(using(this, state='text'), Keyword), '#pop'),\n (r'[%s]+' % _nl, Text),\n include('follow')\n ],\n 'for/f': [\n (r'(\")((?:%s|[^\"])*?\")([%s]*)(\\))' % (_variable, _nlws),\n bygroups(String.Double, using(this, state='string'), Text,\n Punctuation)),\n (r'\"', String.Double, ('#pop', 'for2', 'string')),\n (r\"('(?:%%%%|%s|[\\w\\W])*?')([%s]*)(\\))\" % (_variable, _nlws),\n bygroups(using(this, state='sqstring'), Text, Punctuation)),\n (r'(`(?:%%%%|%s|[\\w\\W])*?`)([%s]*)(\\))' % (_variable, _nlws),\n bygroups(using(this, state='bqstring'), Text, Punctuation)),\n include('for2')\n ],\n 'for/l': [\n (r'-?\\d+', Number.Integer),\n include('for2')\n ],\n 'if': [\n (r'((?:cmdextversion|errorlevel)%s)(%s)(\\d+)' %\n (_token_terminator, _space),\n bygroups(Keyword, using(this, state='text'),\n Number.Integer), '#pop'),\n (r'(defined%s)(%s)(%s)' % (_token_terminator, _space, _stoken),\n bygroups(Keyword, using(this, state='text'),\n using(this, state='variable')), '#pop'),\n (r'(exist%s)(%s%s)' % (_token_terminator, _space, _stoken),\n bygroups(Keyword, using(this, state='text')), '#pop'),\n (r'(%s%s)(%s)(%s%s)' % (_number, _space, _opword, _space, _number),\n bygroups(using(this, state='arithmetic'), Operator.Word,\n using(this, state='arithmetic')), '#pop'),\n (_stoken, using(this, state='text'), ('#pop', 'if2')),\n ],\n 'if2': [\n (r'(%s?)(==)(%s?%s)' % (_space, _space, _stoken),\n bygroups(using(this, state='text'), Operator,\n using(this, state='text')), '#pop'),\n (r'(%s)(%s)(%s%s)' % (_space, _opword, _space, _stoken),\n bygroups(using(this, state='text'), Operator.Word,\n using(this, state='text')), '#pop')\n ],\n '(?': [\n (_space, using(this, state='text')),\n (r'\\(', Punctuation, ('#pop', 'else?', 'root/compound')),\n default('#pop')\n ],\n 'else?': [\n (_space, using(this, state='text')),\n (r'else%s' % _token_terminator, Keyword, '#pop'),\n default('#pop')\n ]\n }\n\n\nclass MSDOSSessionLexer(ShellSessionBaseLexer):\n \"\"\"\n Lexer for MS DOS shell sessions, i.e. command lines, including a\n prompt, interspersed with output.\n\n .. versionadded:: 2.1\n \"\"\"\n\n name = 'MSDOS Session'\n aliases = ['doscon']\n filenames = []\n mimetypes = []\n\n _innerLexerCls = BatchLexer\n _ps1rgx = re.compile(r'^([^>]*>)(.*\\n?)')\n _ps2 = 'More? '\n\n\nclass TcshLexer(RegexLexer):\n \"\"\"\n Lexer for tcsh scripts.\n\n .. versionadded:: 0.10\n \"\"\"\n\n name = 'Tcsh'\n aliases = ['tcsh', 'csh']\n filenames = ['*.tcsh', '*.csh']\n mimetypes = ['application/x-csh']\n\n tokens = {\n 'root': [\n include('basic'),\n (r'\\$\\(', Keyword, 'paren'),\n (r'\\$\\{#?', Keyword, 'curly'),\n (r'`', String.Backtick, 'backticks'),\n include('data'),\n ],\n 'basic': [\n (r'\\b(if|endif|else|while|then|foreach|case|default|'\n r'break|continue|goto|breaksw|end|switch|endsw)\\s*\\b',\n Keyword),\n (r'\\b(alias|alloc|bg|bindkey|builtins|bye|caller|cd|chdir|'\n r'complete|dirs|echo|echotc|eval|exec|exit|fg|filetest|getxvers|'\n r'glob|getspath|hashstat|history|hup|inlib|jobs|kill|'\n r'limit|log|login|logout|ls-F|migrate|newgrp|nice|nohup|notify|'\n r'onintr|popd|printenv|pushd|rehash|repeat|rootnode|popd|pushd|'\n r'set|shift|sched|setenv|setpath|settc|setty|setxvers|shift|'\n r'source|stop|suspend|source|suspend|telltc|time|'\n r'umask|unalias|uncomplete|unhash|universe|unlimit|unset|unsetenv|'\n r'ver|wait|warp|watchlog|where|which)\\s*\\b',\n Name.Builtin),\n (r'#.*', Comment),\n (r'\\\\[\\w\\W]', String.Escape),\n (r'(\\b\\w+)(\\s*)(=)', bygroups(Name.Variable, Text, Operator)),\n (r'[\\[\\]{}()=]+', Operator),\n (r'<<\\s*(\\'?)\\\\?(\\w+)[\\w\\W]+?\\2', String),\n (r';', Punctuation),\n ],\n 'data': [\n (r'(?s)\"(\\\\\\\\|\\\\[0-7]+|\\\\.|[^\"\\\\])*\"', String.Double),\n (r\"(?s)'(\\\\\\\\|\\\\[0-7]+|\\\\.|[^'\\\\])*'\", String.Single),\n (r'\\s+', Text),\n (r'[^=\\s\\[\\]{}()$\"\\'`\\\\;#]+', Text),\n (r'\\d+(?= |\\Z)', Number),\n (r'\\$#?(\\w+|.)', Name.Variable),\n ],\n 'curly': [\n (r'\\}', Keyword, '#pop'),\n (r':-', Keyword),\n (r'\\w+', Name.Variable),\n (r'[^}:\"\\'`$]+', Punctuation),\n (r':', Punctuation),\n include('root'),\n ],\n 'paren': [\n (r'\\)', Keyword, '#pop'),\n include('root'),\n ],\n 'backticks': [\n (r'`', String.Backtick, '#pop'),\n include('root'),\n ],\n }\n\n\nclass TcshSessionLexer(ShellSessionBaseLexer):\n \"\"\"\n Lexer for Tcsh sessions, i.e. command lines, including a\n prompt, interspersed with output.\n\n .. versionadded:: 2.1\n \"\"\"\n\n name = 'Tcsh Session'\n aliases = ['tcshcon']\n filenames = []\n mimetypes = []\n\n _innerLexerCls = TcshLexer\n _ps1rgx = re.compile(r'^([^>]+>)(.*\\n?)')\n _ps2 = '? '\n\n\nclass PowerShellLexer(RegexLexer):\n \"\"\"\n For Windows PowerShell code.\n\n .. versionadded:: 1.5\n \"\"\"\n name = 'PowerShell'\n aliases = ['powershell', 'pwsh', 'posh', 'ps1', 'psm1']\n filenames = ['*.ps1', '*.psm1']\n mimetypes = ['text/x-powershell']\n\n flags = re.DOTALL | re.IGNORECASE | re.MULTILINE\n\n keywords = (\n 'while validateset validaterange validatepattern validatelength '\n 'validatecount until trap switch return ref process param parameter in '\n 'if global: local: function foreach for finally filter end elseif else '\n 'dynamicparam do default continue cmdletbinding break begin alias \\\\? '\n '% #script #private #local #global mandatory parametersetname position '\n 'valuefrompipeline valuefrompipelinebypropertyname '\n 'valuefromremainingarguments helpmessage try catch throw').split()\n\n operators = (\n 'and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle '\n 'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains '\n 'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt '\n 'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like '\n 'lt match ne not notcontains notlike notmatch or regex replace '\n 'wildcard').split()\n\n verbs = (\n 'write where watch wait use update unregister unpublish unprotect '\n 'unlock uninstall undo unblock trace test tee take sync switch '\n 'suspend submit stop step start split sort skip show set send select '\n 'search scroll save revoke resume restore restart resolve resize '\n 'reset request repair rename remove register redo receive read push '\n 'publish protect pop ping out optimize open new move mount merge '\n 'measure lock limit join invoke install initialize import hide group '\n 'grant get format foreach find export expand exit enter enable edit '\n 'dismount disconnect disable deny debug cxnew copy convertto '\n 'convertfrom convert connect confirm compress complete compare close '\n 'clear checkpoint block backup assert approve aggregate add').split()\n\n aliases_ = (\n 'ac asnp cat cd cfs chdir clc clear clhy cli clp cls clv cnsn '\n 'compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo epal '\n 'epcsv epsn erase etsn exsn fc fhx fl foreach ft fw gal gbp gc gci gcm '\n 'gcs gdr ghy gi gjb gl gm gmo gp gps gpv group gsn gsnp gsv gu gv gwmi '\n 'h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp '\n 'ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv '\n 'oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo '\n 'rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc select '\n 'set shcm si sl sleep sls sort sp spjb spps spsv start sujb sv swmi tee '\n 'trcm type wget where wjb write').split()\n\n commenthelp = (\n 'component description example externalhelp forwardhelpcategory '\n 'forwardhelptargetname functionality inputs link '\n 'notes outputs parameter remotehelprunspace role synopsis').split()\n\n tokens = {\n 'root': [\n # we need to count pairs of parentheses for correct highlight\n # of '$(...)' blocks in strings\n (r'\\(', Punctuation, 'child'),\n (r'\\s+', Text),\n (r'^(\\s*#[#\\s]*)(\\.(?:%s))([^\\n]*$)' % '|'.join(commenthelp),\n bygroups(Comment, String.Doc, Comment)),\n (r'#[^\\n]*?$', Comment),\n (r'(<|<)#', Comment.Multiline, 'multline'),\n (r'@\"\\n', String.Heredoc, 'heredoc-double'),\n (r\"@'\\n.*?\\n'@\", String.Heredoc),\n # escaped syntax\n (r'`[\\'\"$@-]', Punctuation),\n (r'\"', String.Double, 'string'),\n (r\"'([^']|'')*'\", String.Single),\n (r'(\\$|@@|@)((global|script|private|env):)?\\w+',\n Name.Variable),\n (r'(%s)\\b' % '|'.join(keywords), Keyword),\n (r'-(%s)\\b' % '|'.join(operators), Operator),\n (r'(%s)-[a-z_]\\w*\\b' % '|'.join(verbs), Name.Builtin),\n (r'(%s)\\s' % '|'.join(aliases_), Name.Builtin),\n (r'\\[[a-z_\\[][\\w. `,\\[\\]]*\\]', Name.Constant), # .net [type]s\n (r'-[a-z_]\\w*', Name),\n (r'\\w+', Name),\n (r'[.,;:@{}\\[\\]$()=+*/\\\\&%!~?^`|<>-]', Punctuation),\n ],\n 'child': [\n (r'\\)', Punctuation, '#pop'),\n include('root'),\n ],\n 'multline': [\n (r'[^#&.]+', Comment.Multiline),\n (r'#(>|>)', Comment.Multiline, '#pop'),\n (r'\\.(%s)' % '|'.join(commenthelp), String.Doc),\n (r'[#&.]', Comment.Multiline),\n ],\n 'string': [\n (r\"`[0abfnrtv'\\\"$`]\", String.Escape),\n (r'[^$`\"]+', String.Double),\n (r'\\$\\(', Punctuation, 'child'),\n (r'\"\"', String.Double),\n (r'[`$]', String.Double),\n (r'\"', String.Double, '#pop'),\n ],\n 'heredoc-double': [\n (r'\\n\"@', String.Heredoc, '#pop'),\n (r'\\$\\(', Punctuation, 'child'),\n (r'[^@\\n]+\"]', String.Heredoc),\n (r\".\", String.Heredoc),\n ]\n }\n\n\nclass PowerShellSessionLexer(ShellSessionBaseLexer):\n \"\"\"\n Lexer for PowerShell sessions, i.e. command lines, including a\n prompt, interspersed with output.\n\n .. versionadded:: 2.1\n \"\"\"\n\n name = 'PowerShell Session'\n aliases = ['pwsh-session', 'ps1con']\n filenames = []\n mimetypes = []\n\n _innerLexerCls = PowerShellLexer\n _bare_continuation = True\n _ps1rgx = re.compile(r'^((?:\\[[^]]+\\]: )?PS[^>]*> ?)(.*\\n?)')\n _ps2 = '> '\n\n\nclass FishShellLexer(RegexLexer):\n \"\"\"\n Lexer for Fish shell scripts.\n\n .. versionadded:: 2.1\n \"\"\"\n\n name = 'Fish'\n aliases = ['fish', 'fishshell']\n filenames = ['*.fish', '*.load']\n mimetypes = ['application/x-fish']\n\n tokens = {\n 'root': [\n include('basic'),\n include('data'),\n include('interp'),\n ],\n 'interp': [\n (r'\\$\\(\\(', Keyword, 'math'),\n (r'\\(', Keyword, 'paren'),\n (r'\\$#?(\\w+|.)', Name.Variable),\n ],\n 'basic': [\n (r'\\b(begin|end|if|else|while|break|for|in|return|function|block|'\n r'case|continue|switch|not|and|or|set|echo|exit|pwd|true|false|'\n r'cd|count|test)(\\s*)\\b',\n bygroups(Keyword, Text)),\n (r'\\b(alias|bg|bind|breakpoint|builtin|command|commandline|'\n r'complete|contains|dirh|dirs|emit|eval|exec|fg|fish|fish_config|'\n r'fish_indent|fish_pager|fish_prompt|fish_right_prompt|'\n r'fish_update_completions|fishd|funced|funcsave|functions|help|'\n r'history|isatty|jobs|math|mimedb|nextd|open|popd|prevd|psub|'\n r'pushd|random|read|set_color|source|status|trap|type|ulimit|'\n r'umask|vared|fc|getopts|hash|kill|printf|time|wait)\\s*\\b(?!\\.)',\n Name.Builtin),\n (r'#.*\\n', Comment),\n (r'\\\\[\\w\\W]', String.Escape),\n (r'(\\b\\w+)(\\s*)(=)', bygroups(Name.Variable, Whitespace, Operator)),\n (r'[\\[\\]()=]', Operator),\n (r'<<-?\\s*(\\'?)\\\\?(\\w+)[\\w\\W]+?\\2', String),\n ],\n 'data': [\n (r'(?s)\\$?\"(\\\\\\\\|\\\\[0-7]+|\\\\.|[^\"\\\\$])*\"', String.Double),\n (r'\"', String.Double, 'string'),\n (r\"(?s)\\$'(\\\\\\\\|\\\\[0-7]+|\\\\.|[^'\\\\])*'\", String.Single),\n (r\"(?s)'.*?'\", String.Single),\n (r';', Punctuation),\n (r'&|\\||\\^|<|>', Operator),\n (r'\\s+', Text),\n (r'\\d+(?= |\\Z)', Number),\n (r'[^=\\s\\[\\]{}()$\"\\'`\\\\<&|;]+', Text),\n ],\n 'string': [\n (r'\"', String.Double, '#pop'),\n (r'(?s)(\\\\\\\\|\\\\[0-7]+|\\\\.|[^\"\\\\$])+', String.Double),\n include('interp'),\n ],\n 'paren': [\n (r'\\)', Keyword, '#pop'),\n include('root'),\n ],\n 'math': [\n (r'\\)\\)', Keyword, '#pop'),\n (r'[-+*/%^|&]|\\*\\*|\\|\\|', Operator),\n (r'\\d+#\\d+', Number),\n (r'\\d+#(?! )', Number),\n (r'\\d+', Number),\n include('root'),\n ],\n }\n\nclass ExeclineLexer(RegexLexer):\n \"\"\"\n Lexer for Laurent Bercot's execline language\n (https://skarnet.org/software/execline).\n\n .. versionadded:: 2.7\n \"\"\"\n\n name = 'execline'\n aliases = ['execline']\n filenames = ['*.exec']\n\n tokens = {\n 'root': [\n include('basic'),\n include('data'),\n include('interp')\n ],\n 'interp': [\n (r'\\$\\{', String.Interpol, 'curly'),\n (r'\\$[\\w@#]+', Name.Variable), # user variable\n (r'\\$', Text),\n ],\n 'basic': [\n (r'\\b(background|backtick|cd|define|dollarat|elgetopt|'\n r'elgetpositionals|elglob|emptyenv|envfile|exec|execlineb|'\n r'exit|export|fdblock|fdclose|fdmove|fdreserve|fdswap|'\n r'forbacktickx|foreground|forstdin|forx|getcwd|getpid|heredoc|'\n r'homeof|if|ifelse|ifte|ifthenelse|importas|loopwhilex|'\n r'multidefine|multisubstitute|pipeline|piperw|posix-cd|'\n r'redirfd|runblock|shift|trap|tryexec|umask|unexport|wait|'\n r'withstdinas)\\b', Name.Builtin),\n (r'\\A#!.+\\n', Comment.Hashbang),\n (r'#.*\\n', Comment.Single),\n (r'[{}]', Operator)\n ],\n 'data': [\n (r'(?s)\"(\\\\.|[^\"\\\\$])*\"', String.Double),\n (r'\"', String.Double, 'string'),\n (r'\\s+', Text),\n (r'[^\\s{}$\"\\\\]+', Text)\n ],\n 'string': [\n (r'\"', String.Double, '#pop'),\n (r'(?s)(\\\\\\\\|\\\\.|[^\"\\\\$])+', String.Double),\n include('interp'),\n ],\n 'curly': [\n (r'\\}', String.Interpol, '#pop'),\n (r'[\\w#@]+', Name.Variable),\n include('root')\n ]\n\n }\n\n def analyse_text(text):\n if shebang_matches(text, r'execlineb'):\n return 1\n","sub_path":"contrib/python/Pygments/py3/pygments/lexers/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":36466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50537103","text":"import os\nimport xml.etree.ElementTree as EleTr\nimport graphviz as gviz\n\nfrom analysis.dict_functions import update_dict_occurences\nfrom analysis.question import question\n\n# Constants defining the color and arrow style for some tags\nNODE_TAGS = {\n 'PLACE': 'green',\n 'LOCATION': 'lightblue',\n 'SPATIAL_ENTITY': 'yellow',\n 'NONMOTION_EVENT': 'red',\n 'MOTION': 'purple',\n 'PATH': \"orange\"\n}\n\nEDGE_TAGS = {\n 'QSLINK': 'solid',\n 'OLINK': 'dashed'\n}\n\n\nclass FileAnalyzer:\n \"\"\"\n Handles the analysis of one file\n :param path: path of the file to be analyzed\n :param nlp: the NLP provided by spacy\n \"\"\"\n def __init__(self, path, nlp):\n # Sets variables\n self.path = path\n root = EleTr.parse(path).getroot()\n text = root.findall('TEXT')[0].text\n\n self.doc = nlp(text)\n self.tags = root.findall('TAGS')[0]\n self.pos_counter = self.create_pos_counter()\n self.sentences = [len(sent) for sent in self.doc.sents]\n\n def create_pos_counter(self):\n \"\"\"\n Creates a dictionary holding the distribution of all PoS-\n :return: dict: A dictionary of the PoS distribution\n \"\"\"\n pos_counter = {}\n for token in self.doc:\n update_dict_occurences(pos_counter, token.pos_)\n return pos_counter\n\n def get_pos_counter(self):\n \"\"\"\n :return: dict: A dictionary of the PoS distribution\n \"\"\"\n return self.pos_counter\n\n def get_tags(self):\n \"\"\"\n :return: The elment of the element-tree holding all tags\n \"\"\"\n return self.tags\n\n def get_sentences(self):\n \"\"\"\n :return: List of all sentence-lengths\n \"\"\"\n return self.sentences\n\n def visualize(self):\n \"\"\"\n Creates a Graph showing the relation between the different Tags\n \"\"\"\n file_name = self.path.split(os.sep)[-1][0:-4]\n print(f'--- {file_name} ---')\n\n graph = gviz.Digraph(comment=file_name, engine='circo')\n\n # Filters the tags in METALINK and non METALINK tags\n metalink_tags = [tag for tag in self.tags if tag.tag == 'METALINK']\n non_metalink_tags = [tag for tag in self.tags if tag.tag != 'METALINK']\n\n # Iterates over all Metalinks and merges two tags if necessary\n for tag in metalink_tags:\n from_id, to_id = tag.attrib['fromID'], tag.attrib['toID']\n non_metalink_tags = self.remove_and_replace(from_id, to_id, non_metalink_tags)\n\n # Filters the non METALINK tags in Nodes and Endges\n node_tags = [tag for tag in non_metalink_tags if tag.tag in NODE_TAGS]\n edge_tags = [tag for tag in non_metalink_tags if tag.tag in EDGE_TAGS]\n\n # Renders all Nodes\n for tag in node_tags:\n graph.node(name=tag.attrib['id'], label=tag.attrib['text'], fillcolor=NODE_TAGS[tag.tag], style='filled')\n\n # Renders all Edges\n for tag in edge_tags:\n graph.edge(tail_name=tag.attrib['fromID'], head_name=tag.attrib['toID'],\n label=tag.attrib['relType'], style=EDGE_TAGS[tag.tag], arrowhead='none')\n\n # Renders a legend explaining the colors and arrows\n label = '<<TABLE>'\n for tag in NODE_TAGS:\n label += f'<TR><TD BGCOLOR=\"{NODE_TAGS[tag]}\">{tag}</TD></TR>'\n label += '<TR><TD>QSLINK --- ></TD></TR><TR><TD>OLINK - - - ></TD></TR>'\n label += '</TABLE>>'\n graph.attr(label=label)\n\n # Outputs the files\n save_location = os.path.join(__file__, '..', '..', 'results', 'graph')\n if not os.path.exists(save_location):\n os.makedirs(save_location)\n\n graph.render(os.path.join(save_location, f'{file_name}.gv'),\n view=question('Do you want to see the resulting graph?'))\n\n @staticmethod\n def remove_and_replace(old, new, tags):\n \"\"\"\n Updates the list of non_metalink_tags on a merge by updating the ids to the tag leftover and removing the\n merged 'old' tag.\n :param old: ID of the old tag\n :param new: ID of the new tag\n :param tags: List of all tags\n :return: list: List of updated tags\n \"\"\"\n for tag in tags:\n if tag.attrib['id'] == old:\n tags.remove(tag)\n elif 'fromID' in tag.attrib and tag.attrib['fromID'] == old:\n tag.attrib['fromID'] = new\n elif 'toID' in tag.attrib and tag.attrib['toID'] == old:\n tag.attrib['toID'] = new\n return tags\n","sub_path":"analysis/file_analyzer.py","file_name":"file_analyzer.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"204754727","text":"\r\nfrom numpy import exp\r\nimport sys\r\nsys.path.append('..\\pyfunctions')\r\nfrom numpy.random import seed\r\nseed(756)\r\nsys.path.append('..\\\\')\r\nfrom GetAgeFreq import GetAgeFreq\r\n\r\nfrom numpy import log\r\nfrom scipy.stats import linregress\r\n\r\ncsvfile='..\\\\TreeNobXdate.csv'\r\ncol=0#Use first column from file\r\nSurveyYear=2005\r\nMaxYear=1980\r\nMinYear=1980-52\r\n\r\n\r\ndata=GetAgeFreq(csvfile,col=col,SurveyYear=SurveyYear,MaxYear=MaxYear,MinYear=MinYear)\r\nnyear=len(data)\r\nna0=sum(data)\r\na0=0\r\nabar=sum([ i*data[i] for i in range(nyear)])/na0\r\n\r\nsCR=(abar-a0)/ ( (abar-a0) +(na0-1)/na0 )\r\nzCR=-log(sCR)\r\nzCRc=zCR- (na0-1)*(na0-2) / na0 / ( na0*(na0*(abar-a0)+1) ) / (na0 + na0*(na0*(abar-a0)-1) )\r\nzCRcSigma=((1-exp(-zCRc))**2)/na0/exp(-zCRc)\r\nprint(-2*zCRcSigma + zCRc ,0*zCRcSigma + zCRc ,+2*zCRcSigma + zCRc )","sub_path":"Traditional/EndChapmanRobson.py","file_name":"EndChapmanRobson.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264542077","text":"\"\"\"GOPEM plotter.\"\"\"\nfrom __future__ import unicode_literals\nimport matplotlib\nfrom PyQt5 import QtWidgets\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nmatplotlib.use('Qt5Agg') # Make sure that we are using QT5\n\n\nclass MplCanvas(FigureCanvas):\n \"\"\"MplCanvas class.\"\"\"\n\n def __init__(self, parent=None, width=5, height=4, dpi=100):\n \"\"\"\n Initialize of MatPlotLib canvas for plotter.\n\n :param parent: the QWidget parent\n :param width: the initial width of canvas\n :param height: the initial height of canvas\n :param dpi: the dpi of the canvas\n \"\"\"\n fig = Figure(figsize=(width, height), dpi=dpi)\n self.axes = fig.add_subplot(111)\n\n FigureCanvas.__init__(self, fig)\n self.setParent(parent)\n\n FigureCanvas.setSizePolicy(self,\n QtWidgets.QSizePolicy.Expanding,\n QtWidgets.QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n\n def update_plot(self, data, x_axis, y_axis):\n \"\"\"\n Update the data and axis range of the canvas.\n\n :param data: a dictionary that contains the data points\n :param x_axis: the ticks on X axis\n :param y_axis: the ticks on Y axis\n :return: None\n \"\"\"\n self.axes.cla()\n self.axes.grid(True, linestyle='-.', which='both')\n if x_axis in data.keys() and y_axis in data.keys():\n self.axes.plot(data[x_axis], data[y_axis], 'r')\n self.axes.set_xlabel(x_axis)\n self.axes.set_ylabel(y_axis)\n\n self.draw()\n\n\nclass ApplicationWindow(QtWidgets.QWidget):\n \"\"\"ApplicationWindow class.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Application widget for MPLCanvas class.\n\n :param args: the list of arguments\n :param kwargs: the dictionary of keywords\n \"\"\"\n super().__init__(*args, **kwargs)\n self.setMinimumSize(400, 400)\n l = QtWidgets.QVBoxLayout(self)\n self.sc = MplCanvas(self, width=20, height=20, dpi=100)\n\n l.addWidget(self.sc)\n\n def update_plotter_data(self, data, x_axis, y_axis):\n \"\"\"\n Update the plotter data and axis.\n\n :param data: the dictionary of data\n :param x_axis: the Ticks on X axis\n :param y_axis: the Ticks on Y axis\n :return: None\n \"\"\"\n self.sc.update_plot(data, x_axis, y_axis)\n\n def file_quit(self):\n \"\"\"\n Close the application.\n\n :return: None\n \"\"\"\n self.close()\n\n def close_event(self, ce):\n \"\"\"\n Slot for close event trigger.\n\n :param ce: close event\n :return: None\n \"\"\"\n self.file_quit()\n","sub_path":"gopem/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"58029490","text":"#Brian Wong 34216498 Project 4 ICS 32 Lab 13\n\nNONE = ' '\nWHITE = 'O'\nBLACK = 'X'\n\ndef opposite_color(color: str) -> str:\n \"\"\"changes the color\"\"\"\n if color == BLACK:\n return WHITE\n else:\n return BLACK\n\n \nfrom collections import namedtuple\nLocation = namedtuple('Location', ['col', 'row'])\n\n\n\nclass Piece:\n def __init__(self, color: str, col: int, row: int):\n \"\"\"Initializes Piece to have a col, row, and color\"\"\"\n self._color = color\n self._col = col\n self._row = row\n\n def get_row(self) -> int:\n \"\"\"gets the # of rows\"\"\"\n return self._row\n\n def get_col(self) -> int:\n \"\"\"gets the # of cols\"\"\"\n return self._col\n\n def get_color(self) -> str:\n \"\"\"Returns color of this Piece\"\"\"\n return self._color\n\n def flipper(self):\n \"\"\"flips the color of the pieces\"\"\"\n if self._color == WHITE:\n self._color = BLACK\n else:\n self._color = WHITE\n \n\n\n\nclass Board:\n def __init__(self, cols: int, rows:int, top_left_pos: str):\n \"\"\"Initializes Board to have a col, row, and color\"\"\"\n if (cols%2==0 and cols>=4 and cols<=16 and rows%2==0\n and rows>=4 and rows<=16):\n self._col = cols\n self._row = rows\n self._board = self.board() #saves board changes\n self.starting_positions(top_left_pos)\n else:\n raise ValueError() #handle error in UI, ask user again\n\n def get_columns(self):\n \"\"\"gets column number\"\"\"\n return self._col\n\n def get_rows(self):\n \"\"\"gets row number\"\"\"\n return self._row\n\n def get_board(self):\n \"\"\"get board\"\"\"\n return self._board\n \n def board(self)->list:\n \"\"\"Creates new board\"\"\"\n \n board = []\n for i in range(self._col):\n row = []\n for j in range(self._row):\n row.append(NONE)\n board.append(row)\n return board\n\n def starting_positions(self, top_left_pos:str):\n \"\"\"drops pieces in starting locations\"\"\"\n if top_left_pos == BLACK:\n opposite_color = WHITE\n else:\n opposite_color = BLACK\n x = int(self._col/2)\n y = int(self._row/2)\n self.drop_on_board(x-1, y-1, top_left_pos)\n self.drop_on_board(x, y, top_left_pos)\n self.drop_on_board(x, y-1, opposite_color)\n self.drop_on_board(x-1, y, opposite_color)\n \n\n def drop_on_board(self, col: int, row: int, color: str):\n \"\"\"Puts a piece on the board, checks if it fits on the board, but\n not if its a valid Othello move\"\"\"\n self._board[col][row] = Piece(color, col, row)\n\n def print_board(self) -> None:\n \"\"\"\n Prints the current state of the board\n \"\"\"\n board = self._board\n print(' ', end=' ')\n for i in range(len(board)):\n print('{:2d}'.format(i+1), end = ' ') \n print()\n\n for row in range(self._row):\n print('{:2d}'.format(row+1), end= ' ')\n for col in range(self._col):\n box = board[col][row] \n if(box == NONE):\n print('{:2s}'.format('.'), end=' ')\n else:\n print('{:2s}'.format(box.get_color()), end=' ')\n print()\n\n \n \n\nclass Game:\n def __init__(self, board_cols:int, board_rows: int,\n color:str, top_left_pos:str):\n self._cols = board_cols\n self._rows = board_rows\n self._board = Board(board_cols, board_rows, top_left_pos)\n self._current_player = color\n\n def get_current_player(self):\n \"\"\"gets current player\"\"\"\n return self._current_player\n\n def test_drop_valid_piece(self, drop_col: int, drop_row: int, color: str) ->list:\n \"\"\"\n Test for valid drops\n #1 Test if its valid to drop the piece in that place\n \"\"\"\n pieces = []\n directions = ['right', 'left', 'top', 'bottom', 'top_right', 'top_left', 'bottom_right', 'bottom_left']\n for direction in directions:\n pieces.extend(self.flip_each_direction(drop_col, drop_row, color, direction))\n return pieces\n \n\n def drop_valid_piece(self, drop_col: int, drop_row:int):\n \"\"\"\n Test for valid drops\n #1 flip the pieces that need to be flipped\n #2 drop the piece\n \"\"\"\n pieces = self.test_drop_valid_piece(drop_col,drop_row,self._current_player)\n \n if len(pieces) != 0:\n for piece in pieces:\n piece.flipper()\n self._board.drop_on_board(drop_col, drop_row, self._current_player)\n self.flips_no_moves()\n else:\n raise ValueError()\n\n \n\n def flip_each_direction(self, starting_col: int, starting_row: int, color: str, direction: str) ->list:\n \"\"\"Find flippable pieces in each direction, returns list of coordinates in that direction\"\"\"\n flippable_pieces = []\n loop_count = 0\n i = starting_col\n j = starting_row\n valid = False\n while True:\n if i == starting_col and j == starting_row:\n piece = self._board.get_board()[i][j]\n if type(piece)== Piece:\n break\n elif i != starting_col or j != starting_row:\n piece = self._board.get_board()[i][j]\n if type(piece) == str: ##is empty\n break\n elif loop_count == 1: ## piece next to starting point\n if piece.get_color() == color:\n break\n elif piece.get_color() == color:\n valid = True\n break\n\n flippable_pieces.append(piece)\n\n if direction == 'right':\n if i == self._cols-1:\n break\n i +=1\n elif direction == 'left':\n if i == 0:\n break\n i -= 1\n elif direction == 'top':\n if j == 0:\n break\n j -= 1\n elif direction == 'bottom':\n if j == self._rows-1:\n break\n j += 1\n elif direction == 'top_right':\n if i == self._cols-1 or j == 0:\n break\n i += 1\n j -= 1\n elif direction == 'top_left':\n if i == 0 or j == 0:\n break\n i -= 1\n j -= 1\n elif direction == 'bottom_right':\n if i == self._cols-1 or j == self._rows-1:\n break\n i += 1\n j += 1\n elif direction == 'bottom_left':\n if i == 0 or j == self._rows - 1:\n break\n i -= 1\n j += 1\n\n loop_count += 1\n \n if valid:\n return flippable_pieces\n else:\n return []\n \n \n ## 1.) if the FIRST spot has a piece that is the opposite color, then can keep going \n ## 2.) if blank, it means it cant be valid even. if not, keep going\n ## 3.) if you hit a piece after the first one that is your color, it's a valid move\n \n\n def num_white_piece(self):\n \"\"\"counts number of white pieces\"\"\"\n count = 0\n for column in self._board.get_board():\n for cell in column:\n if type(cell) == Piece and cell.get_color() == WHITE:\n count +=1\n return count \n\n def num_black_piece(self):\n \"\"\"counts number of black pieces\"\"\"\n count = 0\n for column in self._board.get_board():\n for cell in column:\n if type(cell) == Piece and cell.get_color() == BLACK:\n count +=1\n return count\n\n def opposite_turn(self):\n \"\"\"given the player whose turn it is now, return the opposite player\"\"\"\n self._current_player = opposite_color(self._current_player)\n\n \n def list_of_valid_moves(self, color: str):\n \"\"\"Returns a list of valid moves that a player has\"\"\"\n valid = []\n for col in range(self._cols):\n for row in range(self._rows):\n if type(self._board.get_board()[col][row]) == str:\n flippable_pieces = self.test_drop_valid_piece(col, row, color)\n if len(flippable_pieces) != 0:\n valid.append(Location(col=col+1, row=row+1))\n return valid\n\n def flips_no_moves(self):\n \"\"\"If the player has no more moves, flip to the next player.\n If the new player has no more moves end game(throw error).\"\"\"\n current_player_moves = self.list_of_valid_moves(self._current_player)\n next_color = opposite_color(self._current_player)\n opposite_player_moves = self.list_of_valid_moves(next_color)\n\n if len(opposite_player_moves) != 0:\n self.opposite_turn()\n elif len(opposite_player_moves) == 0 and len(current_player_moves) == 0:\n ## both players can't move; game over\n raise GameOverError()\n\nclass GameOverError(Exception):\n pass\n \n \n\n \n\n\n","sub_path":"othello_logic.py","file_name":"othello_logic.py","file_ext":"py","file_size_in_byte":9413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82052363","text":"##script used to parse PCC motif matrix to sig or not sig\nimport os, sys\n\nsum_matrix = open(sys.argv[1],\"r\") #miteupLMup_TFBM_TFfamily_Low_PCC_average.txt\noutput = open(sys.argv[1] + \"_sig.txt\", \"w\")\n\n\nD = {}\ndef add_data_to_dict(inp):\n for line in inp:\n if line.startswith(\"#python\"):\n pass\n if line.startswith(\"motif\"):\n L = line.strip().split(\"\\t\")\n title_list = L[0:]\n title_str = '\\t'.join(title_list)\n output.write(title_str + '\\n')\n else:\n L2 = line.strip().split('\\t')\n motif = L2[0]\n PCC_dist = L2[1:]\n sig_list= []\n for dist in PCC_dist:\n if float(dist) <=0.39:\n sig_list.append(str(1))\n else:\n sig_list.append(str(0))\n sig_str = \"\\t\".join(sig_list)\n output.write('%s\\t%s\\n' % (motif, sig_str))\n\nadd_data_to_dict(sum_matrix)\n\noutput.close()","sub_path":"convert_sig_motif2.py","file_name":"convert_sig_motif2.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82968758","text":"def fibonacci(n):\r\n if n <= 1:\r\n return n\r\n else:\r\n return fibonacci(n - 1) + fibonacci(n - 2)\r\n\r\n# T(n) = T(n-1) + T(n-2)\r\n# T(n) = 2*T(n-1)\r\n# T(n) = O(2*T(n-1) O definition\r\n# T(n) = O(2^(n-1)) product rule\r\n# T(n) = O(2^n) sum rule\r\n# ____________+\r\n# O(2^n)\r\n\r\nprint(fibonacci(8))\r\n","sub_path":"talleres/taller04/Fibonacci.py","file_name":"Fibonacci.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"304315937","text":"import re\n\nimport argparse\n\nfrom common import execute_command, env\nfrom git import git_command, has_git_changes\nfrom github import add_assignee, get_branch, create_pull_request\n\nCHECK_WORKFLOW_PATH = \".github/workflows/check.yml\"\nRUSTC_VERSION_RE = re.compile(r\".* \\(\\w*\\s*(\\d{4}-\\d{2}-\\d{2})\\)\")\nWORKFLOW_RUSTC_VERSION_RE = re.compile(r\"(rust-version: \\[.*nightly-)\\d{4}-\\d{2}-\\d{2}(.*])\")\nNIGHTLY_BRANCH = \"nightly\"\nDEFAULT_ASSIGNEE = \"Undin\"\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--token\", type=str, required=True, help=\"github token\")\n\n args = parser.parse_args()\n\n repo = env(\"GITHUB_REPOSITORY\")\n\n nightly_branch = get_branch(repo, args.token, NIGHTLY_BRANCH)\n if nightly_branch is not None:\n print(\"Repo already has nightly branch\")\n return\n\n git_command(\"checkout\", \"-b\", NIGHTLY_BRANCH)\n\n output = execute_command(\"rustc\", \"-V\")\n match_result = RUSTC_VERSION_RE.match(output)\n date = match_result.group(1)\n with open(CHECK_WORKFLOW_PATH) as f:\n workflow_text = f.read()\n\n result = re.search(WORKFLOW_RUSTC_VERSION_RE, workflow_text)\n if result is None:\n raise ValueError(\"Failed to find the current version of nightly rust\")\n\n new_workflow_text = re.sub(WORKFLOW_RUSTC_VERSION_RE, f\"\\\\g<1>{date}\\\\g<2>\", workflow_text)\n if new_workflow_text == workflow_text:\n print(\"The latest nightly rustc version is already used\")\n return\n\n with open(CHECK_WORKFLOW_PATH, \"w\") as f:\n f.write(new_workflow_text)\n\n if has_git_changes():\n git_command(\"add\", CHECK_WORKFLOW_PATH)\n git_command(\"commit\", \"-m\", \":arrow_up: nightly\")\n\n git_command(\"push\", \"origin\", NIGHTLY_BRANCH)\n pull_request = create_pull_request(repo, args.token, NIGHTLY_BRANCH, \":arrow_up: nightly\")\n add_assignee(repo, args.token, pull_request[\"number\"], DEFAULT_ASSIGNEE)\n else:\n print(\"Everything is up to date\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/update_nightly.py","file_name":"update_nightly.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"173357271","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport csv\nimport json\nimport logging\nimport sys\nimport urllib\nimport urllib2\nfrom time import gmtime, strftime\n\n# python2 to handle utf8 string\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nAPI_CALL_LIMIT = 50\n\n\ndef retrieve_name_gender(first_name):\n url = \"https://api.genderize.io/?name=\" + first_name\n try:\n res = urllib2.urlopen(url)\n if res:\n json_res = json.load(res)\n logging.root.debug(first_name + \"'s results are \" + str(json_res))\n return json_res\n except Exception as e:\n logging.root.warn(e)\n return None\n\n return None\n\n\ndef main():\n # parse arguments\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-n', '--name_list', required=True,\n help='name_list with frequency')\n parser.add_argument('-i', '--input', required=True,\n help='existed name_gender_file')\n parser.add_argument('-o', '--output', required=True,\n help='output name_gender_file')\n parser.add_argument('-c', '--number_of_scraping', required=True,\n help='number of names to be scraped')\n parser.add_argument('-l', '--logging', required=False,\n help='logging level')\n\n args = parser.parse_args()\n log_handler = logging.StreamHandler()\n log_formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s - %(message)s')\n log_handler.setFormatter(log_formatter)\n logging.root.addHandler(log_handler)\n logging.root.setLevel(level=logging.INFO)\n if args.logging and args.logging.lower() == \"debug\":\n logging.root.setLevel(level=logging.DEBUG)\n\n input_file = args.input\n output_file = args.output\n name_file = args.name_list\n number = args.number_of_scraping\n\n name_list = []\n with open(name_file) as name_input_file:\n name_input_data = csv.DictReader(name_input_file)\n for row in name_input_data:\n first_name = row[\"first_name\"].lower().strip()\n freq = row[\"freq\"]\n if first_name and freq and freq > 0:\n entry = {\n \"first_name\": first_name,\n \"index_freq\": freq\n }\n name_list.append(entry)\n\n logging.root.info(\"read \" + str(len(name_list)) + \" name entries from \" + name_file + \".\")\n\n # read from existed list\n name_gender_dict = {}\n with open(input_file) as name_gender_input_file:\n name_gender_input_data = csv.DictReader(name_gender_input_file)\n for row in name_gender_input_data:\n name = row[\"First_name\"].lower().strip()\n if name and name not in name_gender_dict:\n name_gender_dict[name] = {\n \"index_freq\": row[\"Index_freq\"],\n \"gender\": row[\"Gender\"],\n \"probability\": row[\"Probability\"],\n \"updated\": row[\"Updated\"]\n }\n else:\n logging.root.warn(str(name) + \" is either none or duplicates\")\n logging.root.info(\"read \" + str(len(name_gender_dict)) + \" existed name gender entries from \" + input_file + \".\")\n\n # API_CALL_LIMIT\n count = 0\n for name_entry in name_list:\n first_name = name_entry[\"first_name\"]\n freq = name_entry[\"index_freq\"]\n if first_name in name_gender_dict:\n if freq != name_gender_dict[first_name][\"index_freq\"]:\n name_gender_dict[first_name][\"index_freq\"] = freq\n else:\n count += 1\n try:\n res = retrieve_name_gender(first_name)\n except Exception as e:\n logging.root.warn(e)\n break\n if not res:\n logging.root.error(first_name + \" API call result is None\")\n break\n if \"name\" in res and \"gender\" in res and \"probability\" in res:\n name_gender_dict[first_name] = {\n \"index_freq\": freq,\n \"gender\": res[\"gender\"],\n \"probability\": res[\"probability\"],\n \"updated\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n }\n else:\n logging.root.warn(\"API call return result does not have all keys: \" + str(res))\n name_gender_dict[first_name] = {\n \"index_freq\": freq,\n \"gender\": \"any\",\n \"probability\": 1,\n \"updated\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n }\n if count > number:\n break\n logging.root.info(\"call API \" + str(count) + \" times\")\n logging.root.info(\"name_gender_dict has \" + str(len(name_gender_dict)) + \" entries now.\")\n\n # write results back to csv file\n with open(output_file, \"w\") as output_csv_file:\n fieldnames = [\"First_name\", \"Index_freq\", \"Gender\", \"Probability\", \"Updated\"]\n writer = csv.DictWriter(output_csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for first_name in sorted(name_gender_dict.iterkeys()):\n writer.writerow({\"First_name\": first_name,\n \"Index_freq\": name_gender_dict[first_name][\"index_freq\"],\n \"Gender\": name_gender_dict[first_name][\"gender\"],\n \"Probability\": name_gender_dict[first_name][\"probability\"],\n \"Updated\": name_gender_dict[first_name][\"updated\"]\n })\n logging.root.info(\"write \" + str(len(name_gender_dict)) + \" name gender entries to \" + output_file + \".\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cele_tools/retrieve_name_gender.py","file_name":"retrieve_name_gender.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325835643","text":"#Exercio capitulo 2 programa 2 18/10/2018\n\narea = int(input(\"Entre com aréa a pintar: \"))\n\nlitros = area // 3 # divisao inteira \n \nif area % 3 > 0 :\n litros = litros + 1\n \nprint(litros) \n \n\n","sub_path":"Fund_Python_2018/Exercicos/Cap_2_Prog_2.py","file_name":"Cap_2_Prog_2.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"215829594","text":"import hashlib\nfrom tkinter import *\nimport argparse\n\nclass BaseMethod:\n def __init__(self):\n self.sessions = {'3.2': ['2 - Logging',\n '3 - Graphics'],\n '6.2': ['2 - Pokemon',\n '3 - Crypto Exchange', \n '4 - What3words',\n '5 - Flying Aircraft']}\n self.user_email = ''\n self.sessions_key = ''\n\n def user_input_output(self):\n '''\n Method for gathering both user email and session user is querying.\n '''\n pass\n\n def problem_choice(self, sessions_key, email):\n '''\n Method for determining the session given the student's email. This is standard throughout\n all implementations so useful to implement in abstract class.\n '''\n email = self.user_email.strip().lower() #xtra careful\n sessions_key = self.sessions_key.strip().lower() #xtra careful\n enc = (email + sessions_key).encode()\n md5 = hashlib.md5(enc).hexdigest()\n ind = int(md5, 16) % len(self.sessions[sessions_key])\n return self.sessions[sessions_key][ind]\n\n def run_main_program(self):\n '''\n Function for inherited class specific implementation to work.\n '''\n self.user_input_output()\n\nclass Terminal(BaseMethod):\n def __init__(self):\n super().__init__()\n\n def user_input_output(self):\n self.user_email = input(\"Please enter your student email address: \")\n while \"@minerva.kgi.edu\" not in self.user_email:\n print(\"Oops, I don't think that's a Minervan email address, would you mind checking you typed it write? You wrote {}.\".format(self.user_email))\n self.user_email = input(\"Please enter your student email address: \")\n\n self.sessions_key = input(\"What session is this for (sessions supported: {}): \".format(\", \".join([*self.sessions])))\n while self.sessions_key not in self.sessions.keys():\n print(\"Oops, I don't think we support that session number, would you mind checking you typed it write? You wrote {}.\".format(self.sessions_key))\n self.sessions_key = input(\"What session is this for (sessions supported: {}): \".format(\", \".join([*self.sessions])))\n\n print(\"You'll be doing: {}.\".format(self.problem_choice(self.sessions_key, self.user_email)))\n\nclass TKinter(BaseMethod):\n def __init__(self):\n super().__init__()\n\n def user_input_output(self):\n top = Toplevel(self.root)\n label_user_email = Label(top, text=\"Please enter your student email address:\")\n label_user_email.pack()\n entry_user_email = Entry(top)\n entry_user_email.pack()\n label_sessions_key = Label(top, text=\"Which Session is this for?\")\n label_sessions_key.pack()\n entry_sessions_key = Entry(top)\n entry_sessions_key.pack()\n\n def checker():\n self.user_email = entry_user_email.get()\n self.sessions_key = entry_sessions_key.get()\n if \"@minerva.kgi.edu\" in self.user_email and self.sessions_key in [*self.sessions]:\n top.destroy()\n display_selection()\n else:\n if \"@minerva.kgi.edu\" in self.user_email:\n label_warning = Label(top, text=\"It looks like you may not have entered a session we currently support!\\n Would you mind retyping? As a reminder, you wrote {}.\\n We currently only support ({})\".format(self.sessions_key, \", \".join([*self.sessions])))\n else:\n label_warning = Label(top, text=\"Would you mind checking you entered a minerva address?\\n As a reminder, you wrote {}.\".format(self.user_email))\n\n label_warning.pack()\n\n if hasattr(self.root, 'label_warning'):\n self.user_input()\n\n b = Button(top, text='Submit', command=checker)\n b.pack()\n top.attributes(\"-topmost\", True)\n\n def display_selection():\n self.root.title(\"Pre-Class Work Select\")\n self.root.geometry(\"300x100\")\n Label(self.root, text='For seminar {}'.format(self.sessions_key)).pack()\n Label(self.root, text=self.problem_choice(self.sessions_key, self.user_email)).pack()\n\n def run_main_program(self):\n self.root = Tk()\n self.user_input_output()\n self.root.mainloop()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='UI Controller')\n\n parser.add_argument('UI', action='store', default=Terminal)\n\n args = parser.parse_args()\n\n methods = {\n 'TKinter' : TKinter(),\n 'Terminal' : Terminal()\n }\n\n try:\n methods[vars(args)['UI']].run_main_program()\n except KeyError:\n print(\"Oops, I don't recognize that UI. Want to implement it?\")\n","sub_path":"utils/pcw_selector.py","file_name":"pcw_selector.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"336785069","text":"import pygame\nfrom pygame.sprite import Sprite\nfrom timer import Timer\n\n\nclass Koopa(Sprite):\n def __init__(self, screen):\n super(Koopa, self).__init__()\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.image = pygame.image.load('images/minion/koopa-1.png')\n self.rect = self.image.get_rect()\n self.rect.x = self.rect.width\n self.rect.y = self.rect.height\n self.x = float(self.rect.x)\n\n frames = [pygame.image.load('images/minion/koopa-1.png'),\n pygame.image.load('images/minion/koopa-2.png')]\n self.koopa_moving_timer = Timer(frames)\n\n self.is_dead = False\n self.speed_factor = 1\n self.direction = -1 # -1 = left\n\n def update(self):\n self.x += (self.speed_factor * self.direction)\n self.rect.x = self.x\n\n def blitme(self):\n self.screen.blit(self.image, self.rect)","sub_path":"goomba.py","file_name":"goomba.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"426426080","text":"def mean(vals):\n\t\"\"\"Calculate the arithmetic mean of a list of numbers in vals\"\"\"\n\tassert type(vals) is list, \"wrong input format\"\n\t\n\ttotal = sum(vals)\n\tlength = len(vals)\n\tif length == 0:\n\t\treturn 0.0\n\telse:\n\t\treturn total/length\n\t\n#potential problems: empty list; data types; test cases\n\n#print(mean(\"hello\"))\n\n\n\n","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554303528","text":"\"\"\"\nCopyright (c) 2017 Red Hat, Inc\nAll rights reserved.\n\nThis software may be modified and distributed under the terms\nof the BSD license. See the LICENSE file for details.\n\"\"\"\n\nfrom atomic_reactor.core import DockerTasker\nfrom atomic_reactor.inner import DockerBuildWorkflow\nfrom atomic_reactor.plugin import BuildCanceledException, PluginFailedException\nfrom atomic_reactor.plugin import BuildStepPluginsRunner\nfrom atomic_reactor.plugins import pre_reactor_config\nfrom atomic_reactor.plugins.build_orchestrate_build import (OrchestrateBuildPlugin,\n get_worker_build_info,\n get_koji_upload_dir,\n override_build_kwarg)\nfrom atomic_reactor.plugins.pre_reactor_config import (ReactorConfig,\n ReactorConfigPlugin,\n WORKSPACE_CONF_KEY)\nfrom atomic_reactor.plugins.pre_check_and_set_rebuild import CheckAndSetRebuildPlugin\nfrom atomic_reactor.util import df_parser\nimport atomic_reactor.util\nfrom atomic_reactor.constants import (PLUGIN_ADD_FILESYSTEM_KEY,\n PLUGIN_CHECK_AND_SET_PLATFORMS_KEY)\nfrom flexmock import flexmock\nfrom multiprocessing.pool import AsyncResult\nfrom osbs.api import OSBS\nfrom osbs.conf import Configuration\nfrom osbs.build.build_response import BuildResponse\nfrom osbs.exceptions import OsbsException\nfrom osbs.core import Openshift\nfrom osbs.utils import ImageName\nfrom tests.constants import MOCK_SOURCE, INPUT_IMAGE, SOURCE\nfrom tests.docker_mock import mock_docker\nfrom tests.util import add_koji_map_in_workflow\nfrom textwrap import dedent\nfrom copy import deepcopy\n\nimport json\nimport os\nimport sys\nimport pytest\nimport time\nimport platform\n\n\nMANIFEST_LIST = {\n 'manifests': [\n {'platform': {'architecture': 'amd64'}, 'digest': 'sha256:123456'},\n {'platform': {'architecture': 'ppc64le'}, 'digest': 'sha256:123456'},\n ]\n}\n\n\nDEFAULT_CLUSTERS = {\n 'x86_64': [\n {\n 'name': 'worker_x86_64',\n 'max_concurrent_builds': 3\n }\n ],\n 'ppc64le': [\n {\n 'name': 'worker_ppc64le',\n 'max_concurrent_builds': 3\n }\n ]\n}\n\n\nclass MockSource(object):\n\n def __init__(self, tmpdir):\n tmpdir = str(tmpdir)\n self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile')\n self.path = tmpdir\n self.config = flexmock(image_build_method=None)\n\n def get_build_file_path(self):\n return self.dockerfile_path, self.path\n\n\nclass MockInsideBuilder(object):\n\n def __init__(self):\n mock_docker()\n self.tasker = DockerTasker()\n self.base_image = ImageName(repo='fedora', tag='25')\n self.image_id = 'image_id'\n self.image = INPUT_IMAGE\n self.df_path = 'df_path'\n self.df_dir = 'df_dir'\n self.parent_images_digests = {}\n\n def simplegen(x, y):\n yield \"some\\u2018\".encode('utf-8')\n flexmock(self.tasker, build_image_from_path=simplegen)\n\n def get_built_image_info(self):\n return {'Id': 'some'}\n\n def inspect_built_image(self):\n return None\n\n def ensure_not_built(self):\n pass\n\n\nclass fake_imagestream_tag(object):\n def __init__(self, json_cont):\n self.json_cont = json_cont\n\n def json(self):\n return self.json_cont\n\n\nclass fake_manifest_list(object):\n def __init__(self, json_cont):\n self.content = json_cont\n\n def json(self):\n return self.content\n\n\npytestmark = pytest.mark.usefixtures('user_params')\n\n\ndef mock_workflow(tmpdir, platforms=None):\n workflow = DockerBuildWorkflow(source=MOCK_SOURCE)\n builder = MockInsideBuilder()\n source = MockSource(tmpdir)\n setattr(builder, 'source', source)\n setattr(workflow, 'source', source)\n setattr(workflow, 'builder', builder)\n\n df_path = os.path.join(str(tmpdir), 'Dockerfile')\n with open(df_path, 'w') as f:\n f.write(dedent(\"\"\"\\\n FROM fedora:25\n LABEL com.redhat.component=python \\\n version=2.7 \\\n release=10\n \"\"\"))\n df = df_parser(df_path)\n setattr(workflow.builder, 'df_path', df.dockerfile_path)\n\n platforms = ['x86_64', 'ppc64le'] if platforms is None else platforms\n workflow.prebuild_results[PLUGIN_CHECK_AND_SET_PLATFORMS_KEY] = set(platforms)\n\n build = {\n \"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/some_image@sha256:123456\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"name\": \"registry/some_image:latest\",\n \"kind\": \"DockerImage\"})}}}\n flexmock(os, environ={'BUILD': json.dumps(build)})\n\n return workflow\n\n\ndef mock_reactor_config(tmpdir, clusters=None, empty=False, add_config=None):\n if not clusters and not empty:\n clusters = deepcopy(DEFAULT_CLUSTERS)\n\n koji_map = {\n 'hub_url': '/',\n 'root_url': '',\n 'auth': {}\n }\n\n conf_json = {\n 'version': 1,\n 'clusters': clusters,\n 'koji': koji_map\n }\n if add_config:\n conf_json.update(add_config)\n conf = ReactorConfig(conf_json)\n (flexmock(pre_reactor_config)\n .should_receive('get_config')\n .and_return(conf))\n\n with open(os.path.join(str(tmpdir), 'osbs.conf'), 'w') as f:\n for plat_clusters in clusters.values():\n for cluster in plat_clusters:\n f.write(dedent(\"\"\"\\\n [{name}]\n openshift_url = https://{name}.com/\n namespace = {name}_namespace\n \"\"\".format(name=cluster['name'])))\n return conf_json\n\n\ndef mock_manifest_list():\n (flexmock(atomic_reactor.util)\n .should_receive('get_manifest_list')\n .and_return(fake_manifest_list(MANIFEST_LIST)))\n\n\ndef mock_orchestrator_platfrom(plat='x86_64'):\n (flexmock(platform)\n .should_receive('processor')\n .and_return(plat))\n\n\ndef mock_osbs(current_builds=2, worker_builds=1, logs_return_bytes=False, worker_expect=None):\n (flexmock(OSBS)\n .should_receive('list_builds')\n .and_return(list(range(current_builds))))\n\n koji_upload_dirs = set()\n\n def mock_create_worker_build(**kwargs):\n # koji_upload_dir parameter must be identical for all workers\n koji_upload_dirs.add(kwargs.get('koji_upload_dir'))\n assert len(koji_upload_dirs) == 1\n\n if worker_expect:\n testkwargs = deepcopy(kwargs)\n testkwargs.pop('koji_upload_dir')\n assert testkwargs == worker_expect\n\n return make_build_response('worker-build-{}'.format(kwargs['platform']),\n 'Running')\n (flexmock(OSBS)\n .should_receive('create_worker_build')\n .replace_with(mock_create_worker_build))\n\n if logs_return_bytes:\n log_format_string = b'line \\xe2\\x80\\x98 - %d'\n else:\n log_format_string = 'line \\u2018 - %d'\n\n (flexmock(OSBS)\n .should_receive('get_build_logs')\n .and_yield(log_format_string % line for line in range(10)))\n\n def mock_wait_for_build_to_finish(build_name):\n return make_build_response(build_name, 'Complete')\n (flexmock(OSBS)\n .should_receive('wait_for_build_to_finish')\n .replace_with(mock_wait_for_build_to_finish))\n\n\ndef make_build_response(name, status, annotations=None, labels=None):\n build_response = {\n 'metadata': {\n 'name': name,\n 'annotations': annotations or {},\n 'labels': labels or {},\n },\n 'status': {\n 'phase': status\n }\n }\n\n return BuildResponse(build_response)\n\n\ndef make_worker_build_kwargs(**overrides):\n kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'arrangement_version': 6\n }\n kwargs.update(overrides)\n return kwargs\n\n\ndef teardown_function(function):\n sys.modules.pop('build_orchestrate_build', None)\n\n\n@pytest.mark.parametrize('config_kwargs', [\n None,\n {},\n {'build_image': 'osbs-buildroot:latest'},\n {'build_image': 'osbs-buildroot:latest', 'sources_command': 'fedpkg source'},\n {'build_image': 'osbs-buildroot:latest',\n 'equal_labels': 'label1:label2,label3:label4'},\n])\n@pytest.mark.parametrize('worker_build_image', [\n 'fedora:latest',\n None\n])\n@pytest.mark.parametrize('logs_return_bytes', [\n True,\n False\n])\ndef test_orchestrate_build(tmpdir, caplog,\n config_kwargs, worker_build_image, logs_return_bytes):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n mock_osbs(logs_return_bytes=logs_return_bytes)\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n }\n if worker_build_image:\n plugin_args['worker_build_image'] = worker_build_image\n if config_kwargs is not None:\n plugin_args['config_kwargs'] = config_kwargs\n\n expected_kwargs = {\n 'conf_section': str('worker_x86_64'),\n 'conf_file': str(tmpdir) + '/osbs.conf',\n 'sources_command': None,\n 'koji_hub': '/',\n 'koji_root': ''\n }\n if config_kwargs:\n expected_kwargs['sources_command'] = config_kwargs.get('sources_command')\n if 'equal_labels' in config_kwargs:\n expected_kwargs['equal_labels'] = config_kwargs.get('equal_labels')\n\n clusters = deepcopy(DEFAULT_CLUSTERS)\n\n reactor_dict = {'version': 1, 'arrangement_version': 6}\n if config_kwargs and 'sources_command' in config_kwargs:\n reactor_dict['sources_command'] = 'fedpkg source'\n\n expected_kwargs['source_registry_uri'] = None\n reactor_dict['odcs'] = {'api_url': 'odcs_url'}\n expected_kwargs['odcs_insecure'] = False\n expected_kwargs['odcs_url'] = reactor_dict['odcs']['api_url']\n reactor_dict['prefer_schema1_digest'] = False\n expected_kwargs['prefer_schema1_digest'] = reactor_dict['prefer_schema1_digest']\n reactor_dict['smtp'] = {\n 'from_address': 'from',\n 'host': 'smtp host'}\n expected_kwargs['smtp_host'] = reactor_dict['smtp']['host']\n expected_kwargs['smtp_from'] = reactor_dict['smtp']['from_address']\n expected_kwargs['smtp_email_domain'] = None\n expected_kwargs['smtp_additional_addresses'] = \"\"\n expected_kwargs['smtp_error_addresses'] = \"\"\n expected_kwargs['smtp_to_submitter'] = False\n expected_kwargs['smtp_to_pkgowner'] = False\n reactor_dict['artifacts_allowed_domains'] = ('domain1', 'domain2')\n expected_kwargs['artifacts_allowed_domains'] =\\\n ','.join(reactor_dict['artifacts_allowed_domains'])\n reactor_dict['yum_proxy'] = 'yum proxy'\n expected_kwargs['yum_proxy'] = reactor_dict['yum_proxy']\n reactor_dict['content_versions'] = ['v2']\n expected_kwargs['registry_api_versions'] = 'v2'\n\n # Move client config from plugin args to reactor config\n reactor_dict['clusters_client_config_dir'] = plugin_args.pop('osbs_client_config')\n\n if config_kwargs and 'equal_labels' in config_kwargs:\n expected_kwargs['equal_labels'] = config_kwargs['equal_labels']\n\n label_groups = [x.strip() for x in config_kwargs['equal_labels'].split(',')]\n\n equal_labels = []\n for label_group in label_groups:\n equal_labels.append([label.strip() for label in label_group.split(':')])\n\n reactor_dict['image_equal_labels'] = equal_labels\n\n reactor_dict['clusters'] = clusters\n reactor_dict['platform_descriptors'] = [{'platform': 'x86_64',\n 'architecture': 'amd64'}]\n\n workflow.plugin_workspace[ReactorConfigPlugin.key] = {}\n workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\\\n ReactorConfig(reactor_dict)\n\n add_koji_map_in_workflow(workflow, hub_url='/', root_url='')\n\n with open(os.path.join(str(tmpdir), 'osbs.conf'), 'w') as f:\n for plat_clusters in clusters.values():\n for cluster in plat_clusters:\n f.write(dedent(\"\"\"\\\n [{name}]\n openshift_url = https://{name}.com/\n namespace = {name}_namespace\n \"\"\".format(name=cluster['name'])))\n\n goarch = {'x86_64': 'amd64'}\n plugin_args['goarch'] = goarch\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args\n }]\n )\n\n # Update with config_kwargs last to ensure that, when set\n # always has precedence over worker_build_image param.\n if config_kwargs is not None:\n expected_kwargs.update(config_kwargs)\n expected_kwargs['build_from'] = 'image:registry/some_image@sha256:123456'\n\n (flexmock(atomic_reactor.plugins.pre_reactor_config)\n .should_receive('get_openshift_session')\n .and_return(None))\n\n (flexmock(Configuration).should_call('__init__').with_args(**expected_kwargs).once())\n\n build_result = runner.run()\n assert not build_result.is_failed()\n\n assert (build_result.annotations == {\n 'worker-builds': {\n 'x86_64': {\n 'build': {\n 'build-name': 'worker-build-x86_64',\n 'cluster-url': 'https://worker_x86_64.com/',\n 'namespace': 'worker_x86_64_namespace'\n },\n 'digests': [],\n 'plugins-metadata': {}\n }\n }\n })\n\n build_info = get_worker_build_info(workflow, 'x86_64')\n assert build_info.osbs\n\n for record in caplog.records:\n if not record.name.startswith(\"atomic_reactor\"):\n continue\n\n assert hasattr(record, 'arch')\n if record.funcName == 'watch_logs':\n assert record.arch == 'x86_64'\n else:\n assert record.arch == '-'\n\n\n@pytest.mark.parametrize('metadata_fragment', [\n True,\n False\n])\ndef test_orchestrate_build_annotations_and_labels(tmpdir, metadata_fragment):\n workflow = mock_workflow(tmpdir)\n mock_osbs()\n mock_manifest_list()\n\n md = {\n 'metadata_fragment': 'configmap/spam-md',\n 'metadata_fragment_key': 'metadata.json'\n }\n\n def mock_wait_for_build_to_finish(build_name):\n annotations = {\n 'digests': json.dumps([\n {\n 'digest': 'sha256:{}-digest'.format(build_name),\n 'tag': '{}-latest'.format(build_name),\n 'registry': '{}-registry'.format(build_name),\n 'repository': '{}-repository'.format(build_name),\n },\n ]),\n }\n if metadata_fragment:\n annotations.update(md)\n return make_build_response(build_name, 'Complete', annotations)\n\n (flexmock(OSBS)\n .should_receive('wait_for_build_to_finish')\n .replace_with(mock_wait_for_build_to_finish))\n\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'max_cluster_fails': 2,\n 'unreachable_cluster_retry_delay': .1,\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n build_result = runner.run()\n assert not build_result.is_failed()\n\n expected = {\n 'worker-builds': {\n 'x86_64': {\n 'build': {\n 'build-name': 'worker-build-x86_64',\n 'cluster-url': 'https://worker_x86_64.com/',\n 'namespace': 'worker_x86_64_namespace'\n },\n 'digests': [\n {\n 'digest': 'sha256:worker-build-x86_64-digest',\n 'tag': 'worker-build-x86_64-latest',\n 'registry': 'worker-build-x86_64-registry',\n 'repository': 'worker-build-x86_64-repository',\n },\n ],\n 'plugins-metadata': {}\n },\n 'ppc64le': {\n 'build': {\n 'build-name': 'worker-build-ppc64le',\n 'cluster-url': 'https://worker_ppc64le.com/',\n 'namespace': 'worker_ppc64le_namespace'\n },\n 'digests': [\n {\n 'digest': 'sha256:worker-build-ppc64le-digest',\n 'tag': 'worker-build-ppc64le-latest',\n 'registry': 'worker-build-ppc64le-registry',\n 'repository': 'worker-build-ppc64le-repository',\n },\n ],\n 'plugins-metadata': {}\n },\n },\n }\n if metadata_fragment:\n expected['worker-builds']['x86_64'].update(md)\n expected['worker-builds']['ppc64le'].update(md)\n\n assert (build_result.annotations == expected)\n\n build_info = get_worker_build_info(workflow, 'x86_64')\n assert build_info.osbs\n\n koji_upload_dir = get_koji_upload_dir(workflow)\n assert koji_upload_dir\n\n\ndef test_orchestrate_choose_cluster_retry(tmpdir):\n\n mock_osbs()\n mock_manifest_list()\n\n (flexmock(OSBS).should_receive('list_builds')\n .and_raise(OsbsException)\n .and_raise(OsbsException)\n .and_return([1, 2, 3]))\n\n workflow = mock_workflow(tmpdir)\n\n mock_reactor_config(tmpdir, {\n 'x86_64': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in [('chosen_x86_64', 5), ('spam', 4)]\n ],\n 'ppc64le': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in [('chosen_ppc64le', 5), ('ham', 5)]\n ]\n })\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'find_cluster_retry_delay': .1,\n 'max_cluster_fails': 2,\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n runner.run()\n\n\ndef test_orchestrate_choose_cluster_retry_timeout(tmpdir):\n\n mock_manifest_list()\n (flexmock(OSBS).should_receive('list_builds')\n .and_raise(OsbsException)\n .and_raise(OsbsException)\n .and_raise(OsbsException))\n\n workflow = mock_workflow(tmpdir)\n\n mock_reactor_config(tmpdir, {\n 'x86_64': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in [('chosen_x86_64', 5), ('spam', 4)]\n ],\n 'ppc64le': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in [('chosen_ppc64le', 5), ('ham', 5)]\n ]\n })\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'find_cluster_retry_delay': .1,\n 'max_cluster_fails': 2,\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n build_result = runner.run()\n assert build_result.is_failed()\n fail_reason = json.loads(build_result.fail_reason)['ppc64le']['general']\n assert 'Could not find appropriate cluster for worker build.' in fail_reason\n\n\ndef test_orchestrate_build_cancelation(tmpdir):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n mock_osbs()\n mock_manifest_list()\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n def mock_wait_for_build_to_finish(build_name):\n return make_build_response(build_name, 'Running')\n (flexmock(OSBS)\n .should_receive('wait_for_build_to_finish')\n .replace_with(mock_wait_for_build_to_finish))\n\n flexmock(OSBS).should_receive('cancel_build').once()\n\n (flexmock(AsyncResult).should_receive('ready')\n .and_return(False) # normal execution\n .and_return(False) # after cancel_build\n .and_return(True)) # finally succeed\n\n class RaiseOnce(object):\n \"\"\"\n Only raise an exception the first time this mocked wait() method\n is called.\n \"\"\"\n\n def __init__(self):\n self.exception_raised = False\n\n def get(self, timeout=None):\n time.sleep(0.1)\n if not self.exception_raised:\n self.exception_raised = True\n raise BuildCanceledException()\n\n raise_once = RaiseOnce()\n (flexmock(AsyncResult).should_receive('get')\n .replace_with(raise_once.get))\n\n with pytest.raises(PluginFailedException) as exc:\n runner.run()\n assert 'BuildCanceledException' in str(exc.value)\n\n\n@pytest.mark.parametrize(('clusters_x86_64'), (\n ([('chosen_x86_64', 5), ('spam', 4)]),\n ([('chosen_x86_64', 5000), ('spam', 4)]),\n ([('spam', 4), ('chosen_x86_64', 5)]),\n ([('chosen_x86_64', 5), ('spam', 4), ('bacon', 4)]),\n ([('chosen_x86_64', 5), ('spam', 5)]),\n ([('chosen_x86_64', 1), ('spam', 1)]),\n ([('chosen_x86_64', 2), ('spam', 2)]),\n))\n@pytest.mark.parametrize(('clusters_ppc64le'), (\n ([('chosen_ppc64le', 7), ('eggs', 6)]),\n))\ndef test_orchestrate_build_choose_clusters(tmpdir, clusters_x86_64, clusters_ppc64le):\n workflow = mock_workflow(tmpdir)\n mock_osbs() # Current builds is a constant 2\n mock_manifest_list()\n\n mock_reactor_config(tmpdir, {\n 'x86_64': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in clusters_x86_64\n ],\n 'ppc64le': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in clusters_ppc64le\n ]\n })\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n build_result = runner.run()\n assert not build_result.is_failed()\n\n annotations = build_result.annotations\n assert set(annotations['worker-builds'].keys()) == {'x86_64', 'ppc64le'}\n for plat, plat_annotations in annotations['worker-builds'].items():\n assert plat_annotations['build']['cluster-url'] == 'https://chosen_{}.com/'.format(plat)\n\n\n# This test tests code paths that can no longer be hit in actual operation since\n# we exclude platforms with no clusters in check_and_set_platforms.\ndef test_orchestrate_build_unknown_platform(tmpdir): # noqa\n workflow = mock_workflow(tmpdir, platforms=['x86_64', 'spam'])\n mock_osbs()\n mock_manifest_list()\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n # Explicitly leaving off 'eggs' platform to\n # ensure no errors occur when unknow platform\n # is provided in exclude-platform file.\n 'platforms': ['x86_64', 'spam'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n with pytest.raises(PluginFailedException) as exc:\n runner.run()\n\n assert \"No clusters found for platform spam!\" in str(exc.value)\n\n\ndef test_orchestrate_build_failed_create(tmpdir):\n workflow = mock_workflow(tmpdir)\n mock_osbs()\n mock_manifest_list()\n\n def mock_create_worker_build(**kwargs):\n if kwargs['platform'] == 'ppc64le':\n raise OsbsException('it happens')\n return make_build_response('worker-build-1', 'Running')\n (flexmock(OSBS)\n .should_receive('create_worker_build')\n .replace_with(mock_create_worker_build))\n\n fail_reason = 'build not started'\n annotation_keys = {'x86_64'}\n\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'find_cluster_retry_delay': .1,\n 'failure_retry_delay': .1,\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n build_result = runner.run()\n assert build_result.is_failed()\n\n annotations = build_result.annotations\n assert set(annotations['worker-builds'].keys()) == annotation_keys\n fail_reason = json.loads(build_result.fail_reason)['ppc64le']['general']\n assert \"Could not find appropriate cluster for worker build.\" in fail_reason\n\n\n@pytest.mark.parametrize('pod_available,pod_failure_reason,expected,cancel_fails', [\n # get_pod_for_build() returns error\n (False,\n None,\n KeyError,\n False),\n\n # get_failure_reason() not available in PodResponse\n (True,\n AttributeError(\"'module' object has no attribute 'get_failure_reason'\"),\n KeyError,\n False),\n\n # get_failure_reason() result used\n (True,\n {\n 'reason': 'reason message',\n 'exitCode': 23,\n 'containerID': 'abc123',\n },\n {\n 'reason': 'reason message',\n 'exitCode': 23,\n 'containerID': 'abc123',\n },\n False),\n\n # cancel_build() fails (and failure is ignored)\n (True,\n {\n 'reason': 'reason message',\n 'exitCode': 23,\n 'containerID': 'abc123',\n },\n {\n 'reason': 'reason message',\n 'exitCode': 23,\n 'containerID': 'abc123',\n },\n True)\n])\ndef test_orchestrate_build_failed_waiting(tmpdir,\n pod_available,\n pod_failure_reason,\n cancel_fails,\n expected):\n workflow = mock_workflow(tmpdir)\n mock_osbs()\n\n class MockPodResponse(object):\n def __init__(self, pod_failure_reason):\n self.pod_failure_reason = pod_failure_reason\n\n def get_failure_reason(self):\n if isinstance(self.pod_failure_reason, Exception):\n raise self.pod_failure_reason\n\n return self.pod_failure_reason\n\n def mock_wait_for_build_to_finish(build_name):\n if build_name == 'worker-build-ppc64le':\n raise OsbsException('it happens')\n return make_build_response(build_name, 'Failed')\n (flexmock(OSBS)\n .should_receive('wait_for_build_to_finish')\n .replace_with(mock_wait_for_build_to_finish))\n mock_manifest_list()\n\n cancel_build_expectation = flexmock(OSBS).should_receive('cancel_build')\n if cancel_fails:\n cancel_build_expectation.and_raise(OsbsException)\n\n cancel_build_expectation.once()\n\n expectation = flexmock(OSBS).should_receive('get_pod_for_build')\n if pod_available:\n expectation.and_return(MockPodResponse(pod_failure_reason))\n else:\n expectation.and_raise(OsbsException())\n\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n build_result = runner.run()\n assert build_result.is_failed()\n\n annotations = build_result.annotations\n assert set(annotations['worker-builds'].keys()) == {'x86_64', 'ppc64le'}\n fail_reason = json.loads(build_result.fail_reason)['ppc64le']\n\n if expected is KeyError:\n assert 'pod' not in fail_reason\n else:\n assert fail_reason['pod'] == expected\n\n\n@pytest.mark.parametrize(('task_id', 'error'), [\n ('1234567', None),\n ('bacon', 'ValueError'),\n (None, 'TypeError'),\n])\ndef test_orchestrate_build_get_fs_task_id(tmpdir, task_id, error):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n mock_osbs()\n\n mock_reactor_config(tmpdir)\n\n workflow.prebuild_results[PLUGIN_ADD_FILESYSTEM_KEY] = {\n 'filesystem-koji-task-id': task_id,\n }\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n }\n }]\n )\n\n if error is not None:\n with pytest.raises(PluginFailedException) as exc:\n runner.run()\n workflow.build_result.is_failed()\n assert error in str(exc.value)\n\n else:\n build_result = runner.run()\n assert not build_result.is_failed()\n\n\n@pytest.mark.parametrize('fail_at', ('all', 'first'))\ndef test_orchestrate_build_failed_to_list_builds(tmpdir, fail_at):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n mock_osbs() # Current builds is a constant 2\n\n mock_reactor_config(tmpdir, {\n 'x86_64': [\n {'name': 'spam', 'max_concurrent_builds': 5},\n {'name': 'eggs', 'max_concurrent_builds': 5}\n ],\n })\n\n flexmock_chain = flexmock(OSBS).should_receive('list_builds').and_raise(OsbsException(\"foo\"))\n\n if fail_at == 'all':\n flexmock_chain.and_raise(OsbsException(\"foo\"))\n\n if fail_at == 'first':\n flexmock_chain.and_return(['a', 'b'])\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'find_cluster_retry_delay': .1,\n 'max_cluster_fails': 2\n }\n }]\n )\n if fail_at == 'first':\n build_result = runner.run()\n assert not build_result.is_failed()\n\n annotations = build_result.annotations\n assert annotations['worker-builds']['x86_64']['build']['cluster-url'] == 'https://eggs.com/'\n else:\n build_result = runner.run()\n assert build_result.is_failed()\n if fail_at == 'all':\n assert 'Could not find appropriate cluster for worker build.' \\\n in build_result.fail_reason\n\n\n@pytest.mark.parametrize('is_auto', [\n True,\n False\n])\ndef test_orchestrate_build_worker_build_kwargs(tmpdir, caplog, is_auto):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n expected_kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'is_auto': is_auto,\n 'platform': 'x86_64',\n 'release': '10',\n 'arrangement_version': 6,\n 'parent_images_digests': {},\n 'operator_manifests_extract_platform': 'x86_64',\n }\n\n reactor_config_override = mock_reactor_config(tmpdir)\n reactor_config_override['openshift'] = {\n 'auth': {'enable': None},\n 'build_json_dir': None,\n 'insecure': False,\n 'url': 'https://worker_x86_64.com/'\n }\n expected_kwargs['reactor_config_override'] = reactor_config_override\n mock_osbs(worker_expect=expected_kwargs)\n\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'fedora:latest',\n 'osbs_client_config': str(tmpdir),\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n workflow.prebuild_results[CheckAndSetRebuildPlugin.key] = is_auto\n\n build_result = runner.run()\n assert not build_result.is_failed()\n\n\n@pytest.mark.parametrize('overrides', [\n {None: '4242'},\n {'x86_64': '4242'},\n {'x86_64': '4242', None: '1111'},\n])\ndef test_orchestrate_override_build_kwarg(tmpdir, overrides):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n expected_kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'is_auto': False,\n 'platform': 'x86_64',\n 'release': '4242',\n 'arrangement_version': 6,\n 'parent_images_digests': {},\n 'operator_manifests_extract_platform': 'x86_64',\n }\n reactor_config_override = mock_reactor_config(tmpdir)\n reactor_config_override['openshift'] = {\n 'auth': {'enable': None},\n 'build_json_dir': None,\n 'insecure': False,\n 'url': 'https://worker_x86_64.com/'\n }\n expected_kwargs['reactor_config_override'] = reactor_config_override\n mock_osbs(worker_expect=expected_kwargs)\n\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'fedora:latest',\n 'osbs_client_config': str(tmpdir),\n }\n\n for plat, value in overrides.items():\n override_build_kwarg(workflow, 'release', value, plat)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n build_result = runner.run()\n assert not build_result.is_failed()\n\n\n@pytest.mark.parametrize('content_versions', [\n ['v1', 'v2'],\n ['v1'],\n ['v2'],\n])\ndef test_orchestrate_override_content_versions(tmpdir, caplog, content_versions):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n expected_kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'is_auto': False,\n 'platform': 'x86_64',\n 'release': '10',\n 'arrangement_version': 6,\n 'parent_images_digests': {},\n 'operator_manifests_extract_platform': 'x86_64',\n }\n add_config = {\n 'platform_descriptors': [{\n 'platform': 'x86_64',\n 'architecture': 'amd64',\n }],\n 'content_versions': content_versions\n }\n\n reactor_config_override = mock_reactor_config(tmpdir, add_config=add_config)\n reactor_config_override['openshift'] = {\n 'auth': {'enable': None},\n 'build_json_dir': None,\n 'insecure': False,\n 'url': 'https://worker_x86_64.com/'\n }\n\n will_fail = False\n if 'v2' not in content_versions:\n will_fail = True\n else:\n reactor_config_override['content_versions'] = ['v2']\n\n expected_kwargs['reactor_config_override'] = reactor_config_override\n mock_osbs(worker_expect=expected_kwargs)\n\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'fedora:latest',\n 'osbs_client_config': str(tmpdir),\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n build_result = runner.run()\n if will_fail:\n assert build_result.is_failed()\n assert 'failed to create worker build' in caplog.text\n assert 'content_versions is empty' in caplog.text\n else:\n assert not build_result.is_failed()\n\n\n@pytest.mark.parametrize(('build', 'exc_str', 'bc', 'bc_cont', 'ims', 'ims_cont',\n 'ml', 'ml_cont'), [\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name_wrong\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}}},\n \"Build object is malformed, failed to fetch buildroot image\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind_wrong\": \"DockerImage\"}}}}},\n \"Build object is malformed, failed to fetch buildroot image\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"wrong_kind\"}}}}},\n \"Build kind isn't 'DockerImage' but\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"wrong\"}}},\n \"Build config type isn't BuildConfig :\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\"annotations\": {}}},\n \"Build wasn't created from BuildConfig and neither has 'from'\" +\n \" annotation, which is needed for specified arch\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"wrong\"})}}},\n \"Build annotation has unknown 'kind'\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image@sha256:123456\"})}}},\n \"Buildroot image isn't manifest list, which is needed for specified arch\",\n None, None, None, None, False, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"wrong build config\"}}},\n \"Build config not found :\",\n False, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n \"BuildConfig object is malformed\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {}}}}, None, None,\n None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\", \"name\": \"build config\"}}},\n \"BuildConfig object has unknown 'kind'\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"wrong_kind\"}}}}},\n None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n \"ImageStreamTag not found\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"ImageStreamTag\",\n \"name\": \"wrong_ims\"}}}}},\n False, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n \"ImageStreamTag is malformed\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"ImageStreamTag\",\n \"name\": \"ims\"}}}}},\n True, {\"image\": {}}, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n \"Image in imageStreamTag 'ims' is missing Labels\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"ImageStreamTag\",\n \"name\": \"ims\"}}}}},\n True, {\"image\": {\"dockerImageReference\": \"some@sha256:12345\",\n \"dockerImageMetadata\": {\"Config\": {}}}},\n None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image:tag\"})}}},\n \"Buildroot image isn't manifest list, which is needed for specified arch\",\n None, None, None, None, False, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image:tag\"})}}},\n \"Platform for orchestrator 'x86_64' isn't in manifest list\",\n None, None, None, None, True, {\"manifests\": [{\"platform\": {\"architecture\": \"ppc64le\"},\n \"digest\": \"some_image\"}]}),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot@sha256:1949494494\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image:tag\"})}}},\n \"Orchestrator is using image digest 'osbs-buildroot@sha256:1949494494' \" +\n \"which isn't in manifest list\",\n None, None, None, None, True, {\"manifests\": [{\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"some_image\"}]}),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/image@osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image:tag\"})}}},\n \"build_image for platform 'ppc64le' not available\",\n None, None, None, None, True, {\"manifests\": [{\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"osbs-buildroot:latest\"}]}),\n])\ndef test_set_build_image_raises(tmpdir, build, exc_str, bc, bc_cont, ims, ims_cont, ml, ml_cont):\n build = json.dumps(build)\n workflow = mock_workflow(tmpdir)\n\n orchestrator_default_platform = 'x86_64'\n (flexmock(platform)\n .should_receive('processor')\n .and_return(orchestrator_default_platform))\n\n flexmock(os, environ={'BUILD': build})\n mock_osbs()\n mock_reactor_config(tmpdir)\n\n if bc is False:\n (flexmock(Openshift)\n .should_receive('get_build_config')\n .and_raise(OsbsException))\n if bc is True:\n (flexmock(Openshift)\n .should_receive('get_build_config')\n .and_return(bc_cont))\n if ims is False:\n (flexmock(Openshift)\n .should_receive('get_image_stream_tag')\n .and_raise(OsbsException))\n if ims is True:\n (flexmock(Openshift)\n .should_receive('get_image_stream_tag')\n .and_return(fake_imagestream_tag(ims_cont)))\n if ml is False:\n (flexmock(atomic_reactor.util)\n .should_receive('get_manifest_list')\n .and_return(None))\n if ml is True:\n (flexmock(atomic_reactor.util)\n .should_receive('get_manifest_list')\n .and_return(fake_manifest_list(ml_cont)))\n\n plugin_args = {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'osbs-buildroot:latest',\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n with pytest.raises(PluginFailedException) as ex:\n runner.run()\n assert \"raised an exception: RuntimeError\" in str(ex.value)\n assert exc_str in str(ex.value)\n\n\n@pytest.mark.parametrize(('build', 'bc', 'bc_cont', 'ims', 'ims_cont',\n 'ml', 'ml_cont', 'platforms'), [\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}}},\n None, None, None, None, None, None, ['x86_64']),\n\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/osbs-buildroot@sha256:12345\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"ImageStreamTag\",\n \"name\": \"image_stream_tag\"})}}},\n None, None, True,\n {\"image\": {\"dockerImageReference\": \"registry/osbs-buildroot:ims\"}},\n True,\n {\"manifests\": [{\"platform\": {\"architecture\": \"ppc64le\"},\n \"digest\": \"sha256:987654321\"},\n {\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"sha256:12345\"}]},\n ['ppc64le', 'x86_64']),\n\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/osbs-buildroot@sha256:12345\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"ImageStreamTag\",\n \"name\": \"image_stream_tag\"})}}},\n None, None, True,\n {\"image\": {\"dockerImageReference\": \"registry/osbs-buildroot@sha256:12345\",\n \"dockerImageMetadata\": {\n \"Config\": {\n \"Labels\": {\"release\": \"1\", \"version\": \"1.0\"}}}}},\n True,\n {\"manifests\": [{\"platform\": {\"architecture\": \"ppc64le\"},\n \"digest\": \"sha256:987654321\"},\n {\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"sha256:12345\"}]},\n ['ppc64le', 'x86_64']),\n\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/osbs-buildroot@sha256:12345\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n True,\n {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"DockerImage\",\n \"name\": \"registry/osbs-buildroot:bc\"}}}}},\n False, None, True,\n {\"manifests\": [{\"platform\": {\"architecture\": \"ppc64le\"},\n \"digest\": \"sha256:987654321\"},\n {\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"sha256:12345\"}]},\n ['ppc64le', 'x86_64']),\n])\ndef test_set_build_image_works(tmpdir, build, bc, bc_cont, ims, ims_cont, ml, ml_cont,\n platforms):\n build = json.dumps(build)\n workflow = mock_workflow(tmpdir, platforms=platforms)\n\n orchestrator_default_platform = 'x86_64'\n (flexmock(platform)\n .should_receive('processor')\n .and_return(orchestrator_default_platform))\n\n flexmock(os, environ={'BUILD': build})\n mock_osbs()\n mock_reactor_config(tmpdir)\n\n if bc is True:\n (flexmock(Openshift)\n .should_receive('get_build_config')\n .and_return(bc_cont))\n if ims is True:\n (flexmock(Openshift)\n .should_receive('get_image_stream_tag')\n .and_return(fake_imagestream_tag(ims_cont)))\n if ml is True:\n (flexmock(atomic_reactor.util)\n .should_receive('get_manifest_list')\n .and_return(fake_manifest_list(ml_cont)))\n\n plugin_args = {\n 'platforms': platforms,\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'osbs-buildroot:latest',\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n runner.run()\n\n\n@pytest.mark.parametrize(('platforms', 'override'), [\n (['ppc64le', 'x86_64'], ['ppc64le']),\n (['ppc64le'], ['ppc64le']),\n])\ndef test_set_build_image_with_override(tmpdir, platforms, override):\n workflow = mock_workflow(tmpdir, platforms=platforms)\n\n default_build_image = 'registry/osbs-buildroot@sha256:12345'\n build = json.dumps({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": default_build_image, \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\", \"name\": \"build config\"}}})\n flexmock(os, environ={'BUILD': build})\n\n mock_osbs()\n mock_manifest_list()\n mock_orchestrator_platfrom()\n\n build_config = {\"spec\": {\"strategy\": {\n \"customStrategy\": {\n \"from\": {\"kind\": \"DockerImage\",\n \"name\": \"registry/osbs-buildroot:bc\"}}}}}\n (flexmock(Openshift)\n .should_receive('get_build_config')\n .and_return(build_config))\n\n reactor_config = {\n 'version': 1,\n 'clusters': deepcopy(DEFAULT_CLUSTERS),\n 'platform_descriptors': [{'platform': 'x86_64', 'architecture': 'amd64'}],\n 'build_image_override': {plat: 'registry/osbs-buildroot-{}:latest'.format(plat)\n for plat in override},\n }\n\n workflow.plugin_workspace[ReactorConfigPlugin.key] = {}\n workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\\\n ReactorConfig(reactor_config)\n\n add_koji_map_in_workflow(workflow, hub_url='/', root_url='')\n\n plugin_args = {\n 'platforms': platforms,\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{'name': OrchestrateBuildPlugin.key, 'args': plugin_args}]\n )\n\n runner.run()\n\n for plat in platforms:\n used_image = get_worker_build_info(workflow, plat).osbs.build_conf.get_build_from()\n expected_image = 'image:' + reactor_config['build_image_override'].get(plat,\n default_build_image)\n assert used_image == expected_image\n\n\ndef test_no_platforms(tmpdir):\n workflow = mock_workflow(tmpdir, platforms=[])\n mock_osbs()\n mock_reactor_config(tmpdir)\n\n (flexmock(OrchestrateBuildPlugin)\n .should_receive('set_build_image')\n .never())\n\n plugin_args = {\n 'platforms': [],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'osbs-buildroot:latest',\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n with pytest.raises(PluginFailedException) as exc:\n runner.run()\n assert 'No enabled platform to build on' in str(exc.value)\n\n\n@pytest.mark.parametrize('version,warning,exception', (\n (5, None, PluginFailedException),\n (6, None, None),\n))\ndef test_orchestrate_build_validate_arrangements(tmpdir, caplog, version, warning, exception):\n workflow = mock_workflow(tmpdir)\n mock_osbs() # Current builds is a constant 2\n mock_manifest_list()\n\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(arrangement_version=version),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n if exception:\n with pytest.raises(exception):\n runner.run()\n else:\n runner.run()\n\n if warning:\n assert warning in caplog.text\n\n\ndef test_parent_images_digests(tmpdir, caplog):\n \"\"\"Test if manifest digests and media types of parent images are propagated\n correctly to OSBS client\"\"\"\n media_type = 'application/vnd.docker.distribution.manifest.list.v2+json'\n PARENT_IMAGES_DIGESTS = {\n 'registry.fedoraproject.org/fedora:latest': {\n media_type: 'sha256:123456789abcdef',\n }\n }\n\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n workflow.builder.parent_images_digests.update(PARENT_IMAGES_DIGESTS)\n expected_kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'is_auto': False,\n 'platform': 'x86_64',\n 'release': '10',\n 'arrangement_version': 6,\n 'parent_images_digests': PARENT_IMAGES_DIGESTS,\n 'operator_manifests_extract_platform': 'x86_64',\n }\n\n reactor_config_override = mock_reactor_config(tmpdir)\n reactor_config_override['openshift'] = {\n 'auth': {'enable': None},\n 'build_json_dir': None,\n 'insecure': False,\n 'url': 'https://worker_x86_64.com/'\n }\n expected_kwargs['reactor_config_override'] = reactor_config_override\n mock_osbs(worker_expect=expected_kwargs)\n\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'fedora:latest',\n 'osbs_client_config': str(tmpdir),\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n build_result = runner.run()\n assert not build_result.is_failed()\n","sub_path":"tests/plugins/test_orchestrate_build.py","file_name":"test_orchestrate_build.py","file_ext":"py","file_size_in_byte":56656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"106145237","text":"import datetime\nimport json\nimport re\nfrom collections import defaultdict\n\nimport numpy\nimport pandas as pd\nfrom pandas import DataFrame\n\nfrom utils.constant import 会话发起方式, 会话结束方式\n\n\ndef is_df_empty(df, tables):\n return all(df[table].shape[0] == 0 for table in tables)\n\n\ndef default(o): # numpy.int64 无法json化,因此在json.dumps时,要将其转化为int\n if isinstance(o, numpy.integer):\n return int(o)\n\n\nclass BaseStatis(object):\n def __init__(self, df, statis_type=1):\n self.df = df\n self.statis = dict()\n self.statis_type = statis_type\n if \"question_tag\" in self.df:\n self.tags = self._get_tags\n else:\n self.tags = {}\n\n def _table(self, table):\n if table in self.df:\n return self.df[table]\n else:\n return DataFrame({\"id\": []})\n\n def _series_index(self, series, idx):\n \"\"\"\n 根据索引获取一个Series对象的值\n \"\"\"\n if series.size > 0:\n return series.iloc[idx]\n else:\n return {}\n\n def _get_today_date(self, now, start='start'):\n if start == 'start':\n if now:\n return datetime.datetime.combine(\n datetime.date.today(),\n datetime.time.min) - datetime.timedelta(\n days=1)\n else:\n statistic_now = datetime.datetime.now() - datetime.timedelta(hours=1)\n year = statistic_now.year\n month = statistic_now.month\n day = statistic_now.day\n hour = statistic_now.hour\n return datetime.datetime(year=year, day=day, month=month,\n hour=hour)\n\n elif start == 'end':\n if now:\n return datetime.datetime.combine(\n datetime.date.today(),\n datetime.time.max) - datetime.timedelta(\n days=1)\n else:\n statistic_hour = datetime.datetime.now()\n year = statistic_hour.year\n month = statistic_hour.month\n day = statistic_hour.day\n hour = statistic_hour.hour\n return datetime.datetime(year=year, day=day, month=month,\n hour=hour) - datetime.timedelta(\n seconds=1)\n\n def _count(self, ser):\n return int(ser.id.count())\n\n @property\n def _get_tags(self):\n return {\n _tag.id: _tag.name for _tag in self.df[\"question_tag\"].itertuples()\n }\n\n def _json_dumps(self, d):\n return json.dumps(d, ensure_ascii=False, default=default)\n\n def _session_id(self, _id):\n if _id:\n df = self.df[\"chat_session\"]\n serie = df.loc[df[\"user_id\"] == _id]\n else:\n serie = self.df[\"chat_session\"]\n return serie[\"id\"].values\n\n def _kf_response(self, log_table):\n \"\"\"\n 客服回应会话\n :param log_table: chat_log\n :return:\n \"\"\"\n log_table = log_table.loc[\n (log_table.source == \"9\")\n & (log_table.raw.str.contains('\"from\": \"kf\"'))\n & ~(log_table.raw.str.contains('\"msg_type\": \"event\"'))\n & (log_table.raw.str.contains('\"is_sys_send\": 0'))\n ]\n return log_table\n\n def _msg_table(self, log_table):\n \"\"\"\n chat_log消息量\n :param log_table: chat_log\n :return:\n \"\"\"\n msg_table = log_table.loc[\n (log_table.source == \"9\")\n & (\n (log_table.raw.str.contains('\"from\": \"kf\"'))\n | (log_table.raw.str.contains('\"from\": \"user\"'))\n )\n & (log_table.raw.str.contains('\"is_sys_send\": 0'))\n ]\n return msg_table\n\n def _会话量(self, table):\n \"\"\"\n 总的会话数\n :param table: chat_session\n :return:\n \"\"\"\n num = table.loc[table.status == 2].groupby(\"ori_session\").groups\n return len(num)\n\n def _接待量(self, table):\n \"\"\"\n 总的接待数量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[(table.user_id.notnull()) & (table.status == 2)]\n return self._count(df)\n\n def _机器人接待量(self, table):\n \"\"\"\n 机器人会话数量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[(table.user_id.isnull()) & (table.creator == 0)]\n return self._count(df)\n\n def _排队会话量(self, table):\n \"\"\"\n 访客进入排队\n :param table:chat_queue\n :return:\n \"\"\"\n return self._count(table)\n\n def _人工会话量(self, table):\n \"\"\"\n 客服参与的会话数量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[(table.status == 2) & (table.creator.isin([1, 9, 10, 11, 12, 13, 14, 15]))]\n return self._count(df)\n\n def _机器人转人工(self, table):\n \"\"\"\n 机器人转人工\n :param table:\n :return:\n \"\"\"\n df = table.loc[(table.status == 2) & (table.user_id.notnull()) & (table.creator == 1)]\n return self._count(df)\n\n def _人工消息量(self, session_table, log_table):\n \"\"\"\n 客服被动消息量\n :param session_table:\n :param log_table:\n :return:\n \"\"\"\n active_ori_sessions = set(session_table.loc[\n (session_table.status == 2)\n & (session_table.user_id.notnull())\n & (session_table.creator.isin([2, 3]))].ori_session.values)\n\n no_active_sids = set(session_table.loc[\n (session_table.status == 2)\n & (session_table.user_id.notnull())\n & ~(session_table.ori_session.isin(active_ori_sessions))].sid.values)\n\n msg = log_table.loc[\n (log_table.source == \"9\")\n & ~(log_table.raw.str.contains('\"msg_type\": \"event\"'))\n & (\n (log_table.raw.str.contains('\"from\": \"user\"'))\n | (log_table.raw.str.contains('\"from\": \"kf\"'))\n )\n & (\n (log_table.raw.str.contains('\"is_sys_send\": 0'))\n\n )\n & ~(log_table.raw.str.contains('\"text\": \"转机器人\"'))\n & (log_table.sid.isin(no_active_sids))\n ]\n\n visitor_msg = msg.loc[(msg.raw.str.contains('\"from\": \"user\"'))]\n kf_msg = msg.loc[(msg.raw.str.contains('\"from\": \"kf\"'))]\n return {\n \"总消息量\": int(msg.id.count()),\n \"访客消息量\": int(visitor_msg.id.count()),\n \"客服消息量\": int(kf_msg.id.count())\n }\n\n def _满意统计(self, table):\n \"\"\"\n 满意统计\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[(table.user_id.notnull()) & (table.status == 2)]\n df = df.sort_values('created', ascending=False).groupby('ori_session',\n as_index=False).first()\n satisfaction = df[\"satisfaction\"]\n size = satisfaction.size\n satis = satisfaction.value_counts()\n 评价总量 = size\n 非常满意 = satis.get(5, 0)\n 满意 = satis.get(4, 0)\n 一般 = satis.get(3, 0)\n 不满意 = satis.get(2, 0)\n 非常不满意 = satis.get(1, 0)\n 未评价 = 评价总量 - (非常满意 + 满意 + 一般 + 不满意 + 非常不满意)\n if not size:\n return {\"未评价\": 0, \"非常不满意\": 0, \"不满意\": 0, \"一般\": 0, \"满意\": 0,\n \"非常满意\": 0, \"评价总量\": 0}\n return {\"未评价\": 未评价, \"非常不满意\": 非常不满意, \"不满意\": 不满意, \"一般\": 一般, \"满意\": 满意,\n \"非常满意\": 非常满意, \"评价总量\": 评价总量}\n\n def _一次性解决量(self, table):\n \"\"\"\n 一次性解决率\n :param table: chat_session\n :return:\n \"\"\"\n table = table.loc[\n (table.status == 2)\n & (table.one_solved_status == 1)\n & (table.creator.isin([1, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]))]\n return self._count(table)\n\n def _解决方式(self, table):\n \"\"\"\n 访客解决数量\n :param table:\n :return:\n \"\"\"\n human_table = table.loc[(table.status == 2) & (table.question_status == 1) & (table.user_id.notnull())]\n human_deal = int(human_table.user_id.describe()[\"count\"])\n\n # 机器人解决量\n robot_df = table.loc[\n (table.status == 2)\n & (\n (\n (table.creator == 会话发起方式[\"机器人\"])\n & (table.stop_way == 会话结束方式[\"机器人超时结束\"])\n )\n | (\n (table.creator == 会话发起方式[\"客户入队列\"])\n & (table.stop_way.isin([会话结束方式[\"放弃排队\"], 会话结束方式[\"客服都下线出队\"]]))\n )\n )]\n\n return {\"human\": human_deal, \"robot\": self._count(robot_df)}\n\n def _用户咨询分类(self, table):\n \"\"\"\n :param table: chat_session\n :return: {\"tag1\": \"id\": tag1_id, \"count\": 0, \"sub_tags\": {\"id\": tag2_id, \"count\": 0}}\n \"\"\"\n # 用户分类咨询\n df = table.loc[table.user_id.notnull() & (table.status == 2)]\n df = df.sort_values('created', ascending=False).groupby('ori_session',\n as_index=False).first()\n df = df.fillna(value=0)\n total_num = df[\"tag1\"].size\n\n classify, num1, num2 = {\"未分类\": 0}, 0, 0\n for tag in df.itertuples():\n tag1_content = self.tags.get(int(tag.tag1))\n tag2_content = self.tags.get(int(tag.tag2))\n classify[\"分类总数\"] = total_num\n\n if tag1_content:\n if tag1_content not in classify:\n classify[tag1_content] = {\n \"id\": int(tag.tag1),\n \"count\": 1,\n \"sub_tags\": {}\n }\n\n else:\n classify[tag1_content][\"count\"] += 1\n\n if tag2_content not in classify.get(tag1_content).get(\n \"sub_tags\") and tag2_content:\n sdict = {\n tag2_content: {\"id\": int(tag.tag2), \"count\": 1}}\n classify[tag1_content][\"sub_tags\"].update(sdict)\n elif tag2_content in classify.get(tag1_content).get(\n \"sub_tags\") and tag2_content:\n classify[tag1_content][\"sub_tags\"][tag2_content][\n \"count\"] += 1\n else:\n classify[\"未分类\"] += 1\n return classify\n\n def _客服会话时长(self, chat_session, chat_log):\n \"\"\"\n 客服已接待时长(会话段)\n :param chat_session:\n :param chat_log:\n :return: 各会话的时间比\n \"\"\"\n log_sids = set(self._kf_response(chat_log).sid.values)\n reception_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.sid.isin(log_sids))\n & ~(chat_session.creator.isin([2, 3]))]\n session = {\n \"<2m\": 0,\n \"2m-4m\": 0,\n \"4m-6m\": 0,\n \"6m-8m\": 0,\n \">8m\": 0,\n \"all\": 0\n }\n for each_session in reception_session.itertuples():\n _time = (each_session.stop_time - each_session.created).total_seconds()\n if _time <= 120:\n session[\"<2m\"] += 1\n elif 120 < _time <= 240:\n session[\"2m-4m\"] += 1\n elif 240 < _time <= 360:\n session[\"4m-6m\"] += 1\n elif 360 < _time <= 480:\n session[\"6m-8m\"] += 1\n elif _time > 480:\n session[\">8m\"] += 1\n session[\"all\"] += _time\n return session\n\n def _会话时长(self, chat_session, chat_log):\n \"\"\"\n 客服会话时长(按会话量)\n :param chat_session:\n :param chat_log:\n :return:\n \"\"\"\n log_sids = set(self._kf_response(chat_log).sid.values)\n reception_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.sid.isin(log_sids))\n & ~(chat_session.creator.isin([2, 3]))]\n reception_session_ori_session = set(reception_session.ori_session.values)\n rest_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.ori_session.isin(reception_session_ori_session))]\n session = {\n \"<2m\": 0,\n \"2m-4m\": 0,\n \"4m-6m\": 0,\n \"6m-8m\": 0,\n \">8m\": 0,\n \"all\": 0,\n \"total_count\": 0\n }\n for ori_session, dataframe in rest_session.groupby(\"ori_session\"):\n if dataframe.shape[0] != 0:\n _time = (dataframe.iloc[-1].stop_time - dataframe.iloc[0].created).total_seconds()\n if _time <= 120:\n session[\"<2m\"] += 1\n elif 120 < _time <= 240:\n session[\"2m-4m\"] += 1\n elif 240 < _time <= 360:\n session[\"4m-6m\"] += 1\n elif 360 < _time <= 480:\n session[\"6m-8m\"] += 1\n elif _time > 480:\n session[\">8m\"] += 1\n session[\"all\"] += _time\n session[\"total_count\"] += 1\n return session\n\n def _客服响应时长(self, chat_session, chat_log):\n \"\"\"\n 客服响应时长\n :param chat_session:\n :param chat_log:\n :return: 客服 会话段的响应时长\n \"\"\"\n # kf_response\n log_kf_respose = self._kf_response(chat_log)\n sids_useful = set(log_kf_respose.sid.values)\n\n # 找到chat_session对应sid -> created\n sid_createds = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & ~(chat_session.sid.isin([2, 3]))\n & (chat_session.sid.isin(sids_useful))]\n\n sid_created_mapping = {each_session.sid: each_session.created for each_session in sid_createds.itertuples()}\n\n # 筛选满足要求chat_session 去除主动的sid\n not_satisfy_sid = set(chat_session.loc[chat_session.creator.isin([2, 3])].sid.values)\n rest_log = chat_log.loc[chat_log.sid.isin(sids_useful) & ~(chat_log.sid.isin(not_satisfy_sid))]\n\n # 区分每一个sid\n kf_response = {}\n first_response = {}\n for sid, dataframe in rest_log.sort_values('created', ascending=True).groupby('sid', as_index=False):\n sid_list, only_one_kf, user_status = [], [], False\n for each_log in dataframe.itertuples():\n content = each_log.raw\n _type = re.search(r'\"msg_type\": \"event\"', content)\n _from = re.findall(r'\"from\": \"(\\w+)\"', content)\n _sys = re.search(r'\"is_sys_send\": 0', content)\n if _type and _from and not user_status and not _sys:\n if _from[0] == \"kf\":\n if not sid_list:\n sid_list.append({\"from\": \"user\", \"time\": dataframe.iloc[0].created})\n user_status = True\n if not only_one_kf:\n only_one_kf.append({\"from\": \"user\", \"time\": dataframe.iloc[0].created})\n\n if not _type and _from and not user_status and _sys:\n if _from[0] == \"user\":\n sid_list.append({\"from\": \"user\", \"time\": each_log.created})\n if not only_one_kf:\n only_one_kf.append({\"from\": \"user\", \"time\": each_log.created})\n user_status = True\n if user_status and not _type and _from and _sys:\n if sid_list:\n if sid_list[-1][\"from\"] != _from[0]:\n sid_list.append({\"from\": \"kf\", \"time\": each_log.created})\n user_status = False\n if len(only_one_kf) == 1:\n only_one_kf.append({\"from\": \"kf\", \"time\": each_log.created})\n\n if sid_list:\n if sid_list[-1][\"from\"] != \"kf\":\n sid_list.pop(-1)\n if only_one_kf:\n if only_one_kf[-1][\"from\"] != \"kf\":\n only_one_kf.pop(-1)\n\n kf_response[sid] = sid_list\n first_response[sid] = only_one_kf\n\n response = self._cal_response_time(kf_response)\n first_response = self._cal_response_time(first_response)\n return {\n \"响应时长\": response,\n \"响应数\": response.get(\"total_count\", 0),\n \"首次响应时长\": first_response,\n \"首次响应数\": first_response.get(\"total_count\", 0),\n \"30s应答数\": response.get(\"<15s\", 0) + response.get(\"15s-30s\", 0)}\n\n @staticmethod\n def _cal_response_time(time_data):\n \"\"\"\n 处理响应时长\n :return:\n \"\"\"\n response = defaultdict(dict)\n for key, value in time_data.items():\n if len(value) >= 2 and value[-1][\"from\"] != \"kf\":\n value.pop(-1)\n user = value[::2]\n kf = value[1::2]\n response[key] = [\n (each_kf[\"time\"] - each_user[\"time\"]).total_seconds() for each_user, each_kf in zip(user, kf)\n ]\n elif len(value) >= 2 and value[-1][\"from\"] == \"kf\":\n user = value[::2]\n kf = value[1::2]\n response_time = [(each_kf[\"time\"] - each_user[\"time\"]).total_seconds() for each_user, each_kf in\n zip(user, kf)]\n response[key] = response_time\n else:\n response[key] = []\n response_time = {\n \"<15s\": 0,\n \"15s-30s\": 0,\n \"30s-45s\": 0,\n \"45s-1m\": 0,\n \">1m\": 0,\n \"all\": 0,\n \"total_count\": 0\n }\n for sid, each_sid_time in response.items():\n if each_sid_time:\n for value in each_sid_time:\n if value <= 15:\n response_time[\"<15s\"] += 1\n elif 15 < value <= 30:\n response_time[\"15s-30s\"] += 1\n elif 30 < value <= 45:\n response_time[\"30s-45s\"] += 1\n elif 45 < value <= 60:\n response_time[\"45s-1m\"] += 1\n elif value > 60:\n response_time[\">1m\"] += 1\n response_time[\"total_count\"] += 1\n response_time[\"all\"] += value\n\n return response_time\n\n def _响应时长(self, chat_session, chat_log):\n \"\"\"\n 响应时长\n :param table:\n :return:\n \"\"\"\n # 获取有客服接待的会话 根据客服必须接待\n log_table = self._kf_response(chat_log)\n log_sids = set(log_table.sid.values)\n\n reception_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.sid.isin(log_sids))\n & ~(chat_session.creator.isin([2, 3]))]\n\n # 得到有客服响应的会话段 再得到整个会��\n ori_session = set(reception_session.ori_session.values)\n true_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.ori_session.isin(ori_session))\n & ~(chat_session.creator.isin([2, 3]))]\n true_sids = set(true_session.sid.values)\n\n # sid -> ori_session\n sids_ori_session = {\n tuple(set(dataframe.sid.values)): ori_session for ori_session, dataframe in\n true_session.groupby(\"ori_session\")}\n\n # chat_log 消息段包括访客的消息以及客服的消息\n rest_log = chat_log.loc[chat_log.sid.isin(true_sids)]\n\n # 获取sid dataframe 映射\n sid_dataframe = {sid: dataframe for sid, dataframe in rest_log.sort_values(\n by=[\"created\"], inplace=False, ascending=True).groupby(\"sid\")}\n\n ori_session_dataframes = {}\n for sids, ori_session in sids_ori_session.items():\n for sid in sids:\n if ori_session not in ori_session_dataframes:\n ori_session_dataframes[ori_session] = sid_dataframe.get(sid)\n else:\n ori_session_dataframes[ori_session] = pd.concat(\n [ori_session_dataframes[ori_session], sid_dataframe.get(sid)], axis=0).sort_values(\n by=[\"created\"], inplace=False, ascending=True)\n\n response = {}\n first_response = {}\n for ori_session, dataframe in ori_session_dataframes.items():\n sid_list, only_one_kf = [], []\n user_status = False\n for each_log in dataframe.itertuples():\n content = each_log.raw\n _type = re.search(r'\"msg_type\": \"event\"', content)\n _from = re.findall(r'\"from\": \"(\\w+)\"', content)\n _sys = re.search(r'\"is_sys_send\": 0', content)\n if _type and not user_status and _from and not _sys:\n if _from[0] == \"kf\":\n sid_list.append({\"from\": \"user\", \"time\": each_log.created})\n if not only_one_kf:\n only_one_kf.append({\"from\": \"user\", \"time\": each_log.created})\n user_status = True\n if not _type and _from and not user_status and _sys:\n if _from[0] == \"user\":\n sid_list.append({\"from\": \"user\", \"time\": each_log.created})\n if not only_one_kf:\n only_one_kf.append({\"from\": \"user\", \"time\": each_log.created})\n user_status = True\n if user_status and not _type and _from and _sys:\n if sid_list:\n if sid_list[-1][\"from\"] != _from[0]:\n sid_list.append({\"from\": \"kf\", \"time\": each_log.created})\n user_status = False\n if len(only_one_kf) == 1:\n only_one_kf.append({\"from\": \"kf\", \"time\": each_log.created})\n\n if sid_list:\n if sid_list[-1][\"from\"] != \"kf\":\n sid_list.pop(-1)\n if only_one_kf:\n if only_one_kf[-1][\"from\"] != \"kf\":\n only_one_kf.pop(-1)\n\n response[ori_session] = sid_list\n first_response[ori_session] = only_one_kf\n\n response = self._cal_response_time(response)\n first_response = self._cal_response_time(first_response)\n return {\n \"响应时长\": response,\n \"响应数\": response.get(\"total_count\", 0),\n \"首次响应时长\": first_response,\n \"首次响应数\": first_response.get(\"total_count\", 0),\n \"30s应答数\": response.get(\"<15s\", 0) + response.get(\"15s-30s\", 0)}\n\n def _机器人转人工会话量(self, table):\n \"\"\"\n 机器人转人工会话量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[table.user_id.notnull() & (table[\"creator\"] == 1) & (table[\"status\"] == 2)]\n return self._count(df)\n\n def _访客统计_用户来源(self, table):\n \"\"\"\n 访客来源\n :param table: chat_session 与 chat_user\n :return:\n \"\"\"\n session_df = table.get(\"session\")\n 总访客, 用户来源 = [], {\"h5\": [], \"weixin\": []}\n session_df = session_df.loc[\n (session_df.last_session.isnull()) & (session_df.user_id.isnull()) & (session_df[\"status\"] == 2)]\n for uid, dataframe in session_df.groupby(\"uid\"):\n 总访客.append(uid)\n sess = self._series_index(dataframe, 0)\n 用户来源[sess.get(\"source\")].append(uid)\n\n 新访客 = []\n for row in table.get(\"user\").itertuples():\n 新访客.append(row.uid)\n return self._json_dumps({\"总访客\": 总访客, \"新访客\": 新访客}), self._json_dumps(用户来源)\n\n def _进入排队人数(self, table):\n \"\"\"\n 获取排过队的人数\n :param table: chat_queue\n :return: nums\n \"\"\"\n if table.shape[0] == 0:\n return 0\n else:\n table = table.loc[table.status == 2]\n return self._count(table)\n\n def _转人工数量(self, table):\n \"\"\"\n 获取转人工解决量\n :param table: chat_session\n :return: 转人工的次数\n \"\"\"\n if table.shape[0] == 0:\n return 0\n robot_df = table.loc[(table.status == 2) & (table.user_id.isnull())]\n nums = 0\n for each_robot_msg in robot_df.itertuples():\n is_to_kf_status = json.loads(each_robot_msg.ext_bi) if each_robot_msg.ext_bi else {}\n if is_to_kf_status and \"to_kf\" in is_to_kf_status:\n if is_to_kf_status.get(\"to_kf\") == 1:\n nums += 1\n return nums\n\n def _排队进人工会话量(self, table):\n \"\"\"\n 通过排队最终进入人工会话的量\n :param table: table: chat_session\n :return: nums\n \"\"\"\n if table.shape[0] == 0:\n return 0\n else:\n table = table.loc[\n (table.status == 2)\n & (table.creator == 8)\n & (table.stop_way.isin([14, 15, 17, 19, 20]))]\n return self._count(table)\n\n def _服务总时长(self, table, now, statis_type):\n \"\"\"\n 客服服务时长\n :param table: chat_session\n :return: times (s)\n \"\"\"\n start_time = now - datetime.timedelta(days=1) if statis_type == 1 else now - datetime.timedelta(hours=1)\n end_time = now\n table = table.loc[\n (\n (table.user_id.notnull())\n & (table.status == 2)\n ) & (table.creator.isin(\n [\n 会话发起方式[\"客户转人工\"],\n 会话发起方式[\"客服转交客服\"],\n 会话发起方式[\"客服转交客服组\"],\n 会话发起方式[\"客服超时转交\"],\n 会话发起方式[\"客服强制下线转交\"],\n 会话发起方式[\"队列自动接入人工\"],\n 会话发起方式[\"队列手动接入人工\"],\n 会话发起方式[\"队列指派接入人工\"],\n 会话发起方式[\"关闭队列自动接入人工\"],\n 会话发起方式[\"队列指派到客服组\"],\n 会话发起方式[\"机器人转交客服\"],\n 会话发起方式[\"机器人转交客服组\"],\n 会话发起方式[\"强制转交给客服\"],\n 会话发起方式[\"强制转交给客服组\"],\n 会话发起方式[\"客服被动下线转交\"]\n ]))\n ]\n user_data = defaultdict(list)\n for user_id, data in table.groupby(\"user_id\"):\n for each in data.itertuples():\n created = pd.to_datetime(each.created)\n stop_time = pd.to_datetime(each.stop_time)\n user_data[int(user_id)].append([created, stop_time])\n haved_session_user = {}\n for user, user_content in user_data.items():\n haved_session_user[user] = self.cloc_service_time(user_content)\n return haved_session_user\n\n def _总独立接待量(self, chat_session, chat_log):\n \"\"\"\n 客服数据总览-独立接待量\n :param table: chat_session_ext\n :return:\n \"\"\"\n ori_session_ids = []\n chat_session = chat_session.loc[chat_session.user_id.notnull()]\n for ori_session, dataframe in chat_session.groupby(\"ori_session\"):\n if dataframe.iloc[0].creator in [1, 9, 10, 11, 12, 13, 14, 15] and dataframe.shape[0] == 1:\n if dataframe.iloc[0].stop_way not in [9, 10, 23, 24, 25, 26, 28]:\n ori_session_ids.append(ori_session)\n rest_session = chat_session.loc[chat_session.ori_session.isin(ori_session_ids)]\n\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n session_table = rest_session.loc[rest_session.sid.isin(log_sids)]\n\n count = 0\n for ori_session, dataframe in session_table.groupby(\"ori_session\"):\n count += 1\n return count\n\n def _总接待会话量(self, chat_session, chat_log):\n \"\"\"\n 客服数据总览-接待会话量\n :param chat_session: chat_session\n :param chat_log: chat_log\n :return:\n \"\"\"\n ori_session_ids = []\n for ori_session, dataframe in chat_session.groupby(\"ori_session\"):\n if dataframe.iloc[0].creator in [1, 9, 10, 11, 12, 13, 14, 15]:\n ori_session_ids.append(ori_session)\n rest_session = chat_session.loc[chat_session.ori_session.isin(ori_session_ids)]\n\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n session_table = rest_session.loc[rest_session.sid.isin(log_sids)]\n count = 0\n for ori_session, dataframe in session_table.groupby(\"ori_session\"):\n count += 1\n return count\n\n def _接入会话量(self, table):\n \"\"\"\n 客服工作量-接入会话量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.creator.isin(\n [\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17\n 会话发起方式[\"客服被动下线转交\"] # 18\n ])\n )]\n return self._count(df)\n\n def _接待会话量(self, chat_session, chat_log):\n \"\"\"\n 客服工作量-接待会话量\n :param table: chat_session, chat_log\n :return:\n \"\"\"\n ori_session_ids = []\n for ori_session, dataframe in chat_session.groupby(\"ori_session\"):\n if dataframe.iloc[0].creator in [1, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]:\n ori_session_ids.append(ori_session)\n rest_session = chat_session.loc[chat_session.ori_session.isin(ori_session_ids)]\n\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n session_table = rest_session.loc[rest_session.sid.isin(log_sids)]\n count = 0\n for ori_session, dataframe in session_table.groupby(\"ori_session\"):\n count += 1\n return count\n\n def _独立接待量(self, chat_session, chat_log):\n \"\"\"\n 客服工作量-独立接待量\n :param table: chat_session chat_log\n :return:\n \"\"\"\n ori_session_ids = []\n chat_session = chat_session.loc[chat_session.creator != 8]\n for ori_session, dataframe in chat_session.groupby(\"ori_session\"):\n if dataframe.iloc[0].creator in [1, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] and \\\n dataframe.shape[0] == 1:\n if dataframe.iloc[0].stop_way not in [9, 10, 23, 24, 25, 26, 28]:\n ori_session_ids.append(ori_session)\n rest_session = chat_session.loc[chat_session.ori_session.isin(ori_session_ids)]\n\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n session_table = rest_session.loc[rest_session.sid.isin(log_sids)]\n\n count = 0\n for ori_session, dataframe in session_table.groupby(\"ori_session\"):\n count += 1\n return count\n\n def _首次未响应会话量(self, table):\n \"\"\"\n 客服工作量-首次未响应会话量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.stop_way.isin(\n [\n 会话结束方式[\"客服超时结束\"],\n 会话结束方式[\"客服超时转交\"]\n ]\n ))\n ]\n return self._count(df)\n\n def _结束会话量(self, chat_session, chat_log):\n \"\"\"\n 客服工作量-结束会话量\n :param table: chat_session\n :return:\n \"\"\"\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n df = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.sid.isin(log_sids))\n & (chat_session.creator.isin([\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17,\n 会话发起方式[\"客服被动下线转交\"], # 18\n ]))\n & (chat_session.stop_way.isin(\n [\n 会话结束方式[\"客服超时结束\"],\n 会话结束方式[\"客服下线\"],\n 会话结束方式[\"用户手动\"],\n 会话结束方式[\"客服手动\"],\n 会话结束方式[\"用户超时结束\"],\n 会话结束方式[\"客服被动下线\"],\n 会话结束方式[\"客服强制下线结束\"],\n\n ]))\n ]\n return self._count(df)\n\n def _主动会话量(self, table):\n \"\"\"\n 客服工作量-主动会话量\n :param table:\n :return:\n \"\"\"\n df = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.creator.isin(\n [\n 会话发起方式[\"客服激活\"],\n 会话发起方式[\"客服工单发起\"]\n ]\n ))]\n return self._count(df)\n\n def _主动转接量(self, table):\n \"\"\"\n 客服工作量-转接量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.creator.isin([\n\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17,\n 会话发起方式[\"客服被动下线转交\"], # 18\n ]))\n & (table.stop_way.isin([\n 会话结束方式[\"客服手动转交\"],\n 会话结束方式[\"客服转交客服组\"]\n ]))\n ]\n return self._count(df)\n\n def _接待总时长(self, table):\n \"\"\"\n 客服接待总时长\n :param table: chat_session\n :return:\n \"\"\"\n table = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.creator.isin([1, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]))\n ]\n reception_time = 0\n for each_session in table.itertuples():\n reception_time += (each_session.stop_time - each_session.created).total_seconds()\n return reception_time\n\n def _未回复会话量_无效会话量(self, chat_session, chat_log):\n \"\"\"\n 未回复会话量\n :param chat_session:\n :param chat_log:\n :return:\n \"\"\"\n to_kf = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.creator.isin(\n [\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17\n 会话发起方式[\"客服被动下线转交\"] # 18\n ])\n )]\n total_sids = set(to_kf.sid.values)\n\n visit = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"user\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & ~(chat_log.raw.str.contains('\"text\": \"转机器人\"'))\n & ~(chat_log.raw.str.contains('\"msg_type\": \"event\"'))]\n visit_sids = set(visit.sid.values) & total_sids\n\n kf = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & ~(chat_log.raw.str.contains('\"msg_type\": \"event\"'))]\n kf_sids = set(kf.sid.values) & total_sids\n return len(total_sids - kf_sids), len(total_sids - visit_sids)\n\n def _问题解决_问题未解决(self, chat_session):\n \"\"\"\n 客服问题解决\n :param chat_session:\n :return:\n \"\"\"\n solve = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.creator.isin(\n [\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17\n 会话发起方式[\"客服被动下线转交\"] # 18\n ]\n ))\n & (chat_session.question_status == 1)]\n no_solve = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.creator.isin(\n [\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17\n 会话发起方式[\"客服被动下线转交\"] # 18\n ]\n ))\n & (chat_session.question_status == 0)]\n return self._count(solve), self._count(no_solve)\n\n\n @staticmethod\n def cloc_service_time(time_tuple_list):\n '''时间二元组列表, [(开始时间, 结束时间)]'''\n total_seconds = 0\n last_time = \"\"\n for start, end in time_tuple_list:\n if not last_time:\n total_seconds += (end - start).total_seconds()\n else:\n if last_time > start:\n total_seconds += (end - last_time).total_seconds()\n elif last_time <= start:\n total_seconds += (end - start).total_seconds()\n last_time = end\n return total_seconds if total_seconds >= 0 else 0\n\n\nif __name__ == \"__main__\":\n from utils.utils import get_db\n db = get_db()\n df = {}\n start = \"2018-12-05\"\n end = \"2018-12-25\"\n\n df[\"chat_session\"] = pd.read_sql_query(\n \"\"\"\n select c_s2.* from chat_session as c_s2 where c_s2.ori_session in \n (select c_s1.ori_session from chat_session as c_s1 \n where c_s1.created > \"{}\" \n and c_s1.created < \"{}\" and c_s1.sid = c_s1.ori_session)\n \"\"\".format(start, end), db.bind)\n df[\"chat_log\"] = pd.read_sql_query(\n \"\"\"\n select c_l.* from chat_log as c_l join \n (select * from chat_session as c_s2 where c_s2.ori_session in \n (select c_s1.ori_session from chat_session as c_s1 \n where c_s1.created > \"{}\" and c_s1.created < \"{}\" and c_s1.sid = c_s1.ori_session)) as c_s\n on c_l.sid = c_s.sid and c_l.uid = c_s.uid where c_l.created > \"{}\"\n \"\"\".format(start, end, start), db.bind\n )\n df[\"chat_user\"] = pd.read_sql_query(\n \"\"\"\n select * from chat_user where created > '{}' and created <= '{}'\n \"\"\".format(start, end), db.bind)\n df['question_tag'] = pd.read_sql_table('question_tag', db.bind)\n df['users'] = pd.read_sql_table(\"user\", db.bind)\n df[\"kf_status\"] = pd.read_sql_query(\n \"select * from company_setting where name = 'kf_status'\", db.bind)\n df[\"chat_queue\"] = pd.read_sql_query(\n \"select * from chat_queue where start_time > '{}' and start_time <= '{}'\".format(\n start, end), db.bind)\n\n for key, value in df.items():\n df[key] = value.loc[value.cid.isin([149, \"149\"])]\n\n # result = BaseStatis(df, statis_type=1)._会话时长(df[\"chat_session\"], df[\"chat_log\"])\n # result1 = BaseStatis(df, statis_type=1)._客服响应时长(df[\"chat_session\"], df[\"chat_log\"])\n # pprint(result1)\n # print()\n # result1 = BaseStatis(df, statis_type=1)._结束会话量(df[\"chat_session\"], df[\"chat_log\"])\n # result2 = BaseStatis(df, statis_type=1)._响应时长(df[\"chat_session\"], df[\"chat_log\"])\n # pprint(result2)\n\n base = BaseStatis(df, statis_type=1)\n\n db.close()\n","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":47942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"78953551","text":"# coding:utf-8\n\nfrom datetime import datetime\nimport json \n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required, permission_required \nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.db.models import Sum, Count\nfrom django.db import connection\nfrom django.core import serializers\nfrom templated_docs import fill_template\nfrom templated_docs.http import FileResponse\n\n\nfrom .models import Logistics, Bill, Product, Track, Warehouse, Tariff, Map, SendCar, OrderAir, Ticket, Imgs, OrderAir, SubTicket, Settle\nfrom logistics_set.models import Btype, Bill_option, Rate\nfrom customer.models import Customer\nfrom organization.models import Company\nfrom awb import Awb\nfrom extension import is_in_multiple_groups \n\n\ntoday = datetime.now()\nmonths = range(1, (int(today.month) + 1) )\n\n\ndef index(request):\n return render(request, 'logistics/index.html')\n\ndef detail(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n companys = Company.objects.all();\n return render(request, 'logistics/detail.html', {'pk': pk, 'hashid':hashid, 'logistics':logistics, 'companys':companys})\n except:\n return HttpResponseRedirect('/')\n \ndef broad(request):\n return render(request, 'logistics/broad.html')\n\ndef bill(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n # customer = Customer.objects.get(id=logistics.customer_id)\n sql = '''\n select (IFNULL(yingshou.rmb,0) - IFNULL(yingfu.rmb,0)) as res from\n (select sum(rmb) as rmb from logistics_bill where logistics_id = {pk} and bill_type='应收') as yingshou,\n (select sum(rmb) as rmb from logistics_bill where logistics_id = {pk} and bill_type='应付') as yingfu\n '''\n cursor=connection.cursor()\n cursor.execute(sql.format(pk=pk))\n profit = cursor.fetchone()[0]\n bill = Bill.objects.filter(logistics_id=pk)\n btype = Bill_option.objects.filter(btype=u'应收')\n ftype = Bill_option.objects.filter(btype=u'应付')\n rate = Rate.objects.all()\n blist = []\n flist = []\n for i in btype:\n blist.append(i.fee_name)\n for i in ftype:\n flist.append(i.fee_name)\n context = {'logistics': logistics,'bill': bill, 'pk': pk, 'hashid':hashid, 'rate':rate,\n 'blist':blist, 'flist':flist, 'profit':profit}\n return render(request, 'logistics/bill.html', context=context)\n except:\n return HttpResponseRedirect('/')\n \ndef cost(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # customer = Customer.objects.get(id=logistics.customer_id)\n sql = '''\n select (IFNULL(yingshou.rmb,0) - IFNULL(yingfu.rmb,0)) as res from\n (select sum(rmb) as rmb from logistics_bill where logistics_id = {pk} and bill_type='应收') as yingshou,\n (select sum(rmb) as rmb from logistics_bill where logistics_id = {pk} and bill_type='应付') as yingfu\n '''\n cursor=connection.cursor()\n cursor.execute(sql.format(pk=pk))\n profit = cursor.fetchone()[0]\n bill = Bill.objects.filter(logistics_id=pk)\n btype = Bill_option.objects.filter(btype=u'应收')\n ftype = Bill_option.objects.filter(btype=u'应付')\n rate = Rate.objects.all()\n blist = []\n flist = []\n for i in btype:\n blist.append(i.fee_name)\n for i in ftype:\n flist.append(i.fee_name)\n context = {'logistics': logistics,'bill': bill, 'pk': pk, 'hashid':hashid, 'rate':rate,\n 'blist':blist, 'flist':flist, 'profit':profit}\n return render(request, 'logistics/cost.html', context=context)\n except:\n return HttpResponseRedirect('/')\n \n\ndef invoice(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n # customer = Customer.objects.get(id=logistics.customer_id)\n bill = Bill.objects.filter(logistics_id=pk).filter(bill_type=u'应付')\n btype = Bill_option.objects.filter(btype=u'应付')\n rate = Rate.objects.all()\n blist = []\n for i in btype:\n blist.append(i.fee_name)\n cursor = connection.cursor()\n cursor.execute('''select sum(rmb) as total from logistics_bill \n where bill_type='应付' and logistics_id=%s''' %pk)\n out_amount = cursor.fetchone()[0]\n cursor.close()\n context = {'logistics': logistics, 'bill': bill, 'pk': pk, 'hashid':hashid, 'rate':rate,\n 'blist':blist,'out_amount':out_amount}\n return render(request, 'logistics/invoice.html', context=context)\n except:\n return HttpResponseRedirect('/')\n \ndef minvoice(request):\n return render(request, 'logistics/minvoice.html')\n\ndef track(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n tracks = Track.objects.filter(logistics_id=pk)\n # logistics = Logistics.objects.get(id=pk)\n context = {'pk': pk, 'hashid':hashid, 'tracks': tracks,'logistics':logistics}\n return render(request, 'logistics/track.html', context=context)\n except:\n return HttpResponseRedirect('/')\n\n\ndef product(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n products = Product.objects.filter(logistics_id=pk)\n # logistics = Logistics.objects.get(id=pk)\n imgs = Imgs.objects.filter(logistics_id=pk)\n context = {'pk': pk, 'hashid':hashid, 'products': products,'logistics':logistics,'imgs':imgs}\n return render(request, 'logistics/product.html', context=context)\n except:\n return HttpResponseRedirect('/')\n\n\ndef warehouse(request, pk, hashid):\n if not pk and hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n warehouses = Warehouse.objects.filter(logistics_id=pk)\n if len(warehouses) >= 1:\n warehouses = warehouses[0]\n context = {'pk': pk, 'hashid':hashid ,'warehouse': warehouses,'logistics':logistics}\n return render(request, 'logistics/warehouse.html', context=context)\n except:\n return HttpResponseRedirect('/')\n\ndef safe(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n context = {'pk': pk, 'hashid':hashid, 'logistics':logistics}\n return render(request, 'logistics/safe.html', context=context)\n except:\n return HttpResponseRedirect('/')\n\ndef sendcar(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n maps = Map.objects.all()\n warehouses = Warehouse.objects.filter(logistics_id=pk)\n sendcar = SendCar.objects.filter(logistics_id=pk)\n context = {'pk': pk, 'hashid':hashid, 'sendcar': sendcar, 'logistics': logistics, 'maps':maps, 'warehouses': warehouses}\n return render(request, 'logistics/sendcar.html', context=context)\n except:\n return HttpResponseRedirect('/')\n \n\ndef maps(request):\n maps = Map.objects.all()\n return render(request, 'logistics/maps.html', {'maps': maps})\n\n\ndef mticket(request,pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n ticket = Ticket.objects.filter(logistics_id=pk)\n if len(ticket) > 0:\n ticket = ticket[0]\n return render(request, 'logistics/mticket.html', {'pk': pk, 'hashid':hashid,'logistics':logistics,'ticket':ticket})\n except:\n return HttpResponseRedirect('/')\n\ndef awb_print(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n return render(request, 'logistics/awb_print.html', {'pk': pk, 'hashid':hashid ,'logistics':logistics})\n except:\n return HttpResponseRedirect('/')\n \n\ndef subtable(request,pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n sub_id = request.GET.get('sub_id')\n if sub_id:\n # logistics = Logistics.objects.get(id=pk)\n sub_ticket = SubTicket.objects.get(id=sub_id)\n return render(request, 'logistics/subtable.html', {'pk': pk, 'hashid':hashid ,'sub_id':sub_id,'logistics':logistics, 'sub_ticket':sub_ticket })\n else:\n return HttpResponse('错误请求,请联系管理员')\n except:\n return HttpResponseRedirect('/')\n\ndef subtable_list(request,pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n sublist = SubTicket.objects.filter(logistics_id=pk)\n return render(request, 'logistics/subticket_list.html', {'pk': pk,'hashid':hashid ,'logistics':logistics,'sublist':sublist})\n except:\n return HttpResponseRedirect('/')\n\n\ndef achiver(request,pk):\n logistics = Logistics.objects.get(id=pk)\n return render(request, 'logistics/achiver.html', {'logistics': logistics, 'pk': pk, 'hashid':hashid})\n\n\ndef order_air(request,pk,hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n order_air = OrderAir.objects.filter(logistics_id=pk) \n return render(request, 'logistics/order_air.html', {'order_air': order_air, 'pk': pk, 'hashid':hashid, 'logistics': logistics})\n except:\n return HttpResponseRedirect('/')\n\n# \ndef order_air_list(request):\n return render(request, 'airline/cabin.html')\n \n\ndef order_air_list_detail(request,pk):\n orderair = OrderAir.objects.get(id=pk)\n return render(request, 'airline/cabin_detail.html',{'pk':pk,'orderair':orderair})\n\ndef order_air_list_track(request,pk):\n orderair = OrderAir.objects.get(id=pk)\n logistics = Logistics.objects.get(id=orderair.logistics_id)\n return render(request, 'airline/cabin_track.html',{'pk':pk,'orderair':orderair, 'logistics':logistics})\n \n\n@login_required\n@csrf_exempt\ndef order_air_change(request):\n if request.method == 'POST':\n pk = request.POST['pk']\n old = OrderAir.objects.filter(logistics_id=pk)\n for i in old:\n i.order_air_status = u'作废'\n # i.bill_no = null\n i.save()\n return HttpResponse('yes')\n else:\n return HttpResponse('bad request')\n\n\ndef settle(request,pk, hashid):\n '''\n 结算单\n '''\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk) \n bill = Bill.objects.filter(logistics_id=pk)\n instotal = bill.filter(bill_type='应收').aggregate(Sum('rmb')).get('rmb__sum', 0.00)\n outstotal = bill.filter(bill_type='应付').aggregate(Sum('rmb')).get('rmb__sum', 0.00)\n # settle = Settle.objects.get(logistics_id=pk)\n return render(request, 'logistics/settle.html', {'logistics': logistics, 'pk': pk,'hashid':hashid ,'instotal':instotal, 'outstotal':outstotal})\n except:\n return HttpResponseRedirect('/')\n\ndef manifest(request,pk, hashid): \n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n ticket = Ticket.objects.filter(logistics_id=pk)\n if len(ticket) > 0:\n ticket = ticket[0]\n sub_ticket = SubTicket.objects.filter(logistics_id=pk)\n return render(request, 'logistics/manifest.html', {'logistics': logistics, 'pk': pk,'hashid':hashid,'mawb':ticket,'hawb':sub_ticket})\n except:\n return HttpResponseRedirect('/') \n\n@login_required\ndef graph(request):\n return render(request, 'logistics/graph.html')\n\n\ndef onsite(request):\n return render(request, 'logistics/onsite.html')\n \n\ndef onsite_detail(request, pk):\n logistics = Logistics.objects.get(id=pk)\n imgs = Imgs.objects.filter(logistics_id=pk)\n return render(request, 'logistics/onsite_detail.html', {'pk':pk, 'logistics':logistics, 'imgs':imgs})\n \n@login_required\ndef exportAwb(request):\n pk = request.GET.get('pk')\n ticket = Ticket.objects.filter(logistics_id=pk).exists()\n if ticket:\n ticket = Ticket.objects.filter(logistics_id=pk).values()[0]\n logistics = Logistics.objects.filter(id=pk).values('other_fee','main_ticket_number')[0]\n if logistics['other_fee']:\n fees = json.loads(logistics['other_fee'])\n if fees:\n ticket['other_fee'] = fees\n ticket['main_ticket_number'] = logistics['main_ticket_number']\n return render(request, 'odt/awb.html', {'awb':ticket})\n # file = fill_template('odt/awb.ods', ticket, output_format='ods') \n # visible_filename = logistics['main_ticket_number']+'.ods'\n # return FileResponse(file, visible_filename) \n else:\n return HttpResponse(status=404)\n\ndef sign(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n return render(request, 'logistics/sign.html', {'pk':pk,'hashid':hashid, 'logistics':logistics})\n except:\n return HttpResponseRedirect('/')\n\ndef entrust(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n return render(request, 'logistics/entrust.html', {'pk':pk, 'hashid':hashid,'logistics':logistics})\n except:\n return HttpResponseRedirect('/')\n\ndef awb(request):\n return render(request, 'logistics/awb.html')","sub_path":"apps/logistics/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"314792097","text":"#Sentiment Analysis of keyword \"Clinton\" from 2016-11-6 to 2016-10-12\r\n\r\nimport tweepy\r\nfrom textblob import TextBlob\r\n\r\nimport getoldtweets\r\nimport numpy as np\r\nimport operator\r\n\r\n\r\nconsumer_key= 'Consumer key from twitter'\r\nconsumer_secret= 'Consumer secret from twitter'\r\n\r\naccess_token='Access token from twitter'\r\naccess_token_secret='Access token secret from twitter'\r\n\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\n\r\napi = tweepy.API(auth)\r\n\r\ntopic_name = \"Clinton\"\r\n#To find data for week 1\r\nsince_date = \"2016-11-6\"\r\nuntil_date = \"2016-11-12\"\r\n\r\ndef get_label(analysis, threshold = 0):\r\n\tif analysis.sentiment[0]>threshold:\r\n\t\treturn 'Positive'\r\n\telse:\r\n\t\treturn 'Negative'\r\n\r\nall_polarities = dict()\r\nfor topic_name in tweets:\r\n\tthis_topic_polarities = []\r\n\r\n\tthis_topic_tweets = api.search(q=[topic_name, topic], count=10000, since = since_date, until=until_date)\r\n\r\n\twith open('%s_tweets.csv' % topic, 'wb') as this_topic_file:\r\n\t\tthis_topic_file.write('tweet,sentiment_label\\n')\r\n\t\tfor tweet in this_topic_tweets:\r\n\t\t\tanalysis = TextBlob(tweet.text, pos_tagger=PatternTagger(), analyzer=PatternAnalyzer())\r\n\r\n\r\n\t\t\tthis_topic_polarities.append(analysis.sentiment[0])\r\n\t\t\tthis_topic_file.write('%s,%s\\n' % (tweet.text.encode('utf8'), get_label(analysis)))\r\n\r\n\r\n\tall_polarities[topic] = np.mean(this_topic_polarities)\r\n","sub_path":"sentiment_analysis/Clinton week 1.py","file_name":"Clinton week 1.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"601568993","text":"\"\"\"\nCloud file storage is a custom file storage object to store files on GCS\n\"\"\"\n\nimport uuid\nimport random\nimport string\nfrom datetime import datetime\nfrom django.conf import settings\nfrom django.core.files.storage import Storage\nfrom google_helpers import storage_service\nfrom googleapiclient import http\n\nclass CloudFileStorage(Storage):\n\n def __init__(self):\n self.storage = storage_service.get_storage_resource()\n\n def _open(self, name, mode):\n filepath = name.split('/')\n bucket = filepath.pop(0)\n name = '/'.join(filepath)\n return self.storage.objects().get(bucket=bucket, object=name).execute()\n\n #this can potentially cause a bad status line error\n def _save(self, name, content):\n media = http.MediaInMemoryUpload(content.read())\n filepath = name.split('/')\n bucket = filepath.pop(0)\n name = '/'.join(filepath)\n self.storage.objects().insert(\n bucket=bucket,\n name=name,\n media_body=media\n ).execute()\n return bucket + '/' + name\n\n def get_available_name(self, name):\n name = name.replace(\"./\", \"\")\n filepath = name.split('/')\n bucket = filepath.pop(0)\n name = '/'.join(filepath)\n time = datetime.now().strftime('%Y%m%d-%H%M%S%f')\n random_str = ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(8))\n name = time + '-' + random_str + '-' + name\n name = settings.MEDIA_FOLDER + name\n return bucket + '/' + name\n\n def size(self, name):\n filepath = name.split('/')\n bucket = filepath.pop(0)\n name = '/'.join(filepath)\n metadata = self.storage.objects().get(\n bucket=bucket,\n object=name\n ).execute()\n return metadata['size'];\n\n def deconstruct(self):\n return ('google_helpers.cloud_file_storage.CloudFileStorage', [], {})","sub_path":"google_helpers/cloud_file_storage.py","file_name":"cloud_file_storage.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"260827183","text":"# %% import packages\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# %% Model parameters\r\nN = 60500000\r\nkr = 1/7\r\nki0 = 0.25168\r\nke = 1 # α in original paper\r\nc1 = 63.7 # χ2 in original paper\r\nc2 = 0.135 # χ3 in original paper\r\nkca = 1/6 # ν in original paper\r\nn = 0.4 # f in original paper\r\nkc = kca * n # ν1 in original paper\r\nka = kca*(1-n) # ν2 in original paper\r\nTi = 10.5 # day at which the mitigation policy starts\r\n\r\n# %% simulation time settings\r\nTs = 1 # Time step [s]\r\nt_start = 0 \r\nt_stop = 300 \r\nN_sim =int((t_stop - t_start)/Ts) + 1 # Number of Time_steps\r\n\r\n# %% Preallocation of arrays for plotting :\r\nS = np.zeros(N_sim)\r\nV = np.zeros(N_sim)\r\nE = np.zeros(N_sim)\r\nX = np.zeros(N_sim)\r\nI = np.zeros(N_sim)\r\nC = np.zeros(N_sim)\r\nCC = np.zeros(N_sim)\r\nA = np.zeros(N_sim)\r\nR = np.zeros(N_sim)\r\nt= np.linspace(t_start,t_stop,N_sim)\r\n\r\n# %% Initialization :\r\nS[0] = N\r\nE[0] = (c1 + kca) / ke\r\nI[0]= (c1 * c2) / kc\r\nC[0] = 1\r\nCC[0] = 1\r\nA[0] = (ka*I[0])/(kr+c1)\r\nR[0] = 0\r\nX[0] = 1\r\nV[0] = 0\r\n\r\n# %% Simulation loop :\r\nfor k in range(0, N_sim-1):\r\n # Values of U\r\n if 0<= k <=27:\r\n U = 0.9 \r\n elif 28<= k <=33:\r\n U = 0.85\r\n elif 34<= k <=57:\r\n U = 0.2\r\n elif 58<= k <=67:\r\n U = 0.25\r\n elif 68<= k <=95:\r\n U = 0.5\r\n elif 96<= k <=140:\r\n U = 0.85\r\n else:\r\n U = 0.9\r\n # Mitigation Model \r\n dX_dt = (1/Ti)*(U-X[k])\r\n ki = ki0*X[k]\r\n \r\n # Values of Vaccination Efficiency\r\n if 50<= k <=N_sim-1:\r\n p = 0.5 \r\n else:\r\n p = 0\r\n \r\n # Vaccination Model \r\n dV_dt = p*S[k]\r\n \r\n # SEICAR Model\r\n dS_dt = -(ki/N)*(I[k]+A[k])*S[k] - p*S[k]\r\n dE_dt = ((ki/N)*(I[k]+A[k])*S[k]) - ke*E[k]\r\n dI_dt = ke*E[k]-kc*I[k]-ka*I[k]\r\n dC_dt = kc*I[k]-kr*C[k]\r\n dCC_dt = kc*I[k] # for cumulative confirmed cases just considering compartment C\r\n dA_dt = ka*I[k]-kr*A[k]\r\n dR_dt = kr*C[k]+kr*A[k] + p*S[k]\r\n \r\n # State updates using the Euler method :\r\n S[k+1] = S[k] + dS_dt *Ts\r\n E[k+1] = E[k] + dE_dt *Ts\r\n I[k+1] = I[k] + dI_dt *Ts\r\n C[k+1] = C[k] + dC_dt *Ts\r\n CC[k+1] = CC[k] + dCC_dt *Ts\r\n A[k+1] = A[k] + dA_dt *Ts\r\n R[k+1] = R[k] + dR_dt *Ts\r\n X[k+1] = X[k] + dX_dt *Ts\r\n V[k+1] = V[k] + dV_dt *Ts\r\n \r\n# %% Plotting :\r\nplt.close('all')\r\nplt.figure(1)\r\nplt.plot(t, CC)\r\nplt.legend(labels=('Cumulative Confirmed'))\r\nplt.grid()\r\nplt.show()\r\nprint(CC[249])","sub_path":"problem5_part2_with_mitigation.py","file_name":"problem5_part2_with_mitigation.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"564698238","text":"from django.core.mail import send_mail\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db.models import Count\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.generic import ListView\nfrom haystack.query import SearchQuerySet\nfrom .models import Comment, Post\nfrom .forms import CommentForm, EmailPostForm, SearchForm\nfrom taggit.models import Tag\n\n\n# Create your views here.\n\n\n# class PostListView(ListView):\n# queryset = Post.published.all() # This is equivalent to model = Post\n# context_object_name = 'posts'\n# paginate_by = 3\n# template_name = 'blog/post/list.html'\n\n\n# Function based view equivalent to PostListView\ndef post_list(request, tag_slug=None):\n object_list = Post.published.all()\n tag = None\n\n if tag_slug:\n tag = get_object_or_404(Tag, slug=tag_slug)\n object_list = object_list.filter(tags__in=[tag])\n\n posts_per_page = 3 # 3 posts in each page\n paginator = Paginator(object_list, posts_per_page)\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer deliver the first page\n posts = paginator.page(1)\n except EmptyPage:\n # If page is out of range deliver last page of rsults\n posts = paginator.page(paginator.num_pages)\n return render(request,\n 'blog/post/list.html',\n {'page': page,\n 'posts': posts,\n 'tag': tag})\n\n\ndef post_detail(request, year, month, day, post):\n post = get_object_or_404(Post, slug=post,\n status='published',\n publish__year = year,\n publish__month = month,\n publish__day = day)\n\n # List of active comments for this post\n # This is a QuerySet starting from the post object, and calling the related_name\n # attribute from the Comment model\n comments = post.comments.filter(active=True)\n\n if request.method == 'POST':\n # A comment was posted - instantiate the form using the submitted data\n comment_form = CommentForm(data=request.POST)\n\n if comment_form.is_valid():\n # Create Comment object but don't save to database yet\n # save() method creates an instance of the model that the form is\n # linked to\n new_comment = comment_form.save(commit=False)\n # Assign the current post to the comment just created\n new_comment.post = post\n # Save the comment to the database\n new_comment.save()\n else:\n comment_form = CommentForm()\n\n # List of similar posts to the one the user is viewing\n # Retrieve list of tags for the current psot\n post_tags_ids = post.tags.values_list('id', flat=True)\n # Get all similar posts based on tag id, but exclude the current post\n similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)\n # Use the Count aggregation function to generated a calculated field, same_tags\n # that contains number of tags shared with all the tags queried\n similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]\n return render(request,\n 'blog/post/detail.html',\n {'post': post,\n 'comments': comments,\n 'comment_form': comment_form,\n 'similar_posts': similar_posts})\n\ndef post_share(request, post_id):\n # Retrieve post id that will be shared\n post = get_object_or_404(Post, id=post_id, status='published')\n sent = False\n\n if request.method == 'POST':\n # Form was submitted - pull in the data that was submitted\n form = EmailPostForm(request.POST)\n if form.is_valid():\n # Form fields passed validation\n cd = form.cleaned_data\n post_url = request.build_absolute_uri(post.get_absolute_url())\n subject = '{} ({}) recommends you reading \"{}\"'.format(cd['name'], cd['email'], post.title)\n message = 'Read \"{}\" at {}\\n\\n{}\\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])\n send_mail(subject, message, 'admin@myblog.com', [cd['to']])\n sent=True\n else:\n form = EmailPostForm()\n return render(request, 'blog/post/share.html',\n {'post': post,\n 'form': form,\n 'sent': sent})\n\ndef post_search(request):\n # Instantiate the searchform\n form = SearchForm()\n if 'query' in request.GET:\n # When form is submitted, instantiate it\n # with the submitted GET data\n form = SearchForm(request.GET)\n if form.is_valid():\n cd = form.cleaned_data\n # Some issue with a model not being registered/communicated to\n # Haystack.\n r = SearchQuerySet().models(Post).filter(content=cd['query'])\n pk_list = [i.pk for i in r]\n results = Post.objects.filter(pk__in=pk_list)\n # count total results\n total_results = len(results)\n else:\n cd = {}\n results = {}\n total_results = {}\n return render(request,\n 'blog/post/search.html',\n {'form': form,\n 'cd' : cd,\n 'results': results,\n 'total_results': total_results})","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"375572746","text":"#coding=utf8\nimport csv\nimport json\nimport pymongo\nfrom pymongo import MongoClient\n\nimport os\n#处理type8\n\n# 遍历filepath下所有文件,包括子目录\ndef getAllFile(filepath):\n filenames = []\n files = os.listdir(filepath)\n for fi in files:\n fi_d = os.path.join(filepath,fi)\n if os.path.isdir(fi_d):\n getAllFile(fi_d)\n else:\n filenames.append(fi_d)\n # print(os.path.join(filepath,fi_d))\n return filenames\n# 把csv文件的数据以每行作为一个元素存储到到mdbuffer[]数组中\n\ndef readInToArray(filenames):\n # 存放csv中读取的数据\n mdbuffer = []\n flag = 0\n for filename in filenames:\n try:\n # 打开csv文件,设置读的权限\n csvHand = open(filename, \"r+\", encoding='utf-8', errors='ignore')\n # 创建读取csv文件句柄\n readcsv = csv.reader(csvHand)\n # 把csv的数据读取到mdbuffer中\n if flag == 0 :\n for row in readcsv:\n mdbuffer.append(row)\n # print(row)\n else:\n # print(next(readcsv))\n #跳过表中的第一行\n next(readcsv)\n for row in readcsv:\n mdbuffer.append(row)\n except Exception as e:\n print(\"Read Excel error:\", e)\n finally:\n # 关闭csv文件\n print(filename + \"finished\")\n csvHand.close()\n flag = 1\n return mdbuffer\n\ndef readIntoMongo(mdbuffer):\n # 建立MongoDB数据库连接\n # 远程数据库端\n client = MongoClient('36.26.80.184', 27017)\n # 连接所需数据库,test为数据库名\n db = client.bigdata_mongo\n # 连接所用集合,也就是我们通常所说的表,test为表名\n collection = db.indicators\n '''\n # 远程数据库端\n client = MongoClient('10.0.86.60', 27017)\n # 连接所需数据库,test为数据库名\n db = client.bigdata_mongo\n # 连接所用集合,也就是我们通常所说的表,test为表名\n collection = db.indicator\n\n '''\n '''\n #本地数据库测试\n client = MongoClient('localhost', 27017)\n # 连接所需数据库,test为数据库名\n db = client.bigdata_mongo\n # 连接所用集合,也就是我们通常所说的表,test为表名\n collection = db.test\n'''\n #对数据表进行处理\n\n #获取第一行\n head_row1 = mdbuffer[0]\n #获取第二行\n head_row = mdbuffer[1]\n #获得列数\n columnNumber = len(mdbuffer[0])\n # 获取mdbuffer中的元素个数,即数据表的行数\n rowNumber = len(mdbuffer)\n # 处理首行数据\n kind = head_row1[3]\n counrty_set = []\n time = []\n time_set = []\n\n\n #跳过第一行\n '''\n for row in range(1, rowNumber):\n temp = {}\n item = mdbuffer[row]\n counrty.append(item[0])\n time.append(item[5])\n counrty_set = set(counrty)\n time_set = set(time)\n '''\n for row in range(2, rowNumber):\n # propertyJson用来设置每个document的json数据属性格式\n propertyJson = {}\n #temp用来设置每个indicators属性\n temp = {}\n #获取得一行数据\n item = mdbuffer[row]\n propertyJson[\"Country\"] = item[0]\n propertyJson[\"Year\"] = item[2]\n propertyJson[\"Data_source\"] = 'WHO'\n for column in range(3,columnNumber):\n if column < len(item):\n if item[column].strip() == 'No data': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == 'Elimination verified': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == 'No PC required': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == 'Not applicable': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == '..': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == '':\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == 'Not available':\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column].strip() == '[ - ]':\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column].strip() == '[ - 1]':\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column].strip() == '-':\n temp[kind + head_row[column].replace('.', '_')] = ''\n else: # 将字符串转化为float型数值\n if item[column].find('[') != -1:\n # print((item[column][:(item[column].find('[')-1)]).replace(' ',''))\n temp[kind + head_row[column].replace('.', '_')] = float(\n (item[column][:(item[column].find('[') - 1)]).replace(' ', ''))\n # elif item[column].strip().find('[') == 0:\n # temp[head_row[column]] = ''\n else:\n temp[kind + head_row[column].replace('.', '_')] = float((item[column]).replace(' ', ''))\n\n propertyJson[\"indicators\"] = temp\n print(propertyJson)\n #转换成josn的形式以便插入mongodb\n t = json.dumps(propertyJson)\n loaded_entry = json.loads(t)\n try:\n collection.insert_one(loaded_entry)\n except pymongo.errors.DuplicateKeyError as e:\n pass\n\n\nfiles = getAllFile('D:\\\\DataLab_Project\\\\data\\\\open_data\\\\whoi\\\\type8')\n\nfor item in files:\n path = []\n path.append(item)\n file = readInToArray(path)\n readIntoMongo(file)\nprint(len(file))","sub_path":"chentongbao/code/Indicator_Process/Indicator_process/whoi/whoi_process8.py","file_name":"whoi_process8.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565542440","text":"import re\n\n\nclass Rle:\n \"\"\"\n Class for parse and modify\n Conway's game of life rle files.\n \"\"\"\n\n def __init__(self):\n self.__map__ = [[]]\n pass\n\n def string(self):\n \"\"\"\n Create rle string of this object\n (something like \"2ob$obo$bo!\").\n \"\"\"\n\n result = \"\"\n for i in range(len(self.__map__)):\n result += self.__make_native_string__(i)\n\n return Rle.__optimized_string__(result)\n\n def __make_native_string__(self, line):\n result = \"\"\n for cell in self.__map__[line]:\n if cell:\n result += 'o'\n else:\n result += 'b'\n\n return result\n\n @staticmethod\n def __optimized_string__(string):\n fake_element = [\"0x\"]\n elements = re.findall(\"\\d*[ob$]\", string) + fake_element\n previous = (Rle.__element_number__(elements[0]),\n Rle.__element_char__(elements[0]))\n\n result = \"\"\n\n for current in map(Rle.__parse_element__, elements[1::]):\n if current[1] == previous[1]:\n previous[0] += current[0]\n else:\n result += Rle.__make_element__(previous[0], previous[1])\n\n return result\n\n @staticmethod\n def __element_char__(element):\n return element[-1]\n\n @staticmethod\n def __element_number__(element):\n number = re.findall(\"\\d*\", element)[0]\n if number == \"\":\n return 1\n else:\n return int(number)\n\n @staticmethod\n def __parse_element__(element):\n return Rle.__element_number__(element), Rle.__element_char__(element)\n\n @staticmethod\n def __make_element__(number, char):\n if number == 1:\n return char\n else:\n return str(number) + char\n","sub_path":"RLE.py","file_name":"RLE.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"259912412","text":"# -*- coding: utf-8 -*-\nfrom flask import render_template, Flask, request, send_file\nfrom draw import edit_img, INPUT_FILE, FONT, FONT_SIZE\nimport StringIO\nimport logging\n\napp = Flask(__name__)\n\nhandler = logging.StreamHandler()\nhandler.setLevel(logging.INFO)\nhandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))\napp.logger.addHandler(handler)\napp.logger.handlers.extend(logging.getLogger(\"project-zombie.log\").handlers)\n\nlogger = app.logger\n\n@app.route('/', methods=['GET', 'POST'])\ndef generate_zombie():\n if request.method == 'GET':\n logger.error(\"Browser is {}\".format(request.user_agent.browser))\n logger.error(\"uas is {}\".format(request.user_agent.string))\n logger.error(\"platform is {}\".format(request.user_agent.platform))\n return render_template('index.html')\n elif request.method == 'POST':\n name = request.form.get('name').strip()\n logger.error(\"Sent love to {}\".format(name.encode('utf-8')))\n text_array = [name, \"粽有吉祥如意伴您左右\"]\n img = edit_img('tmp', \"tmp\", text_array[0].encode(\"utf-8\"), INPUT_FILE, FONT, FONT_SIZE, text_array, 1000, 10, True)\n img_io = StringIO.StringIO()\n img.save(img_io, 'JPEG', quality=100)\n img_io.seek(0)\n # adjustment for iOS\n as_attachment = False\n if request.user_agent.platform == \"iphone\":\n as_attachment = True\n return send_file(img_io, attachment_filename='wehome.jpg', as_attachment=as_attachment)\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"155185419","text":"from itertools import product\n\ndef threeSplit(a):\n\n s = sum(a) // 3\n foo = [sum(a[:i+1]) for i in range(len(a))]\n bar = [i for i in range(len(a) - 2) if foo[i] == s]\n answer = [foo[i+1:-1].count(2 * s) for i in bar]\n return sum(answer)\n \n \"\"\" Time Limitation\n prod = product(range(len(a) - 1), repeat = 3)\n perms = [i for i in prod if sum(i) == len(a) and i.count(0) == 0]\n ans = [0 for f, s, t in perms if sum(a[:f]) == sum(a[f:f+s]) == sum(a[f+s:f+s+t])]\n return len(ans) \"\"\"\n","sub_path":"arcade/the_core/threeSplit.py","file_name":"threeSplit.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164358189","text":"# userdb.py Control 역할\nimport sqlite3\n\nfrom sql import Sql\nfrom uservo import UserVO\n\n\nclass UserDB:\n def __init__(self, dbName):\n self.__dbName = dbName;\n def getConn(self):\n con = sqlite3.connect(self.__dbName);\n cursor = con.cursor();\n return {'con':con,'cursor':cursor};\n\n def close(self, cc):\n if cc['cursor'] != None:\n cc['cursor'].close();\n if cc['con'] != None:\n cc['con'].close();\n\n def makeTable(self):\n cc = self.getConn();\n cc['cursor'].execute(Sql.make_userdb);\n cc['con'].commit();\n self.close(cc);\n\n def insert(self, u):\n cc = self.getConn();\n cc['cursor'].execute(Sql.insert_userdb,\n (u.getId(),u.getPwd(),u.getName())\n );\n cc['con'].commit();\n self.close(cc);\n print('%s 등록 되었습니다.' % u);\n def delete(self,id):\n print('%s 삭제 되었습니다.' % id);\n def update(self, u):\n print('%s 수정 되었습니다.' % u);\n def select(self, id):\n result = None;\n cc = self.getConn();\n cc['cursor'].execute(Sql.select_userdb , (id,));\n obj = cc['cursor'].fetchone();\n result = UserVO(obj[0],obj[1],obj[2]);\n self.close(cc);\n return result;\n def selectall(self):\n results = [];\n cc = self.getConn();\n cc['cursor'].execute(Sql.selectall_userdb);\n all = cc['cursor'].fetchall();\n for u in all:\n rs = UserVO(u[0],u[1],u[2]);\n results.append(rs);\n self.close(cc);\n return results;\n\n\n\n\n\n","sub_path":"01_python/day088/userdb.py","file_name":"userdb.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"435542524","text":"from sys import stdin, setrecursionlimit\n\n\ndef main():\n input = stdin.buffer.readline\n s = list(input()[:-1].decode())\n n = len(s)\n l = r = -1\n ans = 0\n for i in range(1, n):\n if s[i] == s[i - 1]:\n if l == -1:\n l = i\n else:\n r = i\n if r != -1:\n ans += r - l\n r = l = -1\n if l != -1:\n ans += n - l\n print(min(ans, n - ans))\n\n\nif __name__ == \"__main__\":\n setrecursionlimit(10000)\n main()\n","sub_path":"Python_codes/p03073/s385005653.py","file_name":"s385005653.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297712891","text":"\"\"\"\ndb wrapper for json-box\n\"\"\"\nimport sqlite3\nimport os\n\ntesting = False\n\nif os.getcwd().startswith(\"/var/www\"):\n DBNAME = \"/var/local/logger/logs.db\"\nelse:\n DBNAME = \"logs.db\"\n\nDBFLAGS = sqlite3.PARSE_COLNAMES | sqlite3.PARSE_DECLTYPES\n\n\ndef dict_factory(cursor, row):\n \"\"\"Return a dict for each row\"\"\"\n return {col[0]: row[idx] for idx, col in enumerate(cursor.description)}\n\n\n# a decorator to manage db access\ndef with_db(func):\n \"\"\"Add an extra argument with a database connection\"\"\"\n\n def func_wrapper(*args, **kwargs):\n db = sqlite3.connect(DBNAME, detect_types=DBFLAGS)\n db.row_factory = dict_factory\n result = func(*args, **dict(kwargs, db=db))\n db.commit()\n db.close()\n return result\n\n return func_wrapper\n\n\ndef insert(db, table, insertVerb=\"insert\", **fields):\n \"\"\"Insert an record into a table\"\"\"\n sql = \"%s into %s (%s) values (%s)\" % (\n insertVerb,\n table,\n \", \".join(fields.keys()),\n \", \".join([\"?\"] * len(fields)),\n )\n return db.execute(sql, tuple(fields.values()))\n\n\n@with_db\ndef createTables(db):\n db.execute(\n \"\"\"create table if not exists logs\n (id integer primary key,\n time timestamp,\n ip text,\n ref text,\n message json\n )\"\"\"\n )\n\n\ncreateTables()\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618634547","text":"import csv\nimport os\nimport select\nimport sys\nimport termios\nimport time\nimport tty\nimport RPi.GPIO as GPIO\n\nimport pandas as pd\n\nfrom hx711py.hx711 import HX711 \n\n\ndef cleanAndExit():\n print(\"Cleaning...\")\n GPIO.cleanup()\n print(\"Bye!\")\n sys.exit()\n\ndef setup(hx, reference_unit):\n\n hx.set_reading_format(\"MSB\", \"MSB\")\n hx.set_reference_unit(reference_unit) \n hx.reset() \n hx.tare() \n print(\"Tare done! Add weight now...\")\n\ndef isData():\n return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])\n\n\n\nif __name__ == '__main__':\n subject = str(input(\"Who is the Subject?\\n\"))\n label = 'Not Sitting'\n old_settings = termios.tcgetattr(sys.stdin)\n data = None\n\n hx1 = HX711(14, 15) #8, 10\n #hx2 = HX711(21, 20) #38, 40\n hx3 = HX711(19, 26) #35, 37\n #hx4 = HX711(6, 13) #31, 33\n hx2 = HX711(6, 13)\n hx4 = HX711(21, 20)\n\n setup(hx1, -44)\n setup(hx2, -46)\n setup(hx3, 49)\n setup(hx4, 44)\n\n try:\n tty.setcbreak(sys.stdin.fileno())\n\n i = 0\n is_writing = False\n print('s: Straight')\n print('f: Forward')\n print('b: Backward')\n print('l: Left')\n print('r: Right')\n print('z: Cross Left')\n print('x Cross Right')\n print('y: Start writing')\n print('p: Pause writing')\n print('esc: Exit')\n first_write = False\n while True:\n if isData():\n c = sys.stdin.read(1)\n \n if c == 's':\n label = 'Straight'\n elif c == 'f':\n label = 'Forward'\n elif c == 'b':\n label = 'Backward'\n elif c == 'l':\n label = 'Left'\n elif c == 'r':\n label = 'Right'\n elif c == 'z':\n label = 'Cross Left'\n elif c == 'x':\n label = 'Cross Right'\n elif c == 'n':\n label = 'Not Sitting'\n elif c == 'p':\n # Stop writing\n is_writing = False\n elif c == 'y':\n is_writing = True\n first_write = True\n # Start writing\n print(c)\n print(label)\n elif is_writing:\n\n file_path = '/home/pi/Documents/data/' + subject + '.csv'\n\n if os.path.isfile(file_path) and data is None:\n print('Reading from old file')\n data = pd.read_csv(file_path)\n elif data is None:\n fieldnames = ['Load Cell 1', 'Load Cell 2', 'Load Cell 3', 'Load Cell 4', 'Total', 'Subject', 'Class']\n data = pd.DataFrame(columns=fieldnames)\n\n try:\n scale_num = 0\n sum_ = 0\n row = {}\n for hx in [hx1, hx2, hx3, hx4]:\n #for i in range(1,5):\n scale_num += 1\n val = 6\n val = hx.get_weight(5)\n sum_ += val\n row['Load Cell ' + str(scale_num)] = val\n print('Load Cell # {}: {}'.format(scale_num, val))\n\n row['Total'] = sum_\n row['Subject'] = subject\n row['Class'] = label\n data = data.append(row, ignore_index=True)\n\n print('total {}'.format(sum_))\n\n\n\n hx1.power_down()\n hx1.power_up()\n hx2.power_down()\n hx2.power_up()\n hx3.power_down()\n hx3.power_up()\n hx4.power_down()\n hx4.power_up()\n time.sleep(1)\n\n except (KeyboardInterrupt, SystemExit):\n data.to_csv(file_path, index=False)\n cleanAndExit()\n finally:\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)\n\n\n\n","sub_path":"keyboard_input.py","file_name":"keyboard_input.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322576732","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 1 15:29:29 2016\n\n@author: Chandler\n\"\"\"\nimport pandas as pd \nimport numpy as np \nimport dateutil.relativedelta\npd.options.mode.chained_assignment = None # default='warn'\n\ndef Merge_Orig_Perf(df_orig, df_perf):\n\tdf_orig_temp = df_orig[['loan_seq_number', 'original_interest_rate', 'original_upb']]\n\tdf_orig_temp.rename(columns={'original_interest_rate':'current_interest_rate'}, inplace=True)\n\tdf_orig_temp.rename(columns={'original_upb':'current_actual_upb'}, inplace=True)\n\n\tdf_merged = pd.concat([df_perf, df_orig_temp])\n\tdf_merged['reporting_period'] = pd.to_datetime(df_merged['reporting_period'], format='%m/%d/%Y',\n\t\t\t\t\t\t\t\t\t\t\t\t errors='ignore')\n\tdf_merged['loan_age'].fillna(-1, inplace=True)\n\tdf_merged.sort_values(by=['loan_seq_number', 'loan_age'], ascending=[True,True], \n\t\t\t\t\t\tinplace=True)\n\tdf_merged.fillna(np.nan, inplace=True)\n\t#df_merged.to_csv('freddie_merged.csv', index=False)\n\n\treturn df_merged\n\ndef Remove_Missing_Principal_Bonds(df_merged, df_orig):\n\t\"\"\"\n\t\tBonds who were missing current principal balance midway through.\n\t\"\"\"\n\tdf_merged.set_index('loan_seq_number', inplace=True)\n\tdf_orig.set_index('loan_seq_number', inplace=True)\n\tindex_to_drop = df_merged[df_merged['current_actual_upb'] == 'nan'].index\n\tdf_merged.drop(index_to_drop, inplace=True)\n\tdf_orig.drop(index_to_drop, inplace=True)\n\tdf_merged.reset_index(level=0, inplace=True)\t# reset 'loan_seq_number' to column\n\tdf_orig.reset_index(level=0, inplace=True)\t# reset 'loan_seq_number' to column\n\n\treturn df_merged, df_orig\n\ndef Create_Pay_Cols(df_mtx):\n\t\"\"\"\n\t\tColumns: [0:'loan_seq_number', 1:'current_actual_upb', 2:'current_interest_rate',\n\t\t\t\t 3:'delinquency_status', 4:'loan_age', 5:'remaining_months_to_maturity',\n\t\t\t\t 6:'reporting_period']\n\t\"\"\"\n\t# columns added\n\tcols_added = ['Principal+Interest Paid', 'Interest Paid','Principal Paid', \n\t\t\t\t 'Principal+Prepayment Paid', 'Prepayment Paid']\n\n\t# convert interest rate to monthly decimals\n\tdf_mtx[:, 2] = df_mtx[:, 2] / 100.0 / 12.0\n\n\tint_pay_arr = [0] * df_mtx.shape[0]\n\tamort_pay_arr = [0] * df_mtx.shape[0]\n\tprinc_arr = [0] * df_mtx.shape[0]\n\tprinc_and_ppy_arr = [0] * df_mtx.shape[0]\n\tprepay_arr = [0] * df_mtx.shape[0]\n\n\tfor i in range(df_mtx.shape[0]):\n\t\tif df_mtx[i, 5] == 'nan':\t# remaining_months_to_maturity\n\t\t\t#df_mtx[i, 5] = int(df_mtx[i+1, 5]) + 1\t# fill in original r_m_t_m\n\t\t\tpass\n\t\telse:\n\t\t\tint_pay_arr[i] = df_mtx[i-1, 1] * df_mtx[i, 2]\t# 'interest_paid' column\n\t\t\tamort_pay_arr[i] = (-1)*np.pmt(df_mtx[i, 2], df_mtx[i, 5], df_mtx[i-1, 1])\n\t\t\tprinc_arr[i] = amort_pay_arr[i] - int_pay_arr[i]\n\t\t\tprinc_and_ppy_arr[i] = df_mtx[i-1, 1] - df_mtx[i, 1]\n\t\t\tprepay_arr[i] = princ_and_ppy_arr[i] - princ_arr[i]\n\n\tdf_new_mtx = np.column_stack([df_mtx, amort_pay_arr, int_pay_arr, princ_arr, \n\t\t\t\t\t\t\t\t princ_and_ppy_arr, prepay_arr])\n\n\treturn df_new_mtx, cols_added\n\ndef Calc_Prepay_Percent(df, df_orig):\n\t\"\"\"\n\t\tGroup performance data by 'loan_seq_number'.\n\t\tTake sum of all prepayments, including negative prepayemnts.\n\t\tDivide original loan amount by sum of prepayments to get prepayment %.\n\t\"\"\"\n\tgrouped = df.groupby('loan_seq_number')\n\tprepay_percent_arr = []\n\n\tfor name, group in grouped:\n\t\tprepay_percent_arr.append(\n\t\t\t[name, group['Prepayment Paid'].sum() / group['current_actual_upb'].max()])\n\n\tprepay_percent_arr = np.array(prepay_percent_arr)\n\tdf_orig['Prepay Percent'] = prepay_percent_arr[:,1]\n\n\treturn df_orig\ndef Revise_format(df_orig):\n '''\n Change first_time_homebuyer_flag and prepayment_penalty_flag into dummy variable, change ltv and int rate into decimal number\n '''\n for i in range(len(df_orig['first_time_homebuyer_flag'])):\n df_orig['first_time_homebuyer_flag'][i] = 1 if df_orig['first_time_homebuyer_flag'][i] == 'Y' else 0\n df_orig['prepayment_penalty_flag'][i] = 1 if df_orig['prepayment_penalty_flag'][i] == 'Y' else 0 \n df_orig['original_combined_ltv'] = df_orig['original_combined_ltv']/100\n df_orig['original_interest_rate'] = df_orig['original_interest_rate']/100\n df_orig['original_ltv'] = df_orig['original_ltv']/100\n df_orig['mortgage_insurance_percentage'] = df_orig['mortgage_insurance_percentage']/100\n return df_orig","sub_path":"clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372383749","text":"import sys\nimport os\nimport time\nimport logging\nimport datetime\n\nfrom elasticsearch import ElasticsearchConsumer\nfrom neo4j_connector import Neo4jConnector\n\nlogger = logging.getLogger('ingestor')\n\n\nclass Ingestor(object):\n def __init__(self):\n # Load env vars and compute index names\n logger.info(\"Initialising ingestor\")\n self._parse_config()\n self._compute_indexes()\n\n # Instantiate clients\n logger.info(\"Instantiating clients\")\n self.db = Neo4jConnector()\n self._es_init_clients()\n\n def _parse_config(self):\n \"\"\"\n Fetch the connection string from environment variables:\n\n ELASTIC_URL: The URI of ElasticSearch\n ELASTICSEARCH_USER: Username for ElasticSearch\n ELASTICSEARCH_PASSWORD: Password for ElasticSearch\n ELASTIC_INDEX: ElasticSearch index\n ELASTIC_DRY_RUN: Whether if the ingestion is real or dry-run only\n ES_INDEX_SPEC: Index specification (path to json file)\n \"\"\"\n self.elastic_url = os.environ['ELASTIC_URL']\n self._elastic_user = os.environ['ELASTICSEARCH_USER']\n self._elastic_password = os.environ['ELASTICSEARCH_PASSWORD']\n self.elastic_index = os.environ['ELASTIC_INDEX']\n self.elastic_dry_run = os.environ['ELASTIC_DRY_RUN']\n self.es_index_spec = os.environ['ES_INDEX_SPEC']\n\n def _compute_indexes(self):\n # Compute tag to identify this run\n now = datetime.datetime.now()\n self.run_tag = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n # Define indexes\n self.index_standard = self.elastic_index\n self.index_short_term = \"short-term-{}\".format(self.elastic_index)\n\n # ==========================================================================\n # ES INTEGRATION\n # ==========================================================================\n def _es_init_clients(self):\n \"\"\"\n Instantiate one ES client for each index to be used:\n cartography-<date>\n short-term-cartography-<date>\n \"\"\"\n self.es_clients = []\n for index in [self.index_standard, self.index_short_term]:\n c = ElasticsearchConsumer(\n self.elastic_url,\n index,\n self.elastic_dry_run,\n self.elastic_user,\n self.elastic_password,\n )\n self.es_clients.append(c)\n\n def _es_push_indexes(self, content):\n \"\"\"\n For each ES client, create an index for today's ingestion\n \"\"\"\n for c in self.es_clients:\n c.create_index(content)\n\n def _es_push_results(self, query_name, records):\n \"\"\"\n For each ES client, push the records provided\n \"\"\"\n for c in self.es_clients:\n c.send_to_es(query_name, records)\n\n # ==========================================================================\n # RECORD MANIPULATION\n # ==========================================================================\n def _sanitise_fields(self, record):\n \"\"\"\n ElasticSearch doesn't like parenthesis in the field names,\n so we have to replace them before ingesting the records.\n \"\"\"\n sanitised = {}\n for k, v in record.items():\n new_key = k.replace('(', '_').replace(')', '_')\n sanitised[new_key] = v\n return sanitised\n\n def _enrich_results(self, record, query):\n \"\"\"\n Enrich results from Neo4j with metadata needed by ES\n \"\"\"\n record['metadata.query_name'] = query['name']\n record['metadata.query_id'] = '{}_{}'.format(query['name'], self.run_tag)\n record['metadata.query_description'] = query['description']\n record['metadata.query_headers'] = query['headers']\n record['@timestamp'] = int(round(time.time() * 1000))\n return record\n\n # ==========================================================================\n # EXPOSED OPERATIONS\n # ==========================================================================\n def push_indexes(self):\n with open(self.es_index_spec) as fp:\n content = fp.read()\n self._es_push_indexes(content)\n\n def query_by_tag(self, tags):\n logger.info(\"Querying Neo4J by tags: {}\".format(tags))\n return self.db.query_by_tag(tags)\n\n def push_results(self, queries_results):\n logger.info(\"Pushing query results to ES\")\n for query in queries_results:\n # query = {\n # 'name': 'gcp_project_list',\n # 'description': 'Full list of GCPProjects',\n # 'headers': ['project_id', ...],\n # 'result': [ {...}, ]\n for r in query['result']:\n # Sanitise fields\n sanitised = self._sanitise_fields(r)\n # Enrich data\n enriched = self._enrich_results(sanitised, query)\n # Send to elastic\n self._es_push_results(query['name'], enriched)\n\n\ndef main():\n # Instantiate ingestor\n ingestor = Ingestor()\n\n # Define index\n logger.info(\"Pushing Elasticsearch indexes...\")\n ingestor.push_indexes()\n\n logger.info(\"Starting ingesting data from Neo4j...\")\n\n # Queries - AWS\n queries_results = ingestor.query_by_tag(['cloud', 'aws'])\n ingestor.push_results(queries_results)\n\n # Queries - GCP\n queries_results = ingestor.query_by_tag(['cloud', 'gcp'])\n ingestor.push_results(queries_results)\n\n logger.info(\"Ingestion completed successfully\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"consumers/elasticsearch/deployment/py/ingestor.py","file_name":"ingestor.py","file_ext":"py","file_size_in_byte":5581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626928159","text":"# -*- coding: utf-8 -*-\n\"\"\"Basic raspa output parser.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport re\n\nfrom math import isnan, isinf\nfrom six.moves import range\nfrom six.moves import zip\n\nfloat_base = float # pylint: disable=invalid-name\n\n\ndef float(number): # pylint: disable=redefined-builtin\n number = float_base(number)\n return number if not any((isnan(number), isinf(number))) else None\n\n\nKELVIN_TO_KJ_PER_MOL = float(8.314464919 / 1000.0) #exactly the same as Raspa\n\n# manage block of the first type\n# --------------------------------------------------------------------------------------------\nBLOCK_1_LIST = [\n (re.compile(\"Average Volume:\"), \"cell_volume\", (1, 2, 4), 0),\n (re.compile(\"Average Pressure:\"), \"pressure\", (1, 2, 4), 0),\n (re.compile(\"Average temperature:\"), \"temperature\", (1, 2, 4), 0),\n (re.compile(\"Average Density:\"), \"adsorbate_density\", (1, 2, 4), 0),\n (re.compile(\"Total energy:$\"), \"total_energy\", (1, 2, 4), 0),\n (re.compile(\"Average Heat Capacity\"), \"framework_heat_capacity\", (1, 2, 4), 0),\n (re.compile(\"Heat of desorption:\"), \"heat_of_desorption\", (1, 4, 3), 4),\n (re.compile(\"Enthalpy of adsorption:\"), \"enthalpy_of_adsorption\", (1, 4, 3), 4),\n (re.compile(\".*Total enthalpy of adsorption from components and measured mol-fraction\"),\n \"enthalpy_of_adsorption_total_molfrac\", (1, 4, 3), 0),\n]\n\n# block of box properties.\nBOX_PROP_LIST = [\n (re.compile(\"Average Box-lengths:\"), 'box'),\n]\n\n\n# pylint: disable=too-many-arguments\ndef parse_block1(flines, result_dict, prop, value=1, unit=2, dev=4):\n \"\"\"Parse block that looks as follows:\n Average Volume:\n =================\n Block[ 0] 12025.61229 [A^3]\n Block[ 1] 12025.61229 [A^3]\n Block[ 2] 12025.61229 [A^3]\n Block[ 3] 12025.61229 [A^3]\n Block[ 4] 12025.61229 [A^3]\n ------------------------------------------------------------------------------\n Average 12025.61229 [A^3] +/- 0.00000 [A^3]\n \"\"\"\n for line in flines:\n if 'Average' in line:\n result_dict[prop + '_average'] = float(line.split()[value])\n result_dict[prop + '_unit'] = re.sub(r\"[{}()\\[\\]]\", '', line.split()[unit])\n result_dict[prop + '_dev'] = float(line.split()[dev])\n break\n\n\n# manage energy block\n# --------------------------------------------------------------------------------------------\nENERGY_BLOCK_LIST = [\n (re.compile(\"Average Adsorbate-Adsorbate energy:\"), 'ads_ads'),\n (re.compile(\"Average Host-Adsorbate energy:\"), 'host_ads'),\n]\n\n\ndef parse_block_energy(flines, res_dict, prop):\n \"\"\"Parse block that looks as follows:\n Average Adsorbate-Adsorbate energy:\n ===================================\n Block[ 0] -443.23204 Van der Waals: -443.23204 Coulomb: 0.00000 [K]\n Block[ 1] -588.20205 Van der Waals: -588.20205 Coulomb: 0.00000 [K]\n Block[ 2] -538.43355 Van der Waals: -538.43355 Coulomb: 0.00000 [K]\n Block[ 3] -530.00960 Van der Waals: -530.00960 Coulomb: 0.00000 [K]\n Block[ 4] -484.15106 Van der Waals: -484.15106 Coulomb: 0.00000 [K]\n ------------------------------------------------------------------------------\n Average -516.80566 Van der Waals: -516.805659 Coulomb: 0.00000 [K]\n +/- 98.86943 +/- 98.869430 +/- 0.00000 [K]\n \"\"\"\n for line in flines:\n if 'Average' in line:\n res_dict[prop + '_total_energy_unit'] = 'kJ/mol'\n res_dict[prop + '_vdw_energy_unit'] = 'kJ/mol'\n res_dict[prop + '_coulomb_energy_unit'] = 'kJ/mol'\n res_dict[prop + '_total_energy_average'] = float(line.split()[1]) * KELVIN_TO_KJ_PER_MOL\n res_dict[prop + '_vdw_energy_average'] = float(line.split()[5]) * KELVIN_TO_KJ_PER_MOL\n res_dict[prop + '_coulomb_energy_average'] = float(line.split()[7]) * KELVIN_TO_KJ_PER_MOL\n if '+/-' in line:\n res_dict[prop + '_total_energy_dev'] = float(line.split()[1]) * KELVIN_TO_KJ_PER_MOL\n res_dict[prop + '_vdw_energy_dev'] = float(line.split()[3]) * KELVIN_TO_KJ_PER_MOL\n res_dict[prop + '_coulomb_energy_dev'] = float(line.split()[5]) * KELVIN_TO_KJ_PER_MOL\n return\n\n\n# manage lines with components\n# --------------------------------------------------------------------------------------------\nLINES_WITH_COMPONENT_LIST = [\n (re.compile(\" Average chemical potential: \"), \"chemical_potential\"),\n (re.compile(\" Average Henry coefficient: \"), \"henry_coefficient\"),\n (re.compile(\" Average <U_gh>_1-<U_h>_0:\"), \"adsorption_energy_widom\"),\n (re.compile(\" Average Widom Rosenbluth-weight:\"), \"widom_rosenbluth_factor\"),\n]\n\n\ndef parse_lines_with_component(res_components, components, line, prop):\n \"\"\"Parse lines that contain components\"\"\"\n # self.logger.info(\"analysing line: {}\".format(line))\n for i, component in enumerate(components):\n if '[' + component + ']' in line:\n words = line.split()\n res_components[i][prop + '_unit'] = re.sub(r'[{}()\\[\\]]', '', words[-1])\n res_components[i][prop + '_dev'] = float(words[-2])\n res_components[i][prop + '_average'] = float(words[-4])\n\n\n# pylint: disable=too-many-locals, too-many-arguments, too-many-statements, too-many-branches\ndef parse_base_output(output_abs_path, system_name, ncomponents):\n \"\"\"Parse RASPA output file\"\"\"\n\n warnings = []\n res_per_component = []\n for i in range(ncomponents):\n res_per_component.append({})\n result_dict = {'exceeded_walltime': False}\n framework_density = re.compile(\"Framework Density:\")\n num_of_molec = re.compile(\"Number of molecules:$\")\n\n with open(output_abs_path, \"r\") as fobj:\n # 1st parsing part\n icomponent = 0\n component_names = []\n res_cmp = res_per_component[0]\n for line in fobj:\n if \"Component\" in line and \"(Adsorbate molecule)\" in line:\n component_names.append(line.split()[2][1:-1])\n # Consider to change it with parse_line()\n if \"Conversion factor molecules/unit cell -> mol/kg:\" in line:\n res_cmp['conversion_factor_molec_uc_to_mol_kg'] = float(line.split()[6])\n res_cmp['conversion_factor_molec_uc_to_mol_kg_unit'] = \"(mol/kg)/(molec/uc)\"\n # this line was corrected in Raspa's commit c1ad4de (Nov19), since \"gr/gr\" should read \"mg/g\"\n if \"Conversion factor molecules/unit cell -> gr/gr:\" in line \\\n or \"Conversion factor molecules/unit cell -> mg/g:\" in line:\n res_cmp['conversion_factor_molec_uc_to_mg_g'] = float(line.split()[6])\n res_cmp['conversion_factor_molec_uc_to_mg_g_unit'] = \"(mg/g)/(molec/uc)\"\n if \"Conversion factor molecules/unit cell -> cm^3 STP/gr:\" in line:\n res_cmp['conversion_factor_molec_uc_to_cm3stp_gr'] = float(line.split()[7])\n res_cmp['conversion_factor_molec_uc_to_cm3stp_gr_unit'] = \"(cm^3_STP/gr)/(molec/uc)\"\n if \"Conversion factor molecules/unit cell -> cm^3 STP/cm^3:\" in line:\n res_cmp['conversion_factor_molec_uc_to_cm3stp_cm3'] = float(line.split()[7])\n res_cmp['conversion_factor_molec_uc_to_cm3stp_cm3_unit'] = \"(cm^3_STP/cm^3)/(molec/uc)\"\n if \"MolFraction:\" in line:\n res_cmp['mol_fraction'] = float(line.split()[1])\n res_cmp['mol_fraction_unit'] = \"-\"\n if \"Partial pressure:\" in line:\n res_cmp['partial_pressure'] = float(line.split()[2])\n res_cmp['partial_pressure_unit'] = \"Pa\"\n if \"Partial fugacity:\" in line:\n res_cmp['partial_fugacity'] = float(line.split()[2])\n res_cmp['partial_fugacity_unit'] = \"Pa\"\n icomponent += 1\n if icomponent < ncomponents:\n res_cmp = res_per_component[icomponent]\n else:\n break\n # end of the 1st parsing part\n\n # 2nd parsing part\n for line in fobj:\n for parse in BLOCK_1_LIST:\n if parse[0].match(line):\n parse_block1(fobj, result_dict, parse[1], *parse[2])\n # I assume here that properties per component are present furhter in the output file.\n # so I need to skip some lines:\n skip_nlines_after = parse[3]\n while skip_nlines_after > 0:\n line = next(fobj)\n skip_nlines_after -= 1\n for i, cmpnt in enumerate(component_names):\n # The order of properties per molecule is the same as the order of molecules in the\n # input file. So if component name was not found in the next line, I break the loop\n # immidiately as there is no reason to continue it\n line = next(fobj)\n if cmpnt in line:\n parse_block1(fobj, res_per_component[i], parse[1], *parse[2])\n else:\n break\n skip_nlines_after = parse[3]\n while skip_nlines_after > 0:\n line = next(fobj)\n skip_nlines_after -= 1\n\n continue # no need to perform further checks, propperty has been found already\n for parse in ENERGY_BLOCK_LIST:\n if parse[0].match(line):\n parse_block_energy(fobj, result_dict, prop=parse[1])\n continue # no need to perform further checks, propperty has been found already\n for parse in BOX_PROP_LIST:\n if parse[0].match(line):\n # parse three cell vectors\n parse_block1(fobj, result_dict, prop='box_ax', value=2, unit=3, dev=5)\n parse_block1(fobj, result_dict, prop='box_by', value=2, unit=3, dev=5)\n parse_block1(fobj, result_dict, prop='box_cz', value=2, unit=3, dev=5)\n # parsee angles between the cell vectors\n parse_block1(fobj, result_dict, prop='box_alpha', value=3, unit=4, dev=6)\n parse_block1(fobj, result_dict, prop='box_beta', value=3, unit=4, dev=6)\n parse_block1(fobj, result_dict, prop='box_gamma', value=3, unit=4, dev=6)\n if framework_density.match(line) is not None:\n result_dict['framework_density'] = line.split()[2]\n result_dict['framework_density_unit'] = re.sub(r'[{}()\\[\\]]', '', line.split()[3])\n\n elif num_of_molec.match(line) is not None:\n break # this stops the cycle\n # end of the 2nd parsing part\n\n # 3rd parsing part\n icomponent = 0\n for line in fobj:\n # Consider to change it with parse_line?\n if 'Average loading absolute [molecules/unit cell]' in line:\n res_per_component[icomponent]['loading_absolute_average'] = float(line.split()[5])\n res_per_component[icomponent]['loading_absolute_dev'] = float(line.split()[7])\n res_per_component[icomponent]['loading_absolute_unit'] = 'molecules/unit cell'\n elif 'Average loading excess [molecules/unit cell]' in line:\n res_per_component[icomponent]['loading_excess_average'] = float(line.split()[5])\n res_per_component[icomponent]['loading_excess_dev'] = float(line.split()[7])\n res_per_component[icomponent]['loading_excess_unit'] = 'molecules/unit cell'\n icomponent += 1\n if icomponent >= ncomponents:\n break\n # end of the 3rd parsing part\n\n # 4th parsing part\n for line in fobj:\n for to_parse in LINES_WITH_COMPONENT_LIST:\n if to_parse[0].search(line):\n parse_lines_with_component(res_per_component, component_names, line, to_parse[1])\n # end of the 4th parsing part\n\n return_dictionary = {\"general\": result_dict, \"components\": {}}\n\n for name, value in zip(component_names, res_per_component):\n return_dictionary[\"components\"][name] = value\n\n with open(output_abs_path, \"r\") as fobj:\n for line in fobj:\n if \"WARNING\" in line:\n warnings.append((system_name, line))\n return return_dictionary, warnings\n","sub_path":"aiida_raspa/utils/base_parser.py","file_name":"base_parser.py","file_ext":"py","file_size_in_byte":12776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"70016444","text":"import pytest\n\nfrom django.urls import reverse\n\n\n@pytest.fixture(autouse=True)\ndef setup(mock_cases_search, authorized_client, queue_pk, mock_queue, mock_countries):\n yield\n\n\n@pytest.mark.parametrize(\n \"url\",\n [\n reverse(\"core:index\"),\n reverse(\"queues:cases\"),\n reverse(\"queues:cases\", kwargs={\"queue_pk\": \"00000000-0000-0000-0000-000000000001\"}),\n ],\n)\ndef test_cases_view(url, authorized_client):\n response = authorized_client.get(url)\n assert response.status_code == 200\n","sub_path":"unit_tests/caseworker/queues/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"511954193","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport xlrd\nimport xlsxwriter\nfrom tqdm import tqdm\n\n\ndef find_miss_post(filepath):\n filename_list = []\n for file in os.listdir(filepath):\n if file.endswith('xlsx'):\n filename_list.append(int(file.split('.')[0]))\n filename_list.sort()\n max_post = filename_list[-1]\n for ele in range(0, max_post):\n if (ele+1) not in filename_list:\n print(str(ele)+' is not exist')\n\n\n# 获取目录下的所有文件名\ndef get_filename(tar_path):\n filename_list = []\n for file in os.listdir(tar_path):\n if file.endswith('xlsx'):\n filename_list.append(int(file.split('.')[0]))\n filename_list.sort()\n filename = []\n for file in filename_list:\n filename.append(tar_path+'/'+str(file)+'.xlsx')\n return filename\n\n\ndef concat_and_insert(f_dir):\n records = []\n print('read xlsx')\n for ai in tqdm(f_dir):\n # 读文件\n data = xlrd.open_workbook(ai)\n # 第一个sheet页的名称\n first_sheet = data.sheet_by_index(0).name\n # print(ai, '>'*10, first_sheet)\n # 获取sheet页的名称\n sheet = data.sheet_by_name(first_sheet)\n # 获取表的行数\n n_rows = sheet.nrows\n if n_rows == 0:\n print(ai+' is empty')\n for i in range(n_rows):\n records.append(sheet.row_values(i))\n return records\n\n\ndef write_file(alist, tar_name):\n tarfile = tar_name + '.xlsx'\n print('write '+tarfile)\n w_new = xlsxwriter.Workbook(tarfile)\n w_add = w_new.add_worksheet(tar_name)\n for row_num, row_data in enumerate(alist):\n w_add.write_row(row_num, 0, row_data)\n w_new.close()\n\n\nif __name__ == '__main__':\n file_path = sys.argv[1]\n\n find_miss_post(file_path)\n\n file_name = get_filename(file_path)\n\n records_all = concat_and_insert(file_name)\n\n tarname = file_path\n write_file(records_all, tarname)\n","sub_path":"each_xlsx_to_one.py","file_name":"each_xlsx_to_one.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"590370906","text":"# encoding: utf-8\n\n\"\"\"\nTest suite for pptx.shapes.shape module\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport pytest\n\nfrom pptx.oxml.shapes.shared import BaseShapeElement\nfrom pptx.oxml.text import CT_TextBody\nfrom pptx.parts.slide import _SlideShapeTree\nfrom pptx.shapes import Subshape\nfrom pptx.shapes.shape import BaseShape\nfrom pptx.text import TextFrame\n\nfrom ..oxml.unitdata.shape import (\n a_cxnSp, a_graphicFrame, a_grpSp, a_grpSpPr, a_p_xfrm, a_pic, an_ext,\n an_off, an_sp, an_spPr, an_xfrm\n)\nfrom ..unitutil import class_mock, instance_mock, loose_mock, property_mock\n\n\nclass DescribeBaseShape(object):\n\n def it_knows_its_shape_id(self, id_fixture):\n shape, shape_id = id_fixture\n assert shape.id == shape_id\n\n def it_knows_its_name(self, name_fixture):\n shape, name = name_fixture\n assert shape.name == name\n\n def it_has_a_position(self, position_get_fixture):\n shape, expected_left, expected_top = position_get_fixture\n assert shape.left == expected_left\n assert shape.top == expected_top\n\n def it_has_dimensions(self, dimensions_get_fixture):\n shape, expected_width, expected_height = dimensions_get_fixture\n assert shape.width == expected_width\n assert shape.height == expected_height\n\n def it_can_change_its_position(self, position_set_fixture):\n shape, left, top, expected_xml = position_set_fixture\n shape.left = left\n shape.top = top\n assert shape._element.xml == expected_xml\n\n def it_can_change_its_dimensions(self, dimensions_set_fixture):\n shape, width, height, expected_xml = dimensions_set_fixture\n shape.width = width\n shape.height = height\n assert shape._element.xml == expected_xml\n\n def it_knows_the_part_it_belongs_to(self, part_fixture):\n shape, parent_ = part_fixture\n part = shape.part\n assert part is parent_.part\n\n def it_knows_whether_it_can_contain_text(self, has_textframe_fixture):\n shape, has_textframe = has_textframe_fixture\n assert shape.has_textframe is has_textframe\n\n def it_knows_whether_it_is_a_placeholder(self, is_placeholder_fixture):\n shape, is_placeholder = is_placeholder_fixture\n assert shape.is_placeholder is is_placeholder\n\n def it_provides_access_to_its_textframe(self, textframe_fixture):\n shape, TextFrame_, txBody_, textframe_ = textframe_fixture\n textframe = shape.textframe\n TextFrame_.assert_called_once_with(txBody_, shape)\n assert textframe is textframe_\n\n def it_raises_when_no_textframe(self, no_textframe_fixture):\n shape = no_textframe_fixture\n with pytest.raises(ValueError):\n shape.textframe\n\n def it_can_set_the_shape_text_to_a_string(self, text_set_fixture):\n shape = text_set_fixture\n shape.text = 'føøbår'\n assert shape.textframe.text == u'føøbår'\n\n def it_raises_on_assign_text_where_no_textframe(\n self, no_textframe_fixture):\n shape = no_textframe_fixture\n with pytest.raises(TypeError):\n shape.text = 'foobar'\n\n # fixtures -------------------------------------------------------\n\n @pytest.fixture(params=[\n ('sp', False), ('sp_with_ext', True),\n ('pic', False), ('pic_with_ext', True),\n ('graphicFrame', False), ('graphicFrame_with_ext', True),\n ('grpSp', False), ('grpSp_with_ext', True),\n ('cxnSp', False), ('cxnSp_with_ext', True),\n ])\n def dimensions_get_fixture(self, request, width, height):\n shape_elm_fixt_name, expect_values = request.param\n shape_elm = request.getfuncargvalue(shape_elm_fixt_name)\n shape = BaseShape(shape_elm, None)\n if not expect_values:\n width = height = None\n return shape, width, height\n\n @pytest.fixture(params=[\n ('sp', 'sp_with_ext'),\n ('pic', 'pic_with_ext'),\n ('graphicFrame', 'graphicFrame_with_ext'),\n ('grpSp', 'grpSp_with_ext'),\n ('cxnSp', 'cxnSp_with_ext'),\n ])\n def dimensions_set_fixture(self, request, width, height):\n start_elm_fixt_name, expected_elm_fixt_name = request.param\n start_elm = request.getfuncargvalue(start_elm_fixt_name)\n shape = BaseShape(start_elm, None)\n expected_xml = request.getfuncargvalue(expected_elm_fixt_name).xml\n return shape, width, height, expected_xml\n\n @pytest.fixture\n def id_fixture(self, shape_elm_, shape_id):\n shape = BaseShape(shape_elm_, None)\n return shape, shape_id\n\n @pytest.fixture(params=[True, False])\n def has_textframe_fixture(self, request, shape_elm_, txBody_):\n has_textframe = request.param\n shape_elm_.txBody = txBody_ if has_textframe else None\n shape = BaseShape(shape_elm_, None)\n return shape, has_textframe\n\n @pytest.fixture(params=[True, False])\n def is_placeholder_fixture(self, request, shape_elm_, txBody_):\n is_placeholder = request.param\n shape_elm_.has_ph_elm = is_placeholder\n shape = BaseShape(shape_elm_, None)\n return shape, is_placeholder\n\n @pytest.fixture\n def name_fixture(self, shape_elm_, shape_name):\n shape = BaseShape(shape_elm_, None)\n return shape, shape_name\n\n @pytest.fixture\n def no_textframe_fixture(self, shape_elm_):\n shape_elm_.txBody = None\n shape = BaseShape(shape_elm_, None)\n return shape\n\n @pytest.fixture\n def part_fixture(self, shapes_):\n parent_ = shapes_\n shape = BaseShape(None, parent_)\n return shape, parent_\n\n @pytest.fixture(params=[\n ('sp', False), ('sp_with_off', True),\n ('pic', False), ('pic_with_off', True),\n ('graphicFrame', False), ('graphicFrame_with_off', True),\n ('grpSp', False), ('grpSp_with_off', True),\n ('cxnSp', False), ('cxnSp_with_off', True),\n ])\n def position_get_fixture(self, request, left, top):\n shape_elm_fixt_name, expect_values = request.param\n shape_elm = request.getfuncargvalue(shape_elm_fixt_name)\n shape = BaseShape(shape_elm, None)\n if not expect_values:\n left = top = None\n return shape, left, top\n\n @pytest.fixture(params=[\n ('sp', 'sp_with_off'),\n ('pic', 'pic_with_off'),\n ('graphicFrame', 'graphicFrame_with_off'),\n ('grpSp', 'grpSp_with_off'),\n ('cxnSp', 'cxnSp_with_off'),\n ])\n def position_set_fixture(self, request, left, top):\n start_elm_fixt_name, expected_elm_fixt_name = request.param\n start_elm = request.getfuncargvalue(start_elm_fixt_name)\n shape = BaseShape(start_elm, None)\n expected_xml = request.getfuncargvalue(expected_elm_fixt_name).xml\n return shape, left, top, expected_xml\n\n @pytest.fixture\n def textframe_fixture(self, shape_elm_, TextFrame_, txBody_, textframe_):\n shape = BaseShape(shape_elm_, None)\n return shape, TextFrame_, txBody_, textframe_\n\n @pytest.fixture\n def text_set_fixture(self, shape_elm_, shape_textframe_):\n shape = BaseShape(shape_elm_, None)\n return shape\n\n # fixture components ---------------------------------------------\n\n @pytest.fixture\n def cxnSp(self):\n return a_cxnSp().with_nsdecls().with_child(an_spPr()).element\n\n @pytest.fixture\n def cxnSp_with_ext(self, width, height):\n return (\n a_cxnSp().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height))))\n ).element\n\n @pytest.fixture\n def cxnSp_with_off(self, left, top):\n return (\n a_cxnSp().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_off().with_x(left).with_y(top))))\n ).element\n\n @pytest.fixture\n def graphicFrame(self):\n # Note that <p:xfrm> element is required on graphicFrame\n return a_graphicFrame().with_nsdecls().with_child(a_p_xfrm()).element\n\n @pytest.fixture\n def graphicFrame_with_ext(self, width, height):\n return (\n a_graphicFrame().with_nsdecls().with_child(\n a_p_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height)))\n ).element\n\n @pytest.fixture\n def graphicFrame_with_off(self, left, top):\n return (\n a_graphicFrame().with_nsdecls().with_child(\n a_p_xfrm().with_child(\n an_off().with_x(left).with_y(top)))\n ).element\n\n @pytest.fixture\n def grpSp(self):\n return (\n a_grpSp().with_nsdecls('p', 'a').with_child(\n a_grpSpPr())\n ).element\n\n @pytest.fixture\n def grpSp_with_ext(self, width, height):\n return (\n a_grpSp().with_nsdecls('p', 'a').with_child(\n a_grpSpPr().with_child(\n an_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height))))\n ).element\n\n @pytest.fixture\n def grpSp_with_off(self, left, top):\n return (\n a_grpSp().with_nsdecls('p', 'a').with_child(\n a_grpSpPr().with_child(\n an_xfrm().with_child(\n an_off().with_x(left).with_y(top))))\n ).element\n\n @pytest.fixture\n def height(self):\n return 654\n\n @pytest.fixture\n def left(self):\n return 123\n\n @pytest.fixture\n def pic(self):\n return a_pic().with_nsdecls().with_child(an_spPr()).element\n\n @pytest.fixture\n def pic_with_off(self, left, top):\n return (\n a_pic().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_off().with_x(left).with_y(top))))\n ).element\n\n @pytest.fixture\n def pic_with_ext(self, width, height):\n return (\n a_pic().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height))))\n ).element\n\n @pytest.fixture\n def shape_elm_(self, request, shape_id, shape_name, txBody_):\n return instance_mock(\n request, BaseShapeElement, shape_id=shape_id,\n shape_name=shape_name, txBody=txBody_\n )\n\n @pytest.fixture\n def shape_id(self):\n return 42\n\n @pytest.fixture\n def shape_name(self):\n return 'Foobar 41'\n\n @pytest.fixture\n def shape_textframe_(self, request):\n return property_mock(request, BaseShape, 'textframe')\n\n @pytest.fixture\n def shapes_(self, request):\n return instance_mock(request, _SlideShapeTree)\n\n @pytest.fixture\n def sp(self):\n return an_sp().with_nsdecls().with_child(an_spPr()).element\n\n @pytest.fixture\n def sp_with_ext(self, width, height):\n return (\n an_sp().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height))))\n ).element\n\n @pytest.fixture\n def sp_with_off(self, left, top):\n return (\n an_sp().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_off().with_x(left).with_y(top))))\n ).element\n\n @pytest.fixture\n def TextFrame_(self, request, textframe_):\n return class_mock(\n request, 'pptx.shapes.shape.TextFrame', return_value=textframe_\n )\n\n @pytest.fixture\n def textframe_(self, request):\n return instance_mock(request, TextFrame)\n\n @pytest.fixture\n def top(self):\n return 456\n\n @pytest.fixture\n def txBody_(self, request):\n return instance_mock(request, CT_TextBody)\n\n @pytest.fixture\n def width(self):\n return 321\n\n\nclass DescribeSubshape(object):\n\n def it_knows_the_part_it_belongs_to(self, subshape_with_parent_):\n subshape, parent_ = subshape_with_parent_\n part = subshape.part\n assert part is parent_.part\n\n # fixtures ---------------------------------------------\n\n @pytest.fixture\n def subshape_with_parent_(self, request):\n parent_ = loose_mock(request, name='parent_')\n subshape = Subshape(parent_)\n return subshape, parent_\n","sub_path":"tests/shapes/test_shape.py","file_name":"test_shape.py","file_ext":"py","file_size_in_byte":12667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618587468","text":"import scipy.integrate as sci\nimport numpy as np\n\nimport pylab\nimport matplotlib.pyplot as plt\n\n# In this file we try to solve numericaly a movement of a ball\n\n\n\n# Input parameter\n\n#----\n# Startvalue\n#----\ny0 = 0 # y-Location\nv_base = 10 # Start velocity in teta direction\nx0 = 0 # x-Location\nt_end = 1 # Duration\ntimeInc = 0.01 # Increment of time\nteta = np.array((0., 10., 30., 45., 60., 80, 90.)) # Throw angle\n\ndef rhs_y(x,t):\n ''' This function is used for solving the equation in y-direction\n\n :param x: Vector used for integration (start value ...)\n :param t: Time factor\n :return: y1_dot, y2_dot: Solution vector (integrated one)\n '''\n y1_dot = x[1]\n y2_dot = -9.81\n return [y1_dot, y2_dot]\n\ndef rhs_x(x,t):\n ''' This function is used for solving the equation in x-direction\n\n :param x: Vector used for integration (start value ...)\n :param t: Time factor\n :return: y1_dot, y2_dot: Solution vector (integrated one)\n '''\n x1_dot = x[1]\n x2_dot = 0\n return [x1_dot, x2_dot]\n\n# Time increment\nt = np.arange(0,t_end,timeInc)\n\n#-----\n## Solution of y-Values\n#----\n# Start values for the numerical method (euler right hand side)\n\nv_y0_base = v_base\nv_x0_base = v_base\nx_final = []\nfor angle in teta:\n v_y0 = v_base* np.sin(angle * np.pi / 180.)\n v_x0 = v_base * np.cos(angle * np.pi / 180.)\n # Call ode integrate\n y_0=[y0, v_y0]\n y=sci.odeint(rhs_y,y_0,t)\n #-----\n ## Solution of x-Values\n #----\n x_0=[x0, v_x0]\n x=sci.odeint(rhs_x,x_0,t)\n\n ## Plot function\n # Time plot functions\n #plt.plot(t,y)\n #plt.plot(t,x)\n # Plotting off x-y location\n x_loc = []\n for x_v_pair in x:\n x_loc.append(x_v_pair[0])\n y_loc = []\n for y_v_pair in y:\n y_loc.append(y_v_pair[0])\n # Analytical functions\n x_ana = v_x0 * t + x0\n y_ana = -0.5 * 9.81 * t**2 + t* v_y0 + y0\n x_max = v_x0 * (2*v_y0/9.81)**0.5+ x0\n # Numerical function\n plt.subplot(311)\n plt.plot(x_loc,y_loc, label=\"ana \"+str(angle) + \"; x_zero \" + str(round(x_max, 1)))\n plt.plot(x_ana,y_ana, label=\"num \"+str(angle))\n plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0.)\n plt.ylabel('y [m]')\n # Correction if the ball hits the ground\n ##plt.ylim(0,max(y_loc))\n plt.title('Throwing a ball x[m]')\n plt.grid(True)\n x_final.append(x_max)\n plt.subplot(337)\n plt.title('Rel, errror y')\n plt.plot(t, (y_loc-y_ana)/y_ana )\n plt.xlabel('t [s]')\n plt.ylabel('(y_num-y_ana)/y_ana')\n\n plt.subplot(338)\n plt.title('Rel, errror x')\n plt.plot(t, (x_loc-x_ana)/x_ana )\n plt.xlabel('t [s]')\n plt.ylabel('(x_num-x_ana)/x_ana')\n\n\n plt.subplot(334)\n plt.title('Abs, errror y')\n plt.plot(t, (y_loc-y_ana) )\n plt.ylabel('(y_num-y_ana)')\n\n plt.subplot(335)\n plt.title('Abs, errror x')\n plt.plot(t, (x_loc-x_ana))\n plt.ylabel('(x_num-x_ana)')\nplt.show()\nprint(x_final)","sub_path":"EulerWurf.py","file_name":"EulerWurf.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"546653162","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom os import path\nimport wget\n\n\nurl = \"https://www.ccontario.com/thru-the-bible\"\nreqs = requests.get(url)\nsoup = BeautifulSoup(reqs.text, \"html.parser\")\ntest_string = \"https://www.ccontario.com/\"\n# with open(\"C:\\Users\\geral\\Downloads\\Audio.txt\",\"w\") as text_file\n\nurls = []\nfor link in soup.find_all(\"a\"):\n url_text = link.get(\"href\")\n if url_text.startswith(test_string):\n x = (url_text[len(test_string) :]).strip()\n # text_file.write(x)\n print(x)\n try:\n src = f\"https://www.calvarychapelontario.com/teaching/{x}/{x}.zip\"\n save_path = f\"C:\\MotherBibleAudio\\{x}.zip\"\n if not path.exists(save_path):\n\n wget.download(src, save_path)\n print(f\"\\n---------- Completed download {x} ----------\")\n else:\n print(f\"\\n---------- {x} already exists ----------\")\n except:\n print(f\"---------- Could not download {x} ----------\")\n\n\n\"\"\"\nimport bs4\nimport requests\n\nurl = \"https://www.ccontario.com/\"\nr = requests.get(url)\ndata = bs4.BeautifulSoup(r.text, \"html.parser\")\nfor l in data.find_all(\"a\"):\n r = requests.get(url + l[\"href\"])\n print(r.status_code)\n\"\"\"\n","sub_path":"mom_bible_audio.py","file_name":"mom_bible_audio.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241287077","text":"#-*- coding:utf-8 -*-\n__author__ = 'liubiao'\n\nfrom common.getconfig import GetConfig\nfrom common.verify import Verify\nfrom nose.plugins.attrib import attr\nfrom common.requestslib import RequestsLib\nfrom common.getexpectdata import GetExpectData\n\n@attr('hotelroute','hhub3')\nclass TestHotelRoute():\n @classmethod\n def setup_class(self):\n conf = GetConfig()\n #ged = GetExpectDate(r\".\\testproject\\hhub3\\AdminOpenTravelTransaction\\QueryToday\")\n self.verity = Verify()\n self.url = conf.get_conf_value(\"hhub3\", \"url\") + r\"api/Hotel/HotelRoute\"\n self.date = conf.get_conf_dict(\"data\")\n #self.expect_string = ged.get_json_expect_date()\n self.requestslib = RequestsLib()\n\n @classmethod\n def teardown_class(self):\n pass\n\n def test_hotel_route(self):\n u'获取酒店交通信息 '\n params = dict()\n params['HotelID'] = '2000505'\n response = self.requestslib.send_request_by_accesstoken('get',self.url,request_body=params)\n self.verity.by_status(response,200)\n\n","sub_path":"testproject/hhub3/hotel/hotelroute/testhotelroute.py","file_name":"testhotelroute.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"346015636","text":"#!/usr/bin/env python3\n\nfrom ev3dev.auto import *\n\nimport time\n\n#Let the program know that what motors are at what ports.\nmotor1 = Motor(OUTPUT_B)\nmotor2 = Motor(OUTPUT_C)\n\n#Repeat forever\nwhile (True):\n #Turn on motors. Start moving forward.\n motor1.run_forever(speed_sp = 500)\n motor2.run_forever(speed_sp = 500)\n\n #Wait 1 second\n time.sleep(1)\n\n#Move backwards\n\n","sub_path":"pynnova/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"528113895","text":"#General\ndebug = True\noutputUser = False\ndownloadWebPage = False\nsaveWebPage = False\n\n#WebInlees\n#gevondenInfo = {'team':False,'tegenstander':False,'tijd':False,'speelplaats':False}\nblokSize = 80\n\n#reistijd\nthuisAdress = 'Blauwborgje 26a, 9747 AC Groningen, Netherlands'\n\n#Rooster\nverzameltijd = 50\nwedstrijdtijd = 200\nshiftTijd = 200\nbeginTijdDag = 900\nlibo = True\nshifts = 10 if libo else 9\n\n#url is nu nog hardcoded\nurl = 'http://gchc.nl/site/default.asp?option=100&menu=1#iSjFp1MT3i5XdrVH.97' \nhorecaLeden = open('horecaLeden','r')","sub_path":"python/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"426786","text":"# -*- coding:utf-8 -*-\n#安装pymssql模块 pip install pymssql\n\nimport pymssql\n\nclass MSSQL:\n def __init__(self,host,user,pwd,db):\n self.host = host\n self.user = user\n self.pwd = pwd\n self.db = db\n\n def __GetConnect(self):\n if not self.db:\n raise(NameError,\"没有设置数据库信息\")\n self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset=\"utf8\")\n cur = self.conn.cursor()\n if not cur:\n raise(NameError,\"连接数据库失败\")\n else:\n return cur\n\n def ExecQuery(self,sql):\n cur = self.__GetConnect()\n cur.execute(sql)\n resList = cur.fetchall()\n\n #查询完毕后必须关闭连接\n self.conn.close()\n return resList\n\n def ExecNonQuery(self,sql):\n cur = self.__GetConnect()\n cur.execute(sql)\n self.conn.commit()\n self.conn.close()\n\nms = MSSQL(host=\"127.0.0.1\",user=\"sa\",pwd=\"rich123456\",db=\"HRInsurance\")\nreslist = ms.ExecQuery(\"SELECT identity_no From emp where len(identity_no)=18\")\nfor i in reslist:\n print(i)\n'''\nnewsql=\"update webuser set name='%s' where id=1\"%u'测试'\nprint(newsql)\nms.ExecNonQuery(newsql.encode('utf-8'))\n'''\n\n\n\n\n\n\n\n","sub_path":"MSSQL.py","file_name":"MSSQL.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"480862215","text":"import os\nimport sys\nfrom ctypes.util import find_library\n\nimport cffi\n\nif sys.version_info[0] == 3:\n def _reraise(ex):\n raise ex[1].with_traceback(ex[2])\nelse:\n exec('''\ndef _reraise(ex):\n raise ex[1], None, ex[2]\n ''')\n\n_pre_cache_callback_base = ['int', 'const char*', 'void*']\n_pre_callback_base = ['int', 'const char*', 'void*']\n_post_callback_base = ['int', 'int', 'const char*', 'void*']\n_callback_str = lambda c: 'int(%s)' % (', '.join(c))\n_callback_ffi = lambda c, n: 'int (*%s)(%s)' % (n, ','.join(c))\n\n__version__ = 0.2\n\nffi = cffi.FFI()\n\nffi.cdef('''\nvoid cl_init(unsigned int);\nconst char* cl_retdbdir(void);\nconst char* cl_strerror(unsigned int);\nvoid* cl_engine_new();\nint cl_load(const char*, int*, unsigned int*, unsigned int);\nint cl_engine_free(void*);\nvoid cl_engine_compile(void*);\nint cl_scanfile(const char*, const char**, unsigned long*, void*, unsigned int);\nint cl_scanfile_callback(const char*, const char**, unsigned long*, void*, unsigned int, void*);\n\nenum cl_engine_field {\n CL_ENGINE_MAX_SCANSIZE, /* uint64_t */\n CL_ENGINE_MAX_FILESIZE, /* uint64_t */\n CL_ENGINE_MAX_RECURSION, /* uint32_t */\n CL_ENGINE_MAX_FILES, /* uint32_t */\n CL_ENGINE_MIN_CC_COUNT, /* uint32_t */\n CL_ENGINE_MIN_SSN_COUNT, /* uint32_t */\n CL_ENGINE_PUA_CATEGORIES, /* (char *) */\n CL_ENGINE_DB_OPTIONS, /* uint32_t */\n CL_ENGINE_DB_VERSION, /* uint32_t */\n CL_ENGINE_DB_TIME, /* time_t */\n CL_ENGINE_AC_ONLY, /* uint32_t */\n CL_ENGINE_AC_MINDEPTH, /* uint32_t */\n CL_ENGINE_AC_MAXDEPTH, /* uint32_t */\n CL_ENGINE_TMPDIR, /* (char *) */\n CL_ENGINE_KEEPTMP, /* uint32_t */\n CL_ENGINE_BYTECODE_SECURITY, /* uint32_t */\n CL_ENGINE_BYTECODE_TIMEOUT, /* uint32_t */\n CL_ENGINE_BYTECODE_MODE, /* uint32_t */\n CL_ENGINE_MAX_EMBEDDEDPE, /* uint64_t */\n CL_ENGINE_MAX_HTMLNORMALIZE, /* uint64_t */\n CL_ENGINE_MAX_HTMLNOTAGS, /* uint64_t */\n CL_ENGINE_MAX_SCRIPTNORMALIZE, /* uint64_t */\n CL_ENGINE_MAX_ZIPTYPERCG, /* uint64_t */\n CL_ENGINE_FORCETODISK, /* uint32_t */\n CL_ENGINE_DISABLE_CACHE, /* uint32_t */\n CL_ENGINE_DISABLE_PE_STATS, /* uint32_t */\n CL_ENGINE_STATS_TIMEOUT, /* uint32_t */\n CL_ENGINE_MAX_PARTITIONS, /* uint32_t */\n CL_ENGINE_MAX_ICONSPE, /* uint32_t */\n CL_ENGINE_TIME_LIMIT /* uint32_t */\n};\n\nint cl_engine_set_num(struct cl_engine*, enum cl_engine_field, long long);\nlong long cl_engine_get_num(const struct cl_engine*, enum cl_engine_field, int*);\nint cl_engine_set_str(struct cl_engine*, enum cl_engine_field, const char*);\nconst char *cl_engine_get_str(const struct cl_engine *, enum cl_engine_field, int*);\n\ntypedef %s;\ntypedef %s;\ntypedef %s;\n\nvoid cl_engine_set_clcb_pre_cache(void*, clcb_pre_cache);\nvoid cl_engine_set_clcb_pre_scan(void*, clcb_pre_scan);\nvoid cl_engine_set_clcb_post_scan(void*, clcb_post_scan);\n''' % (_callback_ffi(_pre_cache_callback_base, 'clcb_pre_cache'),\n _callback_ffi(_pre_callback_base, 'clcb_pre_scan'),\n _callback_ffi(_post_callback_base, 'clcb_post_scan')))\n\n_bases = {'pre_cache': _pre_cache_callback_base, 'pre_scan': _pre_callback_base, 'post_scan': _post_callback_base}\n\ndbopt = {'phishing': 0x2,\n 'phishing_urls': 0x8,\n 'pua': 0x10,\n 'pua_mode': 0x80,\n 'pua_include': 0x100,\n 'pua_exclude': 0x200,\n 'official_only': 0x1000,\n 'bytecode': 0x2000,\n 'bytecode_unsigned': 0x8000,\n 'stdopt': 0x2|0x8|0x2000}\n\nscanopt = {'raw': 0x0,\n 'archive': 0x1,\n 'mail': 0x2,\n 'ole2': 0x4,\n 'blockencrypted': 0x8,\n 'html': 0x10,\n 'pe': 0x20,\n 'blockbroken': 0x40,\n 'mailurl': 0x80, #ignored\n 'blockmax': 0x100, #ignored\n 'algorithmic': 0x200,\n 'phishing_blockssl': 0x800, #ssl mismatches, not ssl by itself\n 'phishing_blockcloak': 0x1000,\n 'elf': 0x2000,\n 'pdf': 0x4000,\n 'structured': 0x8000,\n 'structured_ssn_normal': 0x10000,\n 'scructured_ssn_stripped': 0x20000,\n 'partial_message': 0x40000,\n 'heuristic_precedence': 0x80000,\n 'blockmacros': 0x100000,\n 'allmatches': 0x200000,\n 'swf': 0x400000,\n 'partition_intxn': 0x800000,\n 'file_properties': 0x10000000,\n 'performance_info': 0x40000000, #collect performance timings\n 'internal_collect_sha': 0x80000000, #Enables hash output in sha-collect builds - for internal use only\n 'stdopt': 0x1|0x2|0x4|0x4000|0x10|0x20|0x200|0x2000}\n\nresult = {'clean': 0,\n 'virus': 1,\n 'break': 22}\n\nclass ClamavError(Exception):\n def __init__(self, errcode, errstr):\n self.errcode = errcode\n super(ClamavError, self).__init__(errstr)\n\nclass engine(object):\n def __init__(self, dll_path=find_library('clamav'), init_code=0x0):\n self.exc = None\n self.libclamav = ffi.dlopen(dll_path)\n self.engine = self.libclamav.cl_engine_new()\n self.callbacks = {'pre_cache': None, 'pre_scan': None, 'post_scan': None}\n self.c_callbacks = self.callbacks\n\n def load_db(self, dbdir=None, options=dbopt['stdopt']):\n if not dbdir:\n dbdir = self.libclamav.cl_retdbdir()\n csigs = ffi.new('unsigned int*')\n ret = self.libclamav.cl_load(dbdir, self.engine, csigs, options)\n if ret != 0:\n raise ClamavError(ret, self.libclamav.strerror(ret))\n return csigs[0]\n\n def compile(self):\n # register callbacks\n for k,v in self.callbacks.items():\n if v is not None:\n getattr(self.libclamav, 'cl_engine_set_clcb_%s' % k)(self.engine, self.c_callbacks[k])\n self.libclamav.cl_engine_compile(self.engine)\n\n def scanfile(self, filename, options=scanopt['stdopt'], context=None):\n fname = ffi.new('const char[]', filename.encode())\n cvir = ffi.new('const char**')\n cscanned = ffi.new('unsigned long*')\n\n if context:\n ret = self.libclamav.cl_scanfile_callback(fname, cvir, cscanned, self.engine, options, context)\n else:\n ret = self.libclamav.cl_scanfile(fname, cvir, cscanned, self.engine, options)\n if self.exc is not None:\n _reraise(self.exc)\n if ret == result['clean']:\n return None\n elif ret == result['virus']:\n return ffi.string(cvir[0])\n else:\n raise ClamavError(ret, ffi.string(self.libclamav.cl_strerror(ret)))\n\n def _get_callback(self, n):\n return self.callbacks[n]\n\n def _set_callback(self, f, n):\n def _call(*args):\n call_args = list(args)\n for i, arg in enumerate(call_args):\n if isinstance(arg, ffi.CData) and ffi.typeof(arg) is not ffi.typeof(\"void *\"):\n try:\n call_args[i] = ffi.string(arg)\n except RuntimeError:\n call_args[i] = None\n else:\n call_args[i] = arg\n try:\n res = f(*call_args)\n if res is None:\n res = result['clean']\n if res not in result.values():\n raise ClamavError(0, '')\n except ClamavError:\n print(\"ClamavError\")\n return result['break']\n except:\n print(\"Other exception\")\n self.exc = sys.exc_info()\n return result['break']\n return res\n self.callbacks[n] = _call\n self.c_callbacks[n] = ffi.callback(_callback_str(_bases[n]), _call)\n\n @property\n def pre_cache_callback(self): return self._get_callback('pre_cache')\n\n @pre_cache_callback.setter\n def pre_cache_callback(self, f):\n self._set_callback(f, 'pre_cache')\n\n @property\n def pre_scan_callback(self): return self._get_callback('pre_scan')\n\n @pre_scan_callback.setter\n def pre_scan_callback(self, f):\n self._set_callback(f, 'pre_scan')\n\n @property\n def post_scan_callback(self): return self._get_callback('post_scan')\n\n @post_scan_callback.setter\n def post_scan_callback(self, f):\n self._set_callback(f, 'post_scan')\n\n def set_field(self, f, field, value):\n ret = f(self.engine, field, value)\n if ret != 0:\n raise ClamavError(ret, ffi.string(self.libclamav.cl_strerror(ret)))\n\n def get_field(self, f, field):\n err = 0\n err_ptr = ffi.new_handle(err)\n value = f(self.engine, field, err_ptr)\n if err != 0:\n raise ClamavError(err, ffi.string(self.libclamav.cl_strerror(err)))\n return value\n\n def set_num_field(self, field, value):\n return self.set_field(self.libclamav.cl_engine_set_num, field, value)\n\n def get_num_field(self, field):\n return self.get_field(self.libclamav.cl_engine_get_num, field)\n\n def set_str_field(self, field, value):\n return self.set_field(self.libclamav.cl_engine_set_str, field, value)\n\n def get_str_field(self, field):\n value = self.get_field(self.libclamav.cl_engine_get_str, field)\n if value == ffi.NULL:\n return \"\"\n return ffi.string(value)\n\n def __del__(self):\n if hasattr(self, 'engine'):\n self.libclamav.cl_engine_free(self.engine)\n","sub_path":"clamav.py","file_name":"clamav.py","file_ext":"py","file_size_in_byte":9611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"103805487","text":"'''\nA non validating Java parser\n\n\n\n'''\nimport pickle\nimport os\nfrom .light_parser import Lookahead, Parser, BlockStatement, Statement, Term, Seq, Optional, Node, Token # @UnresolvedImport\nfrom .lexer import JavaLexer\nfrom pygments.token import Keyword\nfrom java_parser.lexer import CommentEndOfLine\nfrom collections import defaultdict\n\ndef parse(text, discoverer=None):\n \"\"\"\n Parse a java code and return a CompilationUnit.\n \n :rtype: CompilationUnit\n \"\"\" \n parser = Parser(JavaLexer,\n [Package, Import, Parenthesis, Bracket, CurlyBracket],\n )\n \n stream = Lookahead(WhitespaceSkipper(parser.parse(text)))\n \n return JavaParser(discoverer).parse(stream)\n \n\n\nclass WhitespaceSkipper:\n \"\"\"\n Skip whitespaces.\n \"\"\"\n def __init__(self, tokens):\n self.tokens = iter(tokens)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n token = None\n while not token:\n token = next(self.tokens)\n \n if not type(token) is Token:\n break\n \n if token.is_whitespace():\n token = None\n \n return token\n \n def __repr__(self):\n return str(self.tokens)\n\n\nclass JavaParser:\n \n def __init__(self, discoverer):\n \n self.result = CompilationUnit(discoverer)\n \n def parse(self, stream):\n# print()\n modifiers = None\n elements_before = []\n new_children = []\n scope = CompilationUnit(None)\n \n try:\n while True:\n token = next(stream)\n# print(token)\n\n # store some elements still unassigned\n if token.is_comment():\n elements_before.append(token)\n elif is_modifier(token):\n modifiers = self.parse_modifiers(token, stream)\n elements_before.append(modifiers)\n \n elif isinstance(token, CurlyBracket):\n # initialiser\n if modifiers:\n \n # leave comments\n \n init = StaticInitializer(scope)\n init.children += elements_before\n elements_before = []\n init.children.append(token)\n new_children.append(init)\n else:\n # class init\n new_children.append(token)\n \n else:\n # method/constructor/variable eat till ; or {}\n local_children = []\n\n seen_assignement = False\n seen_parenthesis = False\n seen_comma = False\n length = 0\n \n while token != ';' and (not isinstance(token, CurlyBracket) or seen_assignement):\n if token == '=':\n seen_assignement = True\n \n if isinstance(token,Parenthesis) and not seen_assignement:\n seen_parenthesis = True\n self.parse_formal_parameters(token)\n length = len(local_children)\n \n local_children.append(token)\n \n if token == '=':\n token = next(stream)\n while token.is_whitespace() or token.is_comment():\n local_children.append(token)\n token = next(stream)\n local_children.append(self.parse_expression(token, stream, scope))\n \n token = next(stream)\n# print(token, scope.is_enum())\n# if scope.is_enum() and token in [',', ';', '}'] and not seen_semi_colon:\n# seen_comma = True\n# break\n \n if token == ';':\n seen_semi_colon = True\n \n if isinstance(token, CurlyBracket):\n # procedure like\n self.parse_simple_statements(token)\n \n # keep the last one\n local_children.append(token)\n \n # one can write \n # void f(...) {...};\n# print('next', stream.look_next())\n try:\n if stream.look_next() == ';':\n token = next(stream)\n local_children.append(token)\n seen_semi_colon = True\n except StopIteration:\n pass\n \n # @todo simplify\n stream.start_lookahead()\n try:\n \n look_next = next(stream)\n while look_next.is_whitespace():\n look_next = next(stream)\n \n # comment at the end of line are treated separatly\n if look_next.type == CommentEndOfLine:\n local_children += stream.stop_lookahead_and_consume()\n else:\n stream.stop_lookahead()\n except:\n stream.stop_lookahead()\n \n \n # switch on type\n element = None\n \n if seen_comma:\n element = EnumValue(scope)\n elif not seen_parenthesis:\n element = VariableDeclaration(scope) \n elif length == 1:\n # constructor\n element = Constructor(scope)\n else:\n element = Method(scope)\n \n # put what we have eaten\n element.children += elements_before\n \n element.children += local_children\n\n element.on_end()\n \n # re-init \n elements_before = []\n modifiers = None\n \n new_children.append(element)\n\n# print('next loop')\n except StopIteration:\n pass\n \n scope.elements = new_children\n return new_children\n\n def parse_annotation(self, token, stream, scope):\n \"\"\"\n Parse an annotation\n \"\"\"\n result = Annotation()\n result.children = [token]\n \n parenthesis = stream.look_next()\n \n if isinstance(parenthesis, Parenthesis):\n next(stream)\n result.children.append(parenthesis)\n self.recurse_on_annotation(parenthesis, scope)\n \n # parse annotation values\n elements = parenthesis.get_children()\n next(elements) # (\n try:\n \n first = True\n while True:\n name_or_value = next(elements)\n \n next_is_equal = False\n try:\n next_is_equal = elements.look_next() == '='\n except StopIteration:\n pass\n \n if next_is_equal:\n # named parameter\n element_name = name_or_value.text\n next(elements) # '='\n value = next(elements)\n \n result.named_parameter_expressions[element_name] = self.parse_constant(value, elements, scope)\n elif name_or_value not in [')', ',']:\n # positional parameter\n constant = self.parse_constant(name_or_value, elements, scope)\n if first:\n result.named_parameter_expressions['value'] = constant\n \n \n except StopIteration:\n pass\n \n \n \n result.on_end()\n return result\n \n def recurse_on_annotation(self, parenthesis, scope):\n \"\"\"\n Parse annotation inside annotations.\n \"\"\"\n \n stream = Lookahead(WhitespaceSkipper(parenthesis.children))\n token = next(stream)\n \n new_children = []\n \n try:\n \n while True:\n \n if is_annotation(token):\n new_children.append(self.parse_annotation(token, stream, scope))\n else:\n new_children.append(token)\n if isinstance(token, Node):\n self.recurse_on_annotation(token, scope)\n \n token = next(stream)\n \n except StopIteration:\n pass \n \n parenthesis.children = new_children\n \n \n def parse_modifiers(self, token, stream):\n \"\"\"\n Parse a modifer list\n \"\"\"\n result = Modifiers()\n result.children = [token]\n \n modifier = stream.look_next()\n \n while is_modifier(modifier):\n next(stream)\n result.children.append(modifier)\n modifier = stream.look_next()\n \n return result\n \n def parse_simple_statements(self, curly_bracket):\n \n stream = Lookahead(curly_bracket.children)\n new_children= [next(stream)] # skip {\n \n catches = []\n \n try:\n while True:\n \n token = next(stream)\n if token.text == 'catch':\n # catch (...) {...}\n catch = Catch()\n catch.children.append(token)\n catch.children.append(next(stream))\n catch.children.append(next(stream))\n \n catches.append(catch)\n elif token.text == 'finally':\n # finally {...}\n catch = Finally()\n catch.children.append(token)\n catch.children.append(next(stream))\n \n catches.append(catch)\n else:\n # something else than a catch series... \n if catches:\n c = Catches()\n c.children = catches\n \n new_children.append(c)\n else:\n new_children.append(token)\n if is_name(token):\n \n n = stream.look_next()\n if n == ';':\n # name ;\n statement = ExpressionStatement()\n statement.children.append(token)\n statement.children.append(next(stream))\n new_children.append(statement)\n elif isinstance(n, Parenthesis):\n # name (...) ;\n statement = ExpressionStatement()\n statement.children.append(token)\n statement.children.append(next(stream))\n statement.children.append(next(stream))\n new_children.append(statement)\n \n \n \n \n except StopIteration:\n pass\n \n \n curly_bracket.children = new_children\n \n def parse_expression(self, token, stream, scope):\n \"\"\"\n @todo\n \"\"\"\n if token.text and token.text[0] in ['\"', \"'\"]:\n return self.parse_simple_constant(token, scope)\n \n return token\n \n def parse_constant(self, token, stream, scope):\n \n result = self.parse_simple_constant(token, scope)\n \n token = stream.look_next()\n while token in ['+', '-', '*', '/']:\n operator = next(stream)\n token = next(stream)\n right = self.parse_simple_constant(token, scope)\n result = BinaryExpression(result, operator, right)\n token = stream.look_next()\n\n return result\n \n def parse_simple_constant(self, token, scope):\n \"\"\"\n :rtype: Expression\n \"\"\"\n if isinstance(token, CurlyBracket):\n # a set of value\n result = []\n sub_values = token.get_children()\n next(sub_values) # {\n try:\n while True:\n sub_value = next(sub_values)\n result.append(self.parse_constant(sub_value, sub_values, scope))\n next(sub_values) # ,\n except StopIteration:\n pass\n return List(result)\n elif isinstance(token, Parenthesis):\n sub_values = token.get_children()\n next(sub_values) # (\n try:\n sub_value = next(sub_values)\n return self.parse_constant(sub_value, sub_values, scope)\n except StopIteration:\n pass\n \n elif isinstance(token, Annotation):\n return token\n else:\n \n # try to convert value...\n if token.text and token.text[0] in ['\"', \"'\"]:\n return ConstantString(token.text[1:-1])\n else:\n try:\n int(token.text)\n return ConstantInteger(token)\n except:\n try:\n float(token.text)\n return ConstantInteger(token)\n except:\n pass\n # defaulting\n return Identifier(token, scope)\n\n \n \n def parse_formal_parameters(self, parenthesis):\n \n children = parenthesis.get_children()\n \n new_children = [next(children)] # openning parenthesis\n \n try:\n \n while True:\n elements = []\n token = next(children)\n \n if token == 'final':\n elements.append(token)\n token = next(children)\n \n while is_annotation(token):\n elements.append(self.parse_annotation(token, children, self.result)) # not sure here\n token = next(children)\n \n elements.append(self.parse_type(token, children))\n elements.append(next(children))\n \n parameter = FormalParameter()\n parameter.children = elements\n \n new_children.append(parameter)\n new_children.append(next(children)) # comma\n \n except StopIteration:\n pass\n \n parenthesis.children = new_children\n \n \n \n \n def parse_type(self, token, stream):\n \n result = self.parse_non_array_type(token, stream)\n \n try:\n current = stream.look_next()\n while isinstance(current, Bracket):\n current = next(stream)\n temp = ArrayType()\n temp.children.append(result)\n temp.children.append(current)\n \n result = temp\n \n current = stream.look_next()\n except StopIteration:\n pass\n \n return result\n \n \n \n def parse_generic_parameter(self, token, stream):\n \"\"\"\n token == '<'\n \"\"\"\n # ?|<type> [extends <type> & <type> ...]\n # empty\n \n result = GenericParameter()\n result.children.append(token)\n \n try:\n while True:\n \n current_token = next(stream)\n if current_token == '>':\n result.children.append(current_token)\n return result\n elif current_token not in ['?', ',', '&', 'extends', 'super']:\n result.children.append(self.parse_type(current_token, stream))\n else:\n result.children.append(current_token)\n \n except StopIteration:\n pass\n \n return result\n \n def parse_non_array_type(self, token, stream):\n \"\"\"\n Type without []\n \"\"\"\n if token.text in ['void', 'byte' , 'short', 'int', 'long', 'float', 'double', 'boolean', 'char']:\n return SimpleType(token)\n\n next_token = stream.look_next()\n if next_token != '<':\n \n return SimpleType(token)\n \n \n result = GenericType()\n result.children.append(token)\n \n token = next(stream)\n result.children.append(self.parse_generic_parameter(token, stream))\n \n return result\n \n \n\n# classical opening\n\nclass Parenthesis(BlockStatement):\n\n begin = '('\n end = ')'\n \n \nclass Bracket(BlockStatement):\n\n begin = '['\n end = ']'\n \n \nclass CurlyBracket(BlockStatement):\n\n begin = '{'\n end = '}'\n\n\n\nclass Scope:\n \n def __init__(self, parent=None):\n self.parent = parent\n\n\n def resolve_qname(self, qualified_name):\n \"\"\"\n Resolve a qualified name\n \"\"\"\n names = qualified_name.split('.')\n \n current_scope = self\n \n for name in names:\n \n if isinstance(current_scope, Scope):\n current_scope = current_scope.resolve_name(name)\n if not current_scope:\n return None\n else:\n return None\n \n return current_scope\n\n def resolve_name(self, name):\n \"\"\"\n Try to resolve an unqualified name in the current scope.\n \"\"\"\n \n local = self.local_resolve_name(name)\n if local:\n return local\n \n if self.parent:\n return self.parent.resolve_name(name)\n \n \n def local_resolve_name(self, name):\n \n pass\n\n\nclass CompilationUnit(Scope):\n \"\"\"\n Root of AST.\n \"\"\"\n def __init__(self, discoverer):\n \n Scope.__init__(self)\n # a file discoverer, optional\n self.discoverer = discoverer\n self.package = None\n self.imports = []\n self.type_declaration = None\n self.elements = []\n \n self.elements_by_fullname = defaultdict(list)\n\n def get_type_declaration(self):\n \"\"\"\n Access to the class/enum/interface/... defined in this compilation unit.\n \n :rtype: Class\n \"\"\"\n return self.type_declaration\n \n def get_possible_qualified_names(self, name):\n \"\"\"\n Given a name, returns the list of possible qualified names.\n \n Using package and imports, one can determine the list of possible qualified names of a Java name.\n \n This information is generally enough for most usages.\n \n Examples :\n \n import java.util.RequestMapping;\n @RequestMapping // possible qualified names are java.util.RequestMapping\n public class MyClass {}\n \n ...\n \n package mypackage;\n @RequestMapping // possible qualified names are mypackage.RequestMapping\n public class MyClass {}\n \n ...\n \n package mypackage;\n import java.util.*;\n @RequestMapping // possible qualified names are mypackage.RequestMapping and java.util.RequestMapping\n public class MyClass {}\n \n \n \"\"\"\n # @todo can be a relative name for a an inner class...\n if '.' in name:\n return [name] # already qualified\n \n result = []\n \n for _import in self.imports:\n qname = _import.get_name().split('.')\n if len(qname) == 1:\n continue\n imported = qname[-1]\n if imported == name:\n return ['.'.join(qname)] # unique solution\n \n # import *\n if imported == '':\n qname[-1] = name\n # one of the possible solutions\n result.append('.'.join(qname))\n \n # package + name is also a solution\n if self.package:\n result.append(self.package.get_name() + '.' + name)\n else:\n result.append(name)\n \n return result\n \n def local_resolve_name(self, name):\n \n # is it the local class ?\n if self.type_declaration and name == self.type_declaration.name:\n return self.type_declaration\n \n # is it something imported ?\n# for fullname in self.get_possible_qualified_names(name):\n# \n# pathes = [path for path in self.discoverer.get_pathes(fullname) if os.path.exists(path)]\n# \n# # else ambiguous...\n# if len(pathes) == 1:\n# \n# with open_source_file(pathes[0]) as f:\n# \n# compilation_unit = parse(f.read(), self.discoverer)\n# return compilation_unit.local_resolve_name(name)\n \n \n def _calculate_elements_by_fullname(self):\n \n if not self.elements_by_fullname:\n \n for element in self.elements:\n \n if isinstance(element, VariableDeclaration):\n self.elements_by_fullname[element.name.text].append(element)\n \n def get_element(self, fullname):\n \"\"\"\n Search a class, method, field etc... by its fullname\n \"\"\"\n self._calculate_elements_by_fullname()\n \n try:\n return self.elements_by_fullname[fullname]\n except:\n pass\n \n def save(self, path):\n \"\"\"\n Passivation to disk\n \"\"\"\n with open(path, \"wb\") as f:\n pickle.dump(self, f, pickle.HIGHEST_PROTOCOL)\n \n \n @staticmethod\n def load(path):\n \"\"\"\n Depassivation from disk\n \"\"\"\n with open(path, \"rb\") as f:\n return pickle.load(f)\n \n \n\nclass Package(Statement):\n\n begin = 'package'\n end = ';'\n \n def __init__(self):\n Statement.__init__(self)\n self.name = None\n \n def get_name(self):\n \"\"\"\n Get package name.\n \n :rtype: str\n \"\"\"\n return self.name.text;\n \n def on_end(self):\n\n tokens = self.get_children()\n next(tokens)\n token = next(tokens)\n self.name = token\n \n\nclass Import(Statement):\n\n begin = 'import'\n end = ';'\n\n def get_name(self):\n \"\"\"\n Get imported name.\n\n :rtype: str\n \"\"\"\n return self.name.text;\n \n def on_end(self):\n\n tokens = self.get_children()\n next(tokens)\n token = next(tokens)\n self.name = token\n\ndef is_annotation(token):\n \n return token.text and token.text[0] == '@' and not token.text == '@interface'\n\ndef is_modifier(token):\n \n return token.text in ['public', 'private', 'protected', \n 'abtsract', 'static', 'final', 'strictfp',\n 'native', 'synchronized', 'transient']\n\ndef is_class(token):\n \n return token.text in ['class', 'interface', 'enum', '@interface'] \n\n\ndef parse_constant(value):\n \"\"\"\n value is a constant element\n \n :rtype: python type with correct elements (for example list of string/int, ...)\n \"\"\"\n if isinstance(value, CurlyBracket):\n # a set of value\n result = []\n sub_values = value.get_children()\n next(sub_values) # {\n try:\n while True:\n \n sub_value = next(sub_values)\n result.append(parse_constant(sub_value))\n next(sub_values) # ,\n except StopIteration:\n pass\n \n return result\n elif isinstance(value, Annotation):\n return value\n else:\n \n # try to convert value...\n if value.text and value.text[0] in ['\"', \"'\"]:\n return value.text[1:-1]\n else:\n try:\n return int(value.text)\n except:\n try:\n return float(value.text)\n except:\n pass\n return value.text\n\n\nclass Annotation(Term):\n \"\"\"\n An annotation\n \"\"\"\n\n def __init__(self):\n Term.__init__(self)\n self.name = None\n self.named_parameters = {}\n self.named_parameter_expressions = {}\n self.named_parameters_calculated = False\n \n def get_type_name(self):\n \"\"\"\n Get the name of the annotation class.\n\n :rtype: str\n \"\"\"\n return self.name\n \n def get_named_parameters(self):\n \"\"\"\n Get the annotation named parameters.\n \n :rtype: map str -> something (int, str)\n \"\"\"\n if not self.named_parameters_calculated:\n \n self.named_parameters = {}\n for key in self.named_parameter_expressions:\n \n self.named_parameters[key] = self.named_parameter_expressions[key].evaluate_as_constant()\n \n self.named_parameters_calculated = True\n \n return self.named_parameters\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return self\n\n def to_text(self):\n return str(self)\n\n def on_end(self):\n\n tokens = self.get_children()\n name = next(tokens)\n self.name = name.text[1:]\n \n try:\n parenthesis = next(tokens)\n elements = parenthesis.get_children()\n next(elements) # (\n try:\n \n first = True\n while True:\n name_or_value = next(elements)\n \n next_is_equal = False\n try:\n next_is_equal = elements.look_next() == '='\n except StopIteration:\n pass\n \n if next_is_equal:\n # named parameter\n element_name = name_or_value.text\n next(elements) # '='\n value = next(elements)\n \n self.named_parameters[element_name] = parse_constant(value)\n elif name_or_value not in [')', ',']:\n # positional parameter\n constant = parse_constant(name_or_value)\n if first:\n self.named_parameters['value'] = constant\n \n \n except StopIteration:\n pass\n \n \n except StopIteration:\n pass\n \n\ndef match_annotation_list(_token, stream):\n \n token = _token\n \n index_of_stream = stream.tokens.index\n \n seen = False\n # accepts list of annotations\n while isinstance(token, Annotation):\n # this index is correct\n index_of_stream = stream.tokens.index\n token = next(stream)\n seen = True\n \n # whatever reason we reput as the last one correct\n stream.tokens.index = index_of_stream\n \n return seen\n\n\ndef match_modifier_list(_token, stream):\n\n token = _token\n\n index_of_stream = stream.tokens.index\n \n seen = False\n \n # then things like public, etc...\n while token.text in ['public', 'private', 'protected', \n 'abtsract', 'static', 'final', 'strictfp',\n 'native', 'synchronized', 'transient']:\n # this index is correct\n index_of_stream = stream.tokens.index\n token = next(stream)\n seen = True\n \n # whatever reason we reput as the last one correct\n stream.tokens.index = index_of_stream\n \n return seen\n\n\n\n\nclass Modifiers(Term):\n \n match = match_modifier_list\n\n\ndef is_name(token):\n \n return not is_keyword(token) and token.text and token.text[0].isalpha()\n\n\nclass JavaStructureElement:\n \n def get_header_comments(self):\n \n tokens = iter(self.children)\n \n result = []\n token = None\n try:\n while token not in ['class', 'interface', 'enum', '@interface']:\n token = next(tokens)\n if token.is_comment():\n result.append(token)\n except StopIteration:\n pass\n \n return result\n\n\nclass Class(JavaStructureElement, BlockStatement, Scope):\n \"\"\"\n Class, interface, enum, annotation.\n \n [AnnotationList] [Modifiers] class|interface|enum|@intereface <name> ... CurlyBracket\n \"\"\"\n \n def __init__(self, parent):\n BlockStatement.__init__(self)\n Scope.__init__(self, parent)\n self.name = None\n self.annotations = []\n self.modifiers = []\n self.extends = []\n\n def get_name(self):\n \"\"\"\n Access to class name\n\n :rtype: str\n \"\"\"\n return self.name.text\n \n def get_annotations(self):\n \"\"\"\n Access to class annotations\n \n :rtype: list of Annotation\n \"\"\"\n return self.annotations\n \n def get_modifiers(self):\n \"\"\"\n Access to class modifiers\n \"\"\"\n return self.modifiers\n \n def get_extends(self):\n \"\"\"\n Inherited class or None\n \n @todo implement\n :rtype: Class or NoneType\n \"\"\"\n return self.extends\n \n def get_methods(self):\n \"\"\"\n Access to class methods\n\n :rtype: list of Method\n \"\"\"\n # not in on_end, because would not work\n for block in self.get_sub_nodes(CurlyBracket):\n \n return list(block.get_sub_nodes(Method))\n \n def get_constructors(self):\n \"\"\"\n Access to class constructors\n \n :rtype: list of Constructor\n \"\"\"\n # not in on_end, because would not work\n for block in self.get_sub_nodes(CurlyBracket):\n \n return list(block.get_sub_nodes(Constructor))\n\n def get_fields(self):\n \"\"\"\n Access to class fields\n\n :rtype: list of VariableDeclaration\n \"\"\"\n # not in on_end, because would not work\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(VariableDeclaration))\n\n def get_enum_values(self):\n \"\"\"\n In case of enum access to constants.\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(EnumValue))\n\n def get_instance_initializers(self):\n \"\"\"\n :rtype: list of CurlyBracket\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(CurlyBracket))\n\n def get_static_initializers(self):\n \"\"\"\n :rtype: list of StaticInitializer\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(StaticInitializer))\n \n def get_type_declarations(self):\n \"\"\"\n Inner class declarations.\n \n :rtype: list of Class\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(Class))\n \n def is_enum(self):\n \"\"\"\n True if class is an enum\n \"\"\"\n tokens = self.get_children()\n kind = tokens.move_to(['class', 'interface', 'enum', '@interface'])\n return kind == 'enum'\n \n def local_resolve_name(self, name):\n \n for child in self.get_methods():\n if child.name == name:\n return child\n \n for child in self.get_constructors():\n if child.name == name:\n return child\n\n for child in self.get_fields():\n if child.name == name:\n return child\n\n for child in self.get_type_declarations():\n if child.name == name:\n return child\n \n pass\n \n def on_end(self):\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n \n for modifiers in self.get_sub_nodes(Modifiers):\n self.modifiers = list(modifiers.get_children())\n\n tokens = self.get_children()\n tokens.move_to(['class', 'interface', 'enum', '@interface'])\n \n \n self.name = next(tokens)\ndef is_keyword(token):\n \n return token.type == Keyword\n\n\ndef is_type(token, stream):\n \n if not is_non_array_type(token, stream):\n return False\n \n index_of_stream = stream.tokens.index\n \n try:\n token = next(stream)\n \n while isinstance(token,Bracket):\n index_of_stream = stream.tokens.index\n token = next(stream)\n \n except StopIteration:\n pass\n stream.tokens.index = index_of_stream\n return True\n\ndef is_generic_type_parameter(token, stream):\n \n # ?|<type> [extends <type> & <type> ...]\n# print(\"is_generic_type_parameter\", stream.tokens.index, stream.tokens)\n \n if token != '?' and not is_type(token, stream):\n return False\n \n index_of_stream = stream.tokens.index\n token = next(stream)\n if token.text != 'extends':\n stream.tokens.index = index_of_stream\n return True\n \n token = next(stream)\n if not is_type(token, stream):\n stream.tokens.index = index_of_stream\n return False\n \n index_of_stream = stream.tokens.index\n token = next(stream)\n while token == '&':\n token = next(stream)\n is_type(token, stream)\n \n index_of_stream = stream.tokens.index\n token = next(stream)\n\n stream.tokens.index = index_of_stream\n return True\n \ndef is_non_array_type(token, stream):\n \"\"\"\n Type without []\n \"\"\"\n if token.text in ['void', 'byte' , 'short', 'int', 'long', 'float', 'double', 'boolean', 'char']:\n return True\n \n if not is_name(token):\n return False\n \n # for rollbacking\n index_of_stream = stream.tokens.index\n \n try:\n token = next(stream)\n if token != '<':\n stream.tokens.index = index_of_stream\n return True\n \n # here we have matched \n # name < \n \n \n index_of_stream = stream.tokens.index\n token = next(stream)\n while is_generic_type_parameter(token, stream):\n token = next(stream)\n if token == '>':\n break\n if token == ',':\n token = next(stream)\n else:\n # something bad happenned\n stream.tokens.index = index_of_stream\n return False\n\n except StopIteration:\n pass\n \n # and again with commas till > \n return True\n \n\ndef is_throws(token, stream):\n \n if token.text != 'throws':\n return False\n \n # eats type, type, ...\n # fragile...\n token = next(stream)\n while is_type(token, stream):\n index_of_stream = stream.tokens.index\n \n token = next(stream)\n if token != ',':\n stream.tokens.index = index_of_stream\n return True\n else:\n token = next(stream)\n \n\nclass Throws(Term):\n \n match = is_throws\n\n\nclass MethodLike(Scope):\n \n def __init__(self, parent):\n Scope.__init__(self, parent)\n self.__parsed = False\n \n def get_statements(self):\n \"\"\"\n Access to method statements\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n \n # on demand statement parsing\n if not self.__parsed:\n parser = Parser(JavaLexer,\n [Assert, Break, Continue, Return, Throw, Switch, DoWhile, Try],\n )\n \n # need one loop to force the parsing\n for _ in recursive_statement_pass(parser.parse_stream([block])):\n pass\n \n self.__parsed = True\n \n return list(block.get_sub_nodes(JavaStatement))\n \n def get_parameters(self):\n \"\"\"\n Access to method parameters\n \n :rtype: list FormalParameter\n \"\"\"\n for parenthesis in self.get_sub_nodes(Parenthesis):\n \n return list(parenthesis.get_sub_nodes(FormalParameter))\n \n\nclass EnumValue(JavaStructureElement, Term):\n \n def __init__(self, parent):\n Term.__init__(self)\n self.name = None\n self.annotations = []\n \n def get_name(self):\n \"\"\"\n Access to name.\n\n :rtype: str\n \"\"\"\n return self.name.text\n \n def on_end(self):\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n\n tokens = self.get_children()\n token = next(tokens)\n\n while isinstance(token, Annotation):\n token = next(tokens)\n \n # here we assume that name is a single token\n self.name = token\n \n\nclass Method(JavaStructureElement, Term, MethodLike):\n \"\"\"\n [AnnotationList] [Modifiers] [AnnotationList] <type> <identifier> Parenthesis [throws <type>, ...] CurlyBracket|;\n \"\"\"\n \n def __init__(self, parent):\n Term.__init__(self)\n MethodLike.__init__(self, parent)\n \n self.name = None\n self.annotations = []\n self.modifiers = []\n self.type = []\n \n def get_name(self):\n \"\"\"\n Access to name.\n\n :rtype: str\n \"\"\"\n return self.name.text\n \n def get_annotations(self):\n \"\"\"\n Access to class annotations\n \"\"\"\n return self.annotations\n \n def get_modifiers(self):\n \"\"\"\n Access to class modifiers\n \"\"\"\n return self.modifiers\n \n def on_end(self):\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n\n tokens = self.get_children()\n token = next(tokens)\n \n while isinstance(token, Annotation):\n token = next(tokens)\n \n if isinstance(token, Modifiers):\n self.modifiers += list(token.get_children())\n token = next(tokens)\n \n # here we are on type...\n while not isinstance(token, Parenthesis):\n self.type.append(token)\n token = next(tokens)\n \n # here we assume that name is a single token\n self.name = self.type[-1]\n self.type = self.type[:-1]\n \n # here token is parenthesis and contains parameters... \n\n\nclass Constructor(JavaStructureElement, Term, MethodLike):\n \"\"\"\n [AnnotationList] [Modifiers] <identifier> Parenthesis [throws <type>, ...] CurlyBracket\n \"\"\"\n \n def __init__(self, parent):\n Term.__init__(self)\n MethodLike.__init__(self, parent)\n \n self.name = None\n self.annotations = []\n self.modifiers = []\n \n def get_name(self):\n \"\"\"\n Access to name.\n :rtype: str\n \"\"\"\n return self.name.text\n \n def get_annotations(self):\n \"\"\"\n Access to class annotations\n \"\"\"\n return self.annotations\n \n def get_modifiers(self):\n \"\"\"\n Access to class modifiers\n \"\"\"\n return self.modifiers\n \n def on_end(self):\n \n tokens = self.get_children()\n token = next(tokens)\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n \n while isinstance(token, Annotation):\n token = next(tokens)\n \n if isinstance(token, Modifiers):\n self.modifiers += list(token.get_children())\n token = next(tokens)\n \n self.name = token\n \n # here token is parenthesis and contains parameters... \n\n\nclass StaticInitializer(Term, MethodLike):\n \n match = Seq('static', CurlyBracket)\n\n def __init__(self, parent):\n Term.__init__(self)\n MethodLike.__init__(self, parent)\n\n\nclass VariableDeclaration(JavaStructureElement, Statement, Scope):\n \"\"\"\n Member variable also...\n \n [AnnotationList] [Modifiers] <type> <identifier> [= ...] ;\n \"\"\"\n\n def __init__(self, parent):\n Statement.__init__(self)\n Scope.__init__(self, parent)\n self.name = None\n self.annotations = []\n self.modifiers = []\n self.type = []\n self.initialisation = None\n \n def get_name(self):\n \"\"\"\n Access to name.\n :rtype: str\n \"\"\"\n return self.name.text\n \n def get_annotations(self):\n \"\"\"\n Access to class annotations\n \"\"\"\n return self.annotations\n \n def get_modifiers(self):\n \"\"\"\n Access to class modifiers\n \"\"\"\n return self.modifiers\n \n def get_initialisation(self):\n \"\"\"\n :rtype: Expression\n \"\"\"\n return self.initialisation\n \n \n def on_end(self):\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n\n tokens = self.get_children()\n token = next(tokens)\n\n while isinstance(token, Annotation):\n token = next(tokens)\n\n if isinstance(token, Modifiers):\n self.modifiers += list(token.get_children())\n token = next(tokens)\n \n # here we are on type...\n while not token in ['=', ';']:\n self.type.append(token)\n token = next(tokens)\n \n # here we assume that name is a single token\n self.name = self.type[-1]\n self.type = self.type[:-1]\n \n if token != '=':\n return\n \n self.initialisation = next(tokens)\n \n\n### For statements\n\"\"\"\n\n\nTodo:\n\n synchronized ParExpression Block\n\n\nHope useless ??:\n Identifier : Statement\n ;\n\nPartially :\n## StatementExpression ;\n\n method ... ;\n\nDone:\n** Block\n** do Statement while ParExpression ;\n** assert Expression [: Expression] ;\n** switch ParExpression { SwitchBlockStatementGroups } \n** break [Identifier] ;\n** continue [Identifier] ;\n** return [Expression] ;\n** throw Expression ;\n** if ParExpression Statement [else Statement] \n** for ( ForControl ) Statement\n** while ParExpression Statement\n** try Block (Catches | [Catches] Finally)\n** try ResourceSpecification Block [Catches] [Finally]\n\n\"\"\"\n\"\"\"\nExpressions:\n\nTodo:\n new <expression> ;\n \n \n \n \n\"\"\"\n\n\nclass JavaStatement():\n pass\n\n\nclass JavaSimpleStatement(JavaStatement, Statement):\n pass\n\n\nclass JavaBlockStatement(JavaStatement, BlockStatement):\n pass\n\n\nclass Assert(JavaSimpleStatement):\n\n begin = 'assert'\n end = ';'\n\n\nclass Break(JavaSimpleStatement):\n\n begin = 'break'\n end = ';'\n\n\nclass Continue(JavaSimpleStatement):\n\n begin = 'continue'\n end = ';'\n\n\nclass Return(JavaSimpleStatement):\n\n begin = 'return'\n end = ';'\n\n\nclass Throw(JavaSimpleStatement):\n\n begin = 'throw'\n end = ';'\n\n\nclass Catch(Term):\n \n match = Seq('catch', Parenthesis, CurlyBracket)\n\n\n\ndef is_catches(token, stream):\n \"\"\"\n catches ... and finally\n \"\"\"\n if isinstance(token, Finally):\n return False\n \n if not isinstance(token, Catch):\n return False\n \n # eats Catch Catch\n index_of_stream = stream.tokens.index\n\n try:\n token = next(stream)\n\n while isinstance(token, Catch) or isinstance(token, Finally):\n index_of_stream = stream.tokens.index\n token = next(stream)\n \n except:\n pass\n \n stream.tokens.index = index_of_stream\n return True\n \n\nclass Catches(Term):\n \n match = is_catches\n\n\nclass Finally(Term):\n\n match = Seq('finally', CurlyBracket)\n\n\nclass Try(JavaStatement, Term):\n \n match = Seq('try', Optional(Parenthesis), CurlyBracket, Optional(Catches))\n \n def get_catches(self):\n \"\"\"\n Access to catches blocks\n \"\"\"\n for node in self.get_sub_nodes(Catches):\n return node.get_sub_nodes(Catch)\n\n \n def get_finally(self):\n \"\"\"\n Access to finally block if exist\n \"\"\"\n for node in self.get_sub_nodes(Catches):\n for f in node.get_sub_nodes(Finally):\n return f\n \n \n\nclass Switch(JavaSimpleStatement):\n\n begin = 'switch'\n end = CurlyBracket\n\n\nclass ExpressionStatement(JavaStatement, Term):\n\n match = Seq(is_name, Optional(Parenthesis), ';')\n\n\nclass DoWhile(JavaBlockStatement):\n \n begin = 'do' \n end = Seq('while', Parenthesis, ';')\n\n def get_statemens(self):\n # @todo\n pass\n \n\nclass If(JavaBlockStatement):\n \n \n def get_condition(self):\n \"\"\"\n The condition of the if\n \"\"\"\n return list(self.get_sub_nodes())[0]\n \n def get_then(self):\n \"\"\"\n The then part\n \"\"\"\n return list(self.get_sub_nodes())[1]\n \n def get_else(self):\n \"\"\"\n The else part\n \"\"\"\n try:\n return list(self.get_sub_nodes())[2]\n except:\n pass\n\n\nclass For(JavaBlockStatement):\n\n def get_for_control(self):\n \"\"\"\n The control of the for\n \n for (....)\n ------\n \"\"\"\n return list(self.get_sub_nodes())[0]\n \n def get_statement(self):\n \"\"\"\n Access to the statement looped.\n \"\"\"\n return list(self.get_sub_nodes())[1]\n \n\n\nclass While(JavaBlockStatement):\n\n def get_condition(self):\n \"\"\"\n The condition of the while\n \"\"\"\n return list(self.get_sub_nodes())[0]\n\n def get_statement(self):\n \"\"\"\n Access to the statement looped.\n \"\"\"\n return list(self.get_sub_nodes())[1]\n\n \ndef recursive_statement_pass(stream):\n \"\"\"\n Special treatment for if/for/while\n \"\"\"\n \n for node in stream:\n handle_node(node)\n yield node\n\n\ndef handle_node(node):\n \n # recurse\n if isinstance(node, Node):\n for sub in node.get_sub_nodes():\n handle_node(sub)\n \n if isinstance(node, CurlyBracket):\n handle_block(node)\n \n\ndef handle_block(node):\n \"\"\"\n Here we get the CurlyBracket nodes\n \"\"\"\n# print('handling block...')\n \n # re-manipulate node.children to create sub nodes for if/else, for () statement, while () statement,\n stream = SimpleStream(node.children)\n\n new_children = []\n \n try:\n while True:\n new_children.append(consume(stream))\n \n except StopIteration:\n pass\n \n \n node.children = new_children\n \n# print()\n# for child in new_children:\n# print(' ', child)\n\n\nclass SimpleStream:\n \n def __init__(self, elements):\n \n self.elements = elements\n self.index = 0\n \n def __iter__(self):\n return self\n\n def __next__(self):\n \n try:\n index = self.index\n self.index += 1\n return self.elements[index]\n except:\n raise StopIteration\n \n def look_next(self):\n \n return self.look(1)\n \n def look(self, delta):\n \"\"\"\n Look future...\n \"\"\"\n try:\n return self.elements[self.index+delta]\n except:\n return None\n \n def peek_next(self):\n \"\"\"\n Look for the next significative token\n \"\"\"\n delta = 1\n peek = None\n while True:\n \n peek = self.look(delta)\n delta += 1\n \n if not peek:\n break\n if not (peek.is_whitespace() or peek.is_comment()):\n break\n \n return peek\n \n\n\ndef eat_statement(stream, l):\n\n # eat up to a node\n # recursive, but will not work for 1; ...\n while True: \n then = consume(stream)\n l.append(then)\n if isinstance(then, Node):\n break\n\n\n\ndef consume(stream):\n \"\"\"\n Main parsing for if, for, while\n \"\"\"\n token = next(stream)\n if token.text == 'if':\n \n result = If()\n result.children.append(token)\n \n # eat up to parenthesis\n while True: \n token = next(stream)\n result.children.append(token)\n if isinstance(token, Parenthesis):\n break\n \n# print(result.children)\n eat_statement(stream, result.children)\n# print(result.children)\n\n # have we a else ?\n peek = stream.peek_next()\n# print(peek)\n if peek.text == 'else':\n \n # eat up to else\n while True:\n token = next(stream)\n result.children.append(token)\n if token.text == 'else':\n break\n \n # eat the next statement\n eat_statement(stream, result.children)\n \n return result\n \n elif token.text == 'for':\n \n result = For()\n result.children.append(token)\n \n # eat up to parenthesis\n while True: \n token = next(stream)\n result.children.append(token)\n if isinstance(token, Parenthesis):\n break\n \n eat_statement(stream, result.children)\n \n return result\n\n elif token.text == 'while':\n \n result = While()\n result.children.append(token)\n \n # eat up to parenthesis\n while True: \n token = next(stream)\n result.children.append(token)\n if isinstance(token, Parenthesis):\n break\n \n eat_statement(stream, result.children)\n \n return result\n \n return token \n\n\n# ???\n \nclass Expression:\n pass\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return \"\"\n\n\nclass BinaryExpression(Expression):\n\n def __init__(self, left, operator, right):\n Expression.__init__(self)\n self.left = left\n self.operator = operator\n self.right = right\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n \n # only + for the moment\n if self.operator == '+':\n \n left = self.left.evaluate_as_constant()\n right = self.right.evaluate_as_constant()\n \n return left + right\n else:\n return self.left.to_text() + self.operator.text + self.right.to_text()\n \n def to_text(self):\n return \"\"\n\n def __repr__(self):\n \n return \"%s %s %s\" % (self.left, self.operator.text, self.right)\n\n\nclass ConstantString(Expression):\n def __init__(self, token):\n self.value = token\n \n def __repr__(self):\n return \"Constant(\\\"%s\\\")\" % self.value\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return self.value\n \n def to_text(self):\n return self.value.text\n\n\nclass ConstantInteger(Expression):\n def __init__(self, token):\n self.value = token\n\n def __repr__(self):\n return \"Constant(%s)\" % self.value\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return int(self.value.text)\n\n def to_text(self):\n return str(self.value)\n \n\nclass ConstantFloat(Expression):\n def __init__(self, token):\n self.value = token\n\n def __repr__(self):\n return \"Constant(%s)\" % self.value\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return float(self.value)\n\n def to_text(self):\n return str(self.value)\n\n\nclass Identifier(Expression):\n def __init__(self, token, scope=None):\n self.identifier = token\n # we need a scope to resolve its value latter\n self.scope = scope\n\n def __repr__(self):\n return self.identifier.text\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n try:\n if self.scope:\n # we can try to resolve it\n resolved_as = self.scope.resolve_qname(self.identifier.text)\n if resolved_as and isinstance(resolved_as, VariableDeclaration):\n \n init_expression = resolved_as.get_initialisation()\n if init_expression:\n \n return init_expression.evaluate_as_constant()\n except:\n pass # shit may happen\n \n return self.identifier.text\n\n def to_text(self):\n return self.identifier.text\n\n\nclass List(Expression):\n def __init__(self, elements):\n self.elements = elements\n\n def __repr__(self):\n return \"List(%s)\" % self.elements\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return [element.evaluate_as_constant() for element in self.elements]\n\n def to_text(self):\n return \"{\" + ','.join([element.to_text() for element in self.elements]) + \"}\"\n\n\n\ndef get_all_tokens(node):\n \n result = []\n \n for t in node.children:\n if isinstance(t, Node):\n result += get_all_tokens(t)\n else:\n result.append(t)\n \n return result\n\n\nclass Type:\n \n \n def __repr__(self): \n return ''.join(token.text for token in get_all_tokens(self))\n\n \n \n\nclass SimpleType(Type, Node):\n \"\"\"\n predefined type of class\n \"\"\"\n def __init__(self, token):\n Node.__init__(self)\n self.children = [token]\n\n def get_type_name(self):\n \"\"\"\n Get the name of the type.\n :rtype: str\n \"\"\"\n return self.children[0].text\n \n\nclass ArrayType(Type, Node):\n \"\"\"\n ... []\n \"\"\"\n \n def get_type(self):\n \"\"\"\n Access to type on which we do an array\n \"\"\"\n return next(self.get_sub_nodes())\n \n\nclass GenericType(Type, Node):\n \"\"\"\n @todo : maybe we need a SimpleType here as first child ?\n ... < ... >\n \"\"\"\n pass\n\n\nclass GenericParameter(Node):\n pass\n \n\nclass FormalParameter(Node):\n \"\"\"\n A formal parameter of a method.\n \"\"\"\n \n def get_name(self):\n \"\"\"\n Parameter name\n \n :rtype: str\n \"\"\"\n for child in self.get_children():\n if child == 'final':\n continue\n \n if isinstance(child, Annotation):\n continue\n \n if isinstance(child, Type):\n continue\n \n return child.text\n\n def get_type(self):\n \"\"\"\n Parameter type\n \n :rtype: Type\n \"\"\"\n for child in self.get_children():\n\n if isinstance(child, Type):\n \n return child\n\n\ndef open_source_file(path):\n \"\"\"\n Equivalent of python open(path) that autotdetects encoding. \n \n :rtype: file \n \"\"\"\n from chardet.universaldetector import UniversalDetector\n \n detector = UniversalDetector()\n with open(path, 'rb') as f:\n count = 0\n for line in f:\n detector.feed(line)\n count += 1\n if detector.done or count > 100: \n break\n detector.close()\n\n encoding = detector.result['encoding']\n \n result = open(path, 'r', encoding=encoding, errors='replace')\n return result\n","sub_path":"analyze/extensions/com.castsoftware.html5.2.0.8-funcrel/java_parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":56975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"178382087","text":"# -*- encoding: utf-8 -*-\nfrom __future__ import print_function, unicode_literals, division\nimport logging\n\nimport threading\ntry:\n import queue\nexcept ImportError:\n import Queue as queue\nfrom enocean.protocol.packet import Packet\nfrom enocean.protocol.constants import PARSE_RESULT\n\nlogger = logging.getLogger('enocean.communicators.Communicator')\n\n\nclass Communicator(threading.Thread):\n '''\n Communicator base-class for EnOcean.\n Not to be used directly, only serves as base class for SerialCommunicator etc.\n '''\n def __init__(self, callback=None):\n super(Communicator, self).__init__()\n # Create an event to stop the thread\n self._stop_flag = threading.Event()\n # Input buffer\n self._buffer = []\n # Setup packet queues\n self.transmit = queue.Queue()\n self.receive = queue.Queue()\n # Set the callback method\n self.__callback = callback\n \n def _get_from_send_queue(self):\n ''' Get message from send queue, if one exists '''\n try:\n p = self.transmit.get(block=False)\n logger.info('Sending packet')\n logger.debug(p)\n return p\n except queue.Empty:\n pass\n return None\n\n def send(self, packet):\n if not isinstance(packet, Packet):\n logger.error('Object to send must be an instance of Packet')\n return False\n self.transmit.put(packet)\n return True\n\n def stop(self):\n self._stop_flag.set()\n\n def parse(self):\n ''' Parses messages and puts them to receive queue '''\n # Loop while we get new messages\n while True:\n status, self._buffer, p = Packet.parse_msg(self._buffer)\n # If message is incomplete -> break the loop\n if status == PARSE_RESULT.INCOMPLETE:\n return status\n\n # If message is OK, add it to receive queue or send to the callback method\n if status == PARSE_RESULT.OK and p:\n if self.__callback is None:\n self.receive.put(p)\n else:\n self.__callback(p)\n logger.debug(p)\n","sub_path":"enocean/communicators/communicator.py","file_name":"communicator.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"651616629","text":"#!/usr/bin/env python\n\nfrom itertools import izip\nfrom os import chdir\nfrom pathlib import Path\nfrom subprocess import check_call\n\ndef main():\n base = Path(__file__).parent.parent.parent\n chdir(str(base))\n clean = Path().glob(r'[c-f]_*/aa*.py')\n for y in clean:\n y.unlink()\n subdirs = Path().glob(r'[b-f]_*')\n d0 = next(subdirs)\n template = tuple(_list_paths(d0))\n contents = tuple(_content(path) for path in template)\n template = (path.name for path in template)\n replace = tuple(path.replace(str(d0)[0], r'{}') for path in template)\n name_template = str(d0)\n for subdir in subdirs:\n name = str(subdir)\n n0 = name[0]\n for r, c in izip(replace, contents):\n c = c.replace(name_template, name)\n output = subdir.joinpath(r.format(n0))\n with output.open('wb') as ostream:\n ostream.write(c)\n check_call(r'git add {}'.format(str(output)), shell=True)\n\ndef _content(path):\n with path.open('rb') as istream:\n return istream.read()\n\ndef _list_paths(y):\n c = str(y)[0]\n pat = r'aa_{}[01]*.py'.format(c)\n for path in y.glob(pat):\n yield path\n\nif __name__ == r'__main__':\n main()\n","sub_path":"zz/aa20141119.py","file_name":"aa20141119.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"653572360","text":"# coding: utf-8\nimport datetime\nimport json\nimport time\nimport urllib\n\n#import brukva\n#import aioredis\nimport tornadoredis\n#from aredis import StrictRedis\nimport tornado.web\nimport tornado.websocket\nimport tornado.ioloop\nimport tornado.httpclient\nfrom django.shortcuts import render, get_object_or_404\nfrom privatemessages.models import Read\n\n\nfrom django.conf import settings\nfrom importlib import import_module\n\nsession_engine = import_module(settings.SESSION_ENGINE)\n\nfrom django.contrib.auth.models import User\n\nc = tornadoredis.Client()\nc.connect()\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.set_header('Content-Type', 'text/plain')\n self.write('Hello. :)')\n\nclass MessagesHandler(tornado.websocket.WebSocketHandler):\n\n waiters = set()\n\n def __init__(self, *args, **kwargs):\n super(MessagesHandler, self).__init__(*args, **kwargs)\n self.client = tornadoredis.Client()\n self.client.connect()\n\n def check_origin(self, origin):\n return True\n\n def open(self, user_id):\n session_key = self.get_cookie(settings.SESSION_COOKIE_NAME)\n session = session_engine.SessionStore(session_key)\n try:\n self.user_id = session[\"_auth_user_id\"]\n self.sender_name = User.objects.get(id=self.user_id).username\n except (KeyError, User.DoesNotExist):\n self.close()\n return\n self.channel = user_id\n self.waiters.add((self))\n print(self.channel)\n print('выполнн')\n self.client.listen(self.show_new_message)\n\n def handle_request(self, response):\n pass\n\n def show_new_message(self, result):#python manage.py starttornadooffers\n print('ЗАЯВКА!')\n self.write_message(str(result.body))\n\n def on_message(self, message):\n print(\"message\")\n for waiter in self.waiters:\n if waiter.channel == self.channel:\n waiter.write_message(message)\n print(\"message_send\")\n\n def on_close(self):\n print('close!')\n try:\n self.waiters.remove((self))\n #self.client.unsubscribe(self.channel)\n except AttributeError:\n pass\n def check():\n if self.client.connection.in_progress:\n tornado.ioloop.IOLoop.instance().add_timeout(\n datetime.timedelta(0.00001),\n check\n )\n else:\n self.client.disconnect()\n tornado.ioloop.IOLoop.instance().add_timeout(\n datetime.timedelta(0.00001),\n check\n )\n\napplication = tornado.web.Application([\n (r\"/\", MainHandler),\n (r'/(?P<user_id>\\d+)/', MessagesHandler),\n])","sub_path":"nicechange/offers/tornadooffers.py","file_name":"tornadooffers.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"122362640","text":"from flask import Flask, render_template, request\n\nfrom urllib.parse import quote\n\nfrom weather_retriever import get_weather\nfrom forex_retriever import get_rate, get_all_currencies\nfrom news_retriever import get_news\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n source = request.args.get('source')\n source = 'bbc' if not source else source.lower()\n articles = get_news(source)\n\n query = request.args.get('location')\n query = 'London, UK' if not query else query\n weather = get_weather(quote(query))\n\n all_currencies = get_all_currencies()\n\n src_currency = request.args.get('src_currency')\n src_currency = 'GBP' if not src_currency else src_currency\n dst_currency = request.args.get('dst_currency')\n dst_currency = 'VND' if not dst_currency else dst_currency\n rate = get_rate(src_currency, dst_currency)\n forex = {\n 'src_currency': src_currency,\n 'dst_currency': dst_currency,\n 'rate': rate\n }\n\n return render_template('index.html', articles=articles, weather=weather, currencies=all_currencies, forex=forex)\n\nif __name__ == '__main__':\n app.run(port=8888, debug=True)\n","sub_path":"headlines.py","file_name":"headlines.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"564208380","text":"from flask import Flask, render_template, request\nfrom sklearn.externals import joblib\nfrom geopy.geocoders import Nominatim\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index(sqft=None, condition=None):\n location = None\n valuation = None\n if request.method == 'POST':\n if request.form['sqft']:\n sqft = request.form['sqft']\n condition = request.form['condition']\n waterfront_flag = 1 if request.form.get(\"waterfront\") == 'on' else 0\n address = request.form['address']\n below_grade = request.form['below_grade']\n if len(address) > 10:\n valuation, location = better_estimator(int(sqft), waterfront_flag, int(below_grade), address)\n else:\n valuation = ballpark_estimator(int(sqft), float(condition))\n\n return render_template('index2.html',\n sqft=sqft,\n condition=condition,\n location=location,\n valuation=valuation)\n\n\ndef ballpark_estimator(sqft=2080, condition=3.4):\n return -214216.30529291916 + 292.81216765 * sqft + 43037.62951553 * condition\n\n\n# put better_estimator code here\n\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', debug=True)\n","sub_path":"tutorial/real_estate2.py","file_name":"real_estate2.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82145772","text":"import collections\nfrom collections.abc import Sequence\n\nfrom supriya import CalculationRate\nfrom supriya.synthdefs import UGen\n\n\nclass Clip(UGen):\n \"\"\"\n Clips a signal outside given thresholds.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> clip = supriya.ugens.Clip.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> clip\n Clip.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"minimum\", 0.0), (\"maximum\", 1.0)]\n )\n _valid_calculation_rates = (\n CalculationRate.AUDIO,\n CalculationRate.CONTROL,\n CalculationRate.SCALAR,\n )\n\n\nclass Fold(UGen):\n \"\"\"\n Folds a signal outside given thresholds.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> fold = supriya.ugens.Fold.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> fold\n Fold.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"minimum\", 0.0), (\"maximum\", 1.0)]\n )\n _valid_calculation_rates = (\n CalculationRate.AUDIO,\n CalculationRate.CONTROL,\n CalculationRate.SCALAR,\n )\n\n\nclass Gate(UGen):\n \"\"\"\n Gates or holds.\n\n ::\n\n >>> source = supriya.ugens.WhiteNoise.ar()\n >>> trigger = supriya.ugens.Dust.kr(1)\n >>> gate = supriya.ugens.Gate.ar(source=source, trigger=trigger,)\n >>> gate\n Gate.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass InRange(UGen):\n \"\"\"\n Tests if a signal is within a given range.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> in_range = supriya.ugens.InRange.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> in_range\n InRange.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", 0), (\"minimum\", 0), (\"maximum\", 1)]\n )\n _valid_calculation_rates = (\n CalculationRate.AUDIO,\n CalculationRate.CONTROL,\n CalculationRate.SCALAR,\n )\n\n\nclass Latch(UGen):\n \"\"\"\n Samples and holds.\n\n ::\n\n >>> source = supriya.ugens.WhiteNoise.ar()\n >>> trigger = supriya.ugens.Dust.kr(1)\n >>> latch = supriya.ugens.Latch.ar(source=source, trigger=trigger,)\n >>> latch\n Latch.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass LeastChange(UGen):\n \"\"\"\n Outputs least changed input.\n\n ::\n\n >>> least_change = supriya.ugens.LeastChange.ar(a=0, b=0,)\n >>> least_change\n LeastChange.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"a\", 0), (\"b\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass MostChange(UGen):\n \"\"\"\n Outputs most changed input.\n\n ::\n\n >>> most_change = supriya.ugens.MostChange.ar(a=0, b=0,)\n >>> most_change\n MostChange.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"a\", 0), (\"b\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Peak(UGen):\n \"\"\"\n Tracks peak signal amplitude.\n\n ::\n\n >>> source = supriya.ugens.In.ar(0)\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> peak = supriya.ugens.Peak.ar(source=source, trigger=trigger,)\n >>> peak\n Peak.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass PeakFollower(UGen):\n \"\"\"\n Tracks peak signal amplitude.\n\n ::\n\n >>> source = supriya.ugens.In.ar(0)\n >>> peak_follower = supriya.ugens.PeakFollower.ar(decay=0.999, source=source,)\n >>> peak_follower\n PeakFollower.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"decay\", 0.999)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Phasor(UGen):\n \"\"\"\n A resettable linear ramp between two levels.\n\n ::\n\n >>> trigger = supriya.ugens.Impulse.kr(0.5)\n >>> phasor = supriya.ugens.Phasor.ar(\n ... rate=1, reset_pos=0, start=0, stop=1, trigger=trigger,\n ... )\n >>> phasor\n Phasor.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"trigger\", 0), (\"rate\", 1), (\"start\", 0), (\"stop\", 1), (\"reset_pos\", 0)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Poll(UGen):\n \"\"\"\n A UGen poller.\n\n ::\n\n >>> sine = supriya.ugens.SinOsc.ar()\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> poll = supriya.ugens.Poll.ar(source=sine, trigger=trigger, trigger_id=1234,)\n >>> poll\n Poll.ar()\n\n .. container:: example\n\n Unlike **sclang**, Python does not share any inter-process\n communication with **scsynth**. This means that the Poll UGen is not\n able to automatically print out its diagnostic messages into a Python\n interpreter session.\n\n To get information out of the Poll UGen, we first need to set the\n Poll's `trigger_id` to a value greater than 0. This will cause the poll\n to send `/tr` OSC messages back to its client - Python. We can then\n register a callback to respond to these `/tr` messages.\n\n ::\n\n >>> with supriya.SynthDefBuilder() as builder:\n ... sine = supriya.ugens.SinOsc.ar()\n ... trigger = supriya.ugens.Impulse.kr(1)\n ... poll = supriya.ugens.Poll.ar(source=sine, trigger=trigger, trigger_id=1234,)\n ...\n >>> synthdef = builder.build()\n\n ::\n\n >>> server = supriya.Server.default().boot()\n >>> synth = supriya.Synth(synthdef).allocate()\n >>> callback = server.osc_protocol.register(\n ... pattern=\"/tr\",\n ... procedure=lambda response: print(\n ... \"Poll value is: {}\".format(response.value)\n ... ),\n ... once=True,\n ... )\n\n ::\n\n >>> server.quit()\n <Server: offline>\n\n \"\"\"\n\n ### CLASS VARIABLES ###\n\n __documentation_section__ = \"Utility UGens\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"trigger\", None), (\"source\", None), (\"trigger_id\", -1)]\n )\n\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n calculation_rate=None,\n label=None,\n source=None,\n trigger=None,\n trigger_id=-1,\n ):\n import supriya.synthdefs\n import supriya.ugens\n\n if label is None:\n if isinstance(source, supriya.synthdefs.UGen):\n label = type(source).__name__\n elif isinstance(source, supriya.synthdefs.OutputProxy):\n label = type(source.source).__name__\n UGen.__init__(\n self,\n calculation_rate=calculation_rate,\n source=source,\n trigger=trigger,\n trigger_id=trigger_id,\n )\n label = str(label)\n self._configure_input(\"label\", len(label))\n for character in label:\n self._configure_input(\"label\", ord(character))\n\n ### PUBLIC METHODS ###\n\n @classmethod\n def ar(cls, label=None, source=None, trigger=None, trigger_id=-1):\n import supriya.synthdefs\n\n calculation_rate = supriya.CalculationRate.AUDIO\n ugen = cls._new_expanded(\n calculation_rate=calculation_rate,\n label=label,\n source=source,\n trigger=trigger,\n trigger_id=trigger_id,\n )\n return ugen\n\n @classmethod\n def kr(cls, label=None, source=None, trigger=None, trigger_id=-1):\n import supriya.synthdefs\n\n calculation_rate = supriya.CalculationRate.CONTROL\n ugen = cls._new_expanded(\n calculation_rate=calculation_rate,\n label=label,\n source=source,\n trigger=trigger,\n trigger_id=trigger_id,\n )\n return ugen\n\n @classmethod\n def new(cls, label=None, source=None, trigger=None, trigger_id=-1):\n import supriya.synthdefs\n\n if isinstance(source, Sequence):\n source = (source,)\n calculation_rates = []\n for single_source in source:\n rate = supriya.CalculationRate.from_expr(single_source)\n calculation_rates.append(rate)\n ugen = cls._new_expanded(\n calculation_rate=calculation_rates,\n label=label,\n source=source,\n trigger=trigger,\n trigger_id=trigger_id,\n )\n return ugen\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def label(self):\n \"\"\"\n Gets `label` input of Poll.\n\n ::\n\n >>> sine = supriya.ugens.SinOsc.ar()\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> poll = supriya.ugens.Poll.ar(\n ... label=\"Foo\", source=sine, trigger=trigger, trigger_id=1234,\n ... )\n >>> poll.label\n 'Foo'\n\n Returns ugen input.\n \"\"\"\n index = tuple(self._ordered_input_names).index(\"trigger_id\") + 2\n characters = self._inputs[index:]\n characters = [chr(int(_)) for _ in characters]\n label = \"\".join(characters)\n return label\n\n\nclass RunningMax(Peak):\n \"\"\"\n Tracks maximum signal amplitude.\n\n ::\n\n >>> source = supriya.ugens.In.ar(0)\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> running_max = supriya.ugens.RunningMax.ar(source=source, trigger=0,)\n >>> running_max\n RunningMax.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass RunningMin(Peak):\n \"\"\"\n Tracks minimum signal amplitude.\n\n ::\n\n >>> source = supriya.ugens.In.ar(0)\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> running_min = supriya.ugens.RunningMin.ar(source=source, trigger=trigger,)\n >>> running_min\n RunningMin.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Schmidt(UGen):\n \"\"\"\n A Schmidt trigger.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> schmidt = supriya.ugens.Schmidt.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> schmidt\n Schmidt.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", 0), (\"minimum\", 0), (\"maximum\", 1)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass SendPeakRMS(UGen):\n \"\"\"\n Tracks peak and power of a signal for GUI applications.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.kr(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms\n SendPeakRMS.kr()\n\n \"\"\"\n\n ### CLASS VARIABLES ###\n\n _default_channel_count = 0\n _ordered_input_names = collections.OrderedDict(\n [(\"reply_rate\", 20), (\"peak_lag\", 3), (\"reply_id\", -1)]\n )\n _unexpanded_argument_names = (\"source\",)\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n calculation_rate=None,\n command_name=\"/reply\",\n peak_lag=3,\n reply_id=-1,\n reply_rate=20,\n source=None,\n ):\n UGen.__init__(\n self,\n calculation_rate=calculation_rate,\n peak_lag=peak_lag,\n reply_id=reply_id,\n reply_rate=reply_rate,\n )\n command_name = str(command_name)\n if not isinstance(source, Sequence):\n source = (source,)\n self._configure_input(\"source\", len(source))\n for input_ in source:\n self._configure_input(\"source\", input_)\n self._configure_input(\"command_name\", len(command_name))\n for character in command_name:\n self._configure_input(\"label\", ord(character))\n\n ### PUBLIC METHODS ###\n\n @classmethod\n def ar(\n cls, command_name=\"/reply\", peak_lag=3, reply_id=-1, reply_rate=20, source=None\n ):\n \"\"\"\n Constructs an audio-rate SendPeakRMS.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.ar(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms\n SendPeakRMS.ar()\n\n Returns ugen graph.\n \"\"\"\n calculation_rate = CalculationRate.AUDIO\n ugen = cls._new_single(\n calculation_rate=calculation_rate,\n command_name=command_name,\n peak_lag=peak_lag,\n reply_id=reply_id,\n reply_rate=reply_rate,\n source=source,\n )\n return ugen\n\n @classmethod\n def kr(\n cls, command_name=\"/reply\", peak_lag=3, reply_id=-1, reply_rate=20, source=None\n ):\n \"\"\"\n Constructs a control-rate SendPeakRMS.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.kr(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms\n SendPeakRMS.kr()\n\n Returns ugen graph.\n \"\"\"\n calculation_rate = CalculationRate.CONTROL\n ugen = cls._new_single(\n calculation_rate=calculation_rate,\n command_name=command_name,\n peak_lag=peak_lag,\n reply_id=reply_id,\n reply_rate=reply_rate,\n source=source,\n )\n return ugen\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def command_name(self):\n \"\"\"\n Gets `command_name` input of SendPeakRMS.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.ar(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms.command_name\n '/reply'\n\n Returns ugen input.\n \"\"\"\n index = tuple(self._ordered_input_names).index(\"reply_id\") + 1\n source_length = int(self._inputs[index])\n index += source_length + 2\n characters = self._inputs[index:]\n characters = [chr(int(_)) for _ in characters]\n command_name = \"\".join(characters)\n return command_name\n\n @property\n def source(self):\n \"\"\"\n Gets `source` input of SendPeakRMS.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.ar(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms.source\n (In.ar()[0], In.ar()[1], In.ar()[2], In.ar()[3])\n\n Returns ugen input.\n \"\"\"\n index = tuple(self._ordered_input_names).index(\"reply_id\") + 1\n source_length = int(self._inputs[index])\n start = index + 1\n stop = start + source_length\n return tuple(self._inputs[start:stop])\n\n\nclass SendTrig(UGen):\n _ordered_input_names = collections.OrderedDict(\n [(\"trigger\", None), (\"id_\", 0), (\"value\", 0)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Sweep(UGen):\n \"\"\"\n A triggered linear ramp.\n\n ::\n\n >>> sweep = supriya.ugens.Sweep.ar(rate=1, trigger=0,)\n >>> sweep\n Sweep.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"trigger\", 0), (\"rate\", 1)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass TDelay(UGen):\n \"\"\"\n A trigger delay.\n\n ::\n\n >>> source = supriya.ugens.Dust.kr()\n >>> tdelay = supriya.ugens.TDelay.ar(duration=0.1, source=source,)\n >>> tdelay\n TDelay.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"duration\", 0.1)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass ToggleFF(UGen):\n \"\"\"\n A toggle flip-flop.\n\n ::\n\n >>> trigger = supriya.ugens.Dust.kr(1)\n >>> toggle_ff = supriya.ugens.ToggleFF.ar(trigger=trigger,)\n >>> toggle_ff\n ToggleFF.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Trig1(UGen):\n \"\"\"\n A timed trigger.\n\n ::\n\n >>> source = supriya.ugens.Dust.kr(1)\n >>> trig_1 = supriya.ugens.Trig1.ar(duration=0.1, source=source,)\n >>> trig_1\n Trig1.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"duration\", 0.1)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Trig(UGen):\n \"\"\"\n A timed trigger.\n\n ::\n\n >>> source = supriya.ugens.Dust.kr(1)\n >>> trig = supriya.ugens.Trig.ar(duration=0.1, source=source,)\n >>> trig\n Trig.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"duration\", 0.1)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Wrap(UGen):\n \"\"\"\n Wraps a signal outside given thresholds.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> wrap = supriya.ugens.Wrap.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> wrap\n Wrap.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", 0), (\"minimum\", 0), (\"maximum\", 1)]\n )\n _valid_calculation_rates = (\n CalculationRate.AUDIO,\n CalculationRate.CONTROL,\n CalculationRate.SCALAR,\n )\n\n\nclass ZeroCrossing(UGen):\n \"\"\"\n A zero-crossing frequency follower.\n\n ::\n\n >>> source = supriya.ugens.In.ar(bus=0)\n >>> zero_crossing = supriya.ugens.ZeroCrossing.ar(source=source,)\n >>> zero_crossing\n ZeroCrossing.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n","sub_path":"supriya/ugens/triggers.py","file_name":"triggers.py","file_ext":"py","file_size_in_byte":19351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"304223485","text":"from google_scholar_citations_count_retriever import QueryManipulator\nfrom unittest import TestCase\nfrom third_party.scholar import ScholarArticle\n\n\nclass GoogleScholarCitationsCountRetrieverTest(TestCase):\n\n def setUp(self):\n self.articles = [self.__create_scholar_article('Made up book, volume 1', 100),\n self.__create_scholar_article('Another made up book.', 124),\n self.__create_scholar_article('Made up book: vol I', 101),\n self.__create_scholar_article('This is a different book', 23)]\n\n self.expected_report = {'best_match_title': 'Made up book: vol I',\n 'best_match_num_citations': 101,\n 'articles_list': [\n {\n 'title': 'Made up book, volume 1',\n 'num_citations': 100,\n },\n {\n 'title': 'Another made up book.',\n 'num_citations': 124,\n },\n {\n 'title': 'Made up book: vol I',\n 'num_citations': 101,\n },\n {\n 'title': 'This is a different book',\n 'num_citations': 23,\n }\n ]}\n\n @staticmethod\n def __create_scholar_article(title, citations):\n article = ScholarArticle()\n article.attrs['title'][0] = title\n article.attrs['num_citations'][0] = citations\n return article\n\n def test_find_best_matching_article(self):\n query_manipulator = QueryManipulator('Made up book, volume 1', self.articles)\n best_match = query_manipulator.find_best_matching_article()\n self.assertEqual(best_match.attrs['title'][0], 'Made up book: vol I')\n\n query_manipulator = QueryManipulator('This is a different book.', self.articles)\n best_match = query_manipulator.find_best_matching_article()\n self.assertEqual(best_match.attrs['title'][0], 'This is a different book')\n\n def test_generate_report(self):\n query_manipulator = QueryManipulator('Made up book, volume 1', self.articles)\n report = query_manipulator.generate_report()\n self.assertEqual(report, self.expected_report)","sub_path":"python/test/google_scholar_citations_count_retriever_test.py","file_name":"google_scholar_citations_count_retriever_test.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189699566","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author;鸿\nimport requests as r\nimport re\nimport time\nimport os\nword = str(input('请输入需要爬取图片的名称:'))\nurl = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&fm=index&pos=history&word={}'.format(word)\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'\n}\nresponse = r.get(url,headers=headers)\nhtml = response.text\n\nurls = re.findall('\"middleURL\":\"(.*?)\"',html)\nif not os.path.exists(word):\n os.mkdir(word)\ni=0\nfor url in urls:\n time.sleep(1)\n response = r.get(url,headers=headers)\n with open(word+'/'+str(i)+'.jpg','wb') as f:\n f.write(response.content)\n i+=1\nprint('爬取完成')","sub_path":"阶段一/百度图片爬取.py","file_name":"百度图片爬取.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"527063182","text":"\r\nfrom tkinter import *\r\nimport mysql.connector\r\nimport tkinter.messagebox as MessageBox\r\n\r\nmydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n\r\nprint(mydb)\r\n\r\nif(mydb):\r\n print(\"Connection successfull\")\r\n\r\nelse:\r\n print(\"Connection unsuccessfull\")\r\n\r\nmycursor=mydb.cursor()\r\n\r\n\r\n#creating the college table with coll_id as primary key\r\n\r\n## mycursor.execute(\" create table college(coll_id varchar(10) primary key,board varchar(10),accred varchar(10),state varchar(10),ranking int(10))\")\r\n\r\n#creating the department table with dept_id as primary key and the coll_id as foreign key\r\n\r\n## mycursor.execute(\"create table department (dept_id varchar(10) primary key,coll_id varchar(10) ,foreign key(coll_id) references college(coll_id) on delete cascade,hod_id varchar(10),instr_count int(10))\")\r\n\r\n\r\n#creating table instructor with dept_id as foreign key and instr_id as primary key\r\n\r\n## mycursor.execute(\"create table instructor(dept_id varchar(10) ,foreign key (dept_id) references department(dept_id) on delete cascade,instr_id varchar(10) primary key,rating int(10),qualification varchar(10))\")\r\n\r\n# create table courses with crc_id as primary_key and instr_id as foreign key\r\n\r\n## mycursor.execute(\"create table courses (crc_id varchar(10) primary key,instr_id varchar(10), foreign key(instr_id) references instructor(instr_id),std_count bigint(10))\")\r\n\r\n\r\n#create table student with std_id as primary key , crc_id and dept_id as foreign keys\r\n\r\n##mycursor.execute(\"create table student(std_id varchar(10) primary key,crc_id varchar(10),foreign key(crc_id) references courses(crc_id),dept_id varchar(10) , foreign key (dept_id) references department(dept_id),marks1 int(100),marks2 int(100),marks3 int(100),final_marks int (100))\")\r\n\r\n\r\n#mycursor.execute(\"Create table addresses(first_name text,last_name text,address text , city text , state text , zipcode int)\")\r\n\r\n\r\nmycursor.execute(\"show tables\")\r\nfor db in mycursor: \r\n print(db)\r\n\r\n\r\n\r\n\r\nTk, Label\r\nroot = Tk()\r\nroot.title('DBMS MINI PROJECT')\r\nroot.geometry(\"1000x1000\")\r\n\r\n# #create a submit function into the database \r\n\r\ndef insert():\r\n\r\n #to add data into the database we need to also add the creation of the database part ito the function\r\n \r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n\r\n #insert into the table \r\n coll_id_label=coll_id.get()\r\n board_label=board.get()\r\n accred_label=accred.get()\r\n state_label=state.get()\r\n ranking_label=ranking.get()\r\n\r\n mycursor.execute(\"insert into college values('\"+coll_id_label + \"' , '\"+board_label + \"' , '\"+accred_label + \"', '\"+state_label + \"','\"+ ranking_label + \"')\")\r\n \r\n \r\n\r\n #clear the text boxes\r\n coll_id.delete(0,END)\r\n board.delete(0,END)\r\n accred.delete(0,END)\r\n state.delete(0,END)\r\n ranking.delete(0,END)\r\n \r\n \r\n\r\n mydb.commit()\r\n MessageBox.showinfo(\"Inserted Status\",\"Inserted Successfully\")\r\n show()\r\n mydb.close()\r\n \r\n#\r\ndef delete():\r\n\r\n #delete from the table \r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n\r\n #execute the query\r\n coll_id_label=coll_id.get()\r\n mycursor.execute(\"delete from college where coll_id='\"+coll_id_label+\"'\")\r\n \r\n coll_id.delete(0,END)\r\n board.delete(0,END)\r\n accred.delete(0,END)\r\n state.delete(0,END)\r\n ranking.delete(0,END)\r\n mydb.commit()\r\n MessageBox.showinfo(\"Deleted Status\",\"Deleted Successfully\")\r\n show()\r\n \r\n mydb.close()\r\n \r\n\r\n\r\ndef update():\r\n \r\n #insert into the table \r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n\r\n #insert into the table \r\n coll_id_label=coll_id.get()\r\n board_label=board.get()\r\n accred_label=accred.get()\r\n state_label=state.get()\r\n ranking_label=ranking.get()\r\n \r\n mycursor.execute('''UPDATE college SET board=%s ,accred =%s ,state =%s ,ranking=%s where coll_id=%s''',(board_label ,accred_label ,state_label,ranking_label ,coll_id_label) )\r\n # mycursor.execute(\"update college set board_label='\"+board_label + \"',accred_label='\"+accred_label + \"',state_label= '\"+state_label + \"',ranking_label='\"+ ranking_label + \"' where coll_id_label='\"+ coll_id_label +\"'\")\r\n \r\n coll_id.delete(0,END)\r\n board.delete(0,END)\r\n accred.delete(0,END)\r\n state.delete(0,END)\r\n ranking.delete(0,END)\r\n \r\n mydb.commit()\r\n MessageBox.showinfo(\"Update Status\",\"Updated Successfully\")\r\n show()\r\n mydb.close()\r\n \r\n\r\n #clear the text boxes\r\n \r\n\r\n\r\ndef get():\r\n \r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n\r\n #execute the query\r\n coll_id_label=coll_id.get()\r\n mycursor.execute(\"select * from college where coll_id='\"+coll_id_label+\"'\")\r\n rows = mycursor.fetchall()\r\n for row in rows:\r\n board.insert(0,row[1])\r\n accred.insert(0,row[2])\r\n state.insert(0,row[3])\r\n ranking.insert(0,row[4]) \r\n \r\n \r\n mydb.commit()\r\n mydb.close()\r\n\r\ndef show():\r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n mycursor.execute(\"select * from college\")\r\n rows=mycursor.fetchall()\r\n list.delete(0, list.size())\r\n\r\n for row in rows:\r\n insertData = row[0]+ ' | ' + row[1] + ' | ' + row[2] + ' | ' + row[3] + ' | ' + str(row[4])\r\n list.insert(list.size()+1 , insertData)\r\n\r\n mydb.commit()\r\n mydb.close()\r\n\r\ncoll_id=Entry(root,width=30)\r\ncoll_id.place(x=150,y=30)\r\n\r\n\r\nboard=Entry(root,width=30)\r\nboard.place(x=150,y=60)\r\n\r\naccred=Entry(root,width=30)\r\naccred.place(x=150,y=90)\r\n\r\nstate=Entry(root,width=30)\r\nstate.place(x=150,y=120)\r\n\r\nranking=Entry(root,width=30)\r\nranking.place(x=150,y=150)\r\n\r\n\r\n\r\n# Create text box label for college table \r\n\r\ncoll_id_label=Label(root , text=\"College Id\")\r\ncoll_id_label.place(x=20,y=30)\r\n\r\n\r\nboard_label=Label(root , text=\"Board\")\r\nboard_label.place(x=20,y=60)\r\n\r\naccred_label=Label(root , text=\"Accredation\")\r\naccred_label.place(x=20,y=90)\r\n\r\nstate_label=Label(root , text=\"State\")\r\nstate_label.place(x=20,y=120)\r\n\r\nranking_label=Label(root , text=\"Ranking\")\r\nranking_label.place(x=20,y=150)\r\n\r\n\r\n# # create a submit button\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ninsert = Button(root , text=\"insert\" , command=insert)\r\ninsert.place(x=50,y=180)\r\n\r\ndelete = Button(root , text=\"Delete \" , command=delete)\r\ndelete.place(x=100,y=180)\r\n\r\nupdate = Button(root , text=\"Update \" , command=update)\r\nupdate.place(x=160,y=180)\r\n\r\nget = Button(root , text=\"get\" , command=get)\r\nget.place(x=220,y=180)\r\n\r\nlist = Listbox(root)\r\nlist.place(x=350 , y=20)\r\nshow()\r\nroot.mainloop()\r\n","sub_path":"college.py","file_name":"college.py","file_ext":"py","file_size_in_byte":6917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"153957373","text":"# https://www.hackerrank.com/challenges/dynamic-array/problem\n# Create a list, seqList, of N empty sequences, where each sequence is indexed from 0 to N.\n# The elements within each of the sequences also use 0-indexing.\n# Create an integer, lastAnswer, and initialize it to 0.\nfile_ = '03.txt'\nseqList = []\nlastAnswer = 0\n\nwith open(file_, 'r') as inputs:\n data = inputs.readlines()\n n, q = map(int, data[0].split(' '))\n inputs.close()\n\nfor i in range(n):\n seqList.append([])\n\ndef query_one(x, y, n, last_answer):\n temp_index = (x ^ last_answer) % n\n seqList[temp_index].append(y)\n\ndef query_two(x, y, n, last_answer):\n temp_index = (x ^ last_answer) % n\n seq = seqList[temp_index]\n last_answer = seqList[temp_index][y % len(seq)]\n return last_answer\n\nfor i in range(q):\n query, x, y = map(int, data[i+1].split(' '))\n if query == 1:\n query_one(x, y, n, lastAnswer)\n elif query == 2:\n lastAnswer = query_two(x, y, n, lastAnswer)\n print(lastAnswer)","sub_path":"Arrays/03.py","file_name":"03.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"593954304","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom datetime import datetime, timedelta\n\nfrom django.conf import settings\nfrom dimagi.utils.chunked import chunked\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext as _\nfrom django.urls import reverse\nfrom memoized import memoized\n\nfrom corehq.elastic import ES_MAX_CLAUSE_COUNT\nfrom corehq.apps.es.case_search import flatten_result\nfrom corehq.apps.locations.models import SQLLocation\nfrom corehq.apps.sms.models import MessagingEvent\nfrom casexml.apps.case.models import CommCareCase\nfrom corehq.motech.repeaters.dbaccessors import (\n iter_repeat_records_by_domain,\n get_repeat_record_count,\n get_repeat_records_by_payload_id,\n get_repeaters_by_domain,\n)\nfrom corehq.motech.repeaters.views import DomainForwardingRepeatRecords\nfrom corehq.apps.es import CaseSearchES\nfrom corehq.apps.reports.generic import GenericTabularReport\nfrom corehq.apps.reports.filters.select import RepeaterFilter\nfrom corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn\n\nfrom custom.enikshay.case_utils import get_person_case, CASE_TYPE_VOUCHER\nfrom custom.enikshay.exceptions import ENikshayException\nfrom custom.enikshay.reports.filters import VoucherStateFilter, DistrictLocationFilter, VoucherIDFilter\nfrom custom.enikshay.integrations.bets.repeaters import ChemistBETSVoucherRepeater, LabBETSVoucherRepeater\nfrom corehq.apps.reports.dispatcher import CustomProjectReportDispatcher\nfrom corehq.apps.reports.filters.select import RepeatRecordStateFilter\nfrom dimagi.utils.modules import to_function\n\n\nclass ENikshayRepeaterFilter(RepeaterFilter):\n\n def __init__(self, *args, **kwargs):\n super(ENikshayRepeaterFilter, self).__init__(*args, **kwargs)\n self.enikshay_repeaters = tuple(to_function(cls, failhard=True) for cls in settings.ENIKSHAY_REPEATERS)\n\n def _get_repeaters(self):\n return [\n repeater for repeater in get_repeaters_by_domain(self.domain)\n if isinstance(repeater, self.enikshay_repeaters)\n ]\n\n\nclass ENikshayForwarderReport(DomainForwardingRepeatRecords):\n name = 'eNikshay Forwarder Report'\n base_template = 'reports/base_template.html'\n asynchronous = True\n section_name = 'Custom Reports'\n slug = 'enikshay_repeater_report'\n dispatcher = CustomProjectReportDispatcher\n fields = (ENikshayRepeaterFilter, RepeatRecordStateFilter)\n exportable = True\n exportable_all = True\n\n emailable = True\n\n @property\n def get_all_rows(self):\n repeater_id = self.request.GET.get('repeater', None)\n state = self.request.GET.get('record_state', None)\n if self.is_rendered_as_email:\n same_time_yesterday = datetime.today() - timedelta(days=1)\n return [\n [\n get_repeat_record_count(self.domain, repeater_id, \"SUCCESS\"),\n get_repeat_record_count(self.domain, repeater_id, \"SUCCESS\", same_time_yesterday),\n get_repeat_record_count(self.domain, repeater_id, \"CANCELLED\"),\n get_repeat_record_count(self.domain, repeater_id, \"CANCELLED\", same_time_yesterday),\n ]\n ]\n return [self._make_row(record) for record in\n iter_repeat_records_by_domain(self.domain, repeater_id=repeater_id, state=state)]\n\n @property\n def headers(self):\n if self.is_rendered_as_email:\n columns = [\n DataTablesColumn(_('Successful Records')),\n DataTablesColumn(_('Successful Records in Last 24 hours')),\n DataTablesColumn(_('Cancelled Records')),\n DataTablesColumn(_('Cancelled Records in Last 24 hours')),\n ]\n else:\n columns = [\n DataTablesColumn(_('Record ID')),\n DataTablesColumn(_('Status')),\n DataTablesColumn(_('Person Case')),\n DataTablesColumn(_('Payload Case')),\n DataTablesColumn(_('URL')),\n DataTablesColumn(_('Last sent date')),\n DataTablesColumn(_('Attempts')),\n ]\n return DataTablesHeader(*columns)\n\n def _make_row(self, record):\n attempt_messages = [\n escape(\"{date}: {message}\".format(\n date=self._format_date(attempt.datetime),\n message=attempt.message))\n for attempt in record.attempts]\n\n row = [\n record._id,\n self._get_state(record)[1],\n self._get_person_id_link(record),\n self._get_case_id_link(record.payload_id),\n record.url if record.url else _('Unable to generate url for record'),\n self._format_date(record.last_checked) if record.last_checked else '---',\n \",<br />\".join(attempt_messages),\n ]\n return row\n\n def _get_person_id_link(self, record):\n try:\n person_id = get_person_case(self.domain, record.payload_id).case_id\n return self._get_case_id_link(person_id)\n except ENikshayException as error:\n return \"Error: {}\".format(error)\n\n def _get_case_id_link(self, case_id):\n return '<a href=\"{url}\" target=\"_blank\">{case_id}</a>'.format(\n url=reverse('case_data', args=[self.domain, case_id]),\n case_id=case_id\n )\n\n\nclass ENikshayVoucherReport(GenericTabularReport):\n slug = 'enikshay_voucher_repeater_report'\n section_name = 'Custom Reports'\n name = 'BETS Voucher Report'\n\n base_template = 'reports/base_template.html'\n dispatcher = CustomProjectReportDispatcher\n exportable = True\n exportable_all = True\n\n asynchronous = True\n ajax_pagination = True\n\n sortable = False\n\n fields = (VoucherStateFilter, DistrictLocationFilter, VoucherIDFilter)\n\n @property\n def district_ids(self):\n return self.request.GET.getlist('district_ids')\n\n @property\n def voucher_state(self):\n return self.request.GET.get('voucher_state')\n\n @property\n def voucher_id(self):\n return self.request.GET.get('voucher_id')\n\n @property\n def headers(self):\n return DataTablesHeader(\n DataTablesColumn('Voucher Case ID'),\n DataTablesColumn('Voucher Readable ID'),\n DataTablesColumn('Voucher Status'),\n DataTablesColumn('Voucher District ID'),\n DataTablesColumn('Voucher Type'),\n DataTablesColumn('Voucher Approved Amount'),\n DataTablesColumn('Voucher Beneficiary ID'),\n DataTablesColumn('Voucher Beneficiary Name'),\n DataTablesColumn('Voucher Issued by Name'),\n\n DataTablesColumn('Amount Paid'),\n DataTablesColumn('Date Paid'),\n DataTablesColumn('Comments'),\n DataTablesColumn('Payment Mode'),\n DataTablesColumn('Check Number'),\n DataTablesColumn('Bank Name'),\n DataTablesColumn('Reason Rejected'),\n DataTablesColumn('Date Rejected'),\n DataTablesColumn('Messaging Activity'),\n\n DataTablesColumn('BETS Sent Date'),\n DataTablesColumn('Forwading Status'),\n DataTablesColumn('BETS Response Message'),\n )\n\n @property\n def rows(self):\n return self.get_rows(paged=True)\n\n @property\n def get_all_rows(self):\n return self.get_rows(paged=False)\n\n def get_rows(self, paged=True):\n location_ids = self._get_voucher_location_ids()\n if location_ids:\n vouchers = []\n for location_id_chunk in chunked(location_ids, ES_MAX_CLAUSE_COUNT):\n vouchers += [\n CommCareCase.wrap(flatten_result(result))\n for result in self._search_results(paged, location_id_chunk).raw_hits\n ]\n else:\n vouchers = [\n CommCareCase.wrap(flatten_result(result))\n for result in self._search_results(paged).raw_hits\n ]\n\n return [row for voucher in vouchers for row in self._make_rows(voucher)]\n\n @memoized\n def _search_results(self, paged=True, location_ids=None):\n cs = (\n CaseSearchES()\n .domain(self.domain)\n .case_type(CASE_TYPE_VOUCHER)\n )\n\n if location_ids:\n cs = cs.case_property_query('voucher_fulfilled_by_location_id', \" \".join(location_ids))\n\n if self.voucher_state:\n cs = cs.case_property_query('state', self.voucher_state)\n\n if self.voucher_id:\n cs = cs.case_property_query('voucher_id', self.voucher_id)\n\n if paged:\n cs = cs.start(self.pagination.start).size(self.pagination.count)\n\n return cs.run()\n\n @memoized\n def _get_voucher_location_ids(self):\n \"\"\"Return all locations beneath the district that could own the voucher\n \"\"\"\n district_locs = SQLLocation.active_objects.filter(location_id__in=self.district_ids)\n voucher_location_types = ['plc', 'pcc', 'pdr', 'dto']\n possible_location_ids = (\n SQLLocation.active_objects\n .get_queryset_descendants(district_locs, include_self=True)\n .filter(location_type__code__in=voucher_location_types)\n .values_list('location_id', flat=True)\n )\n return possible_location_ids\n\n def get_messaging_event_detail_link(self, messaging_event_id):\n return (\n '<a target=\"_blank\" href=\"/a/%s/reports/message_event_detail/?id=%s\">[%s]</a>' %\n (self.domain, messaging_event_id, messaging_event_id)\n )\n\n def get_messaging_event_links(self, voucher_case_id):\n event_pks = (\n MessagingEvent\n .objects\n .filter(domain=self.domain, messagingsubevent__case_id=voucher_case_id)\n .values_list('pk', flat=True)\n .distinct()\n .order_by('date')\n )\n\n return ', '.join([self.get_messaging_event_detail_link(pk) for pk in event_pks])\n\n def _make_rows(self, voucher):\n default_row = [\n voucher.case_id,\n voucher.get_case_property('voucher_id'),\n voucher.get_case_property('state'),\n voucher.get_case_property('voucher_district_id'),\n voucher.get_case_property('voucher_type'),\n voucher.get_case_property('amount_approved'),\n voucher.get_case_property('voucher_fulfilled_by_id'),\n voucher.get_case_property('voucher_fulfilled_by_name'),\n voucher.get_case_property('voucher_issued_by_name'),\n voucher.get_case_property('amount_paid'),\n voucher.get_case_property('date_paid'),\n voucher.get_case_property('comments'),\n voucher.get_case_property('payment_mode'),\n voucher.get_case_property('check_number'),\n voucher.get_case_property('bank_name'),\n voucher.get_case_property('reason_rejected'),\n voucher.get_case_property('date_rejected'),\n self.get_messaging_event_links(voucher.case_id),\n ]\n\n repeat_records = self._get_voucher_repeat_records(voucher.case_id)\n if not repeat_records:\n return [default_row + [\"-\", \"-\", \"-\"]]\n\n rows = []\n for repeat_record in repeat_records:\n attempt_messages = [\n escape(\"{date}: {message}\".format(\n date=attempt.datetime,\n message=attempt.message))\n for attempt in repeat_record.attempts\n ]\n rows.append(\n default_row + [\n repeat_record.last_checked if repeat_record.last_checked else '-',\n repeat_record.state,\n \",<br />\".join(attempt_messages),\n ]\n )\n return rows\n\n def _get_voucher_repeat_records(self, voucher_id):\n repeat_records = get_repeat_records_by_payload_id(self.domain, voucher_id)\n return [r for r in repeat_records if r.repeater_id in self._get_voucher_repeater_ids()]\n\n def _get_voucher_repeater_ids(self):\n return [\n repeater._id for repeater in get_repeaters_by_domain(self.domain)\n if isinstance(repeater, (LabBETSVoucherRepeater, ChemistBETSVoucherRepeater))\n ]\n\n @property\n def total_records(self):\n location_ids = self._get_voucher_location_ids()\n if location_ids:\n total = 0\n for location_id_chunk in chunked(location_ids, ES_MAX_CLAUSE_COUNT):\n total += self._search_results(location_ids=location_id_chunk).total\n else:\n total = self._search_results().total\n return total\n\n @property\n def shared_pagination_GET_params(self):\n return [\n dict(name='district_ids', value=self.district_ids),\n dict(name='voucher_state', value=self.voucher_state),\n dict(name='voucher_id', value=self.voucher_id),\n ]\n","sub_path":"custom/enikshay/reports/repeaters.py","file_name":"repeaters.py","file_ext":"py","file_size_in_byte":13009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226615743","text":"#!/usr/bin/env python\n\nimport json, argparse\nfrom datetime import datetime, timezone\n# external:\nimport dateparser\nfrom matplotlib import pyplot as plt\n\ndef dateutil_parse_local(point_in_time: str):\n dt = dateparser.parse(point_in_time)\n return dt\n\ndef dateutil_parse_utc(point_in_time: str):\n dt = dateparser.parse(point_in_time, settings={'TIMEZONE': 'UTC'})\n return dt.replace(tzinfo=timezone.utc)\n\n# general metrics\nGEN = []\nwith open(\"metrics_gen.jsonl\", \"rt\") as f:\n for line in f.readlines():\n GEN.append(json.loads(line))\n # example chunk:\n #{'data': [{'capacityUtilized': 'N/A',\n # 'connectedPVCount': '27112',\n # 'dataRate': '586,518.88',\n # 'dataRateGBPerDay': '47.19',\n # 'dataRateGBPerYear': '17,226.17',\n # 'disconnectedPVCount': '9470',\n # 'eventRate': '28,665.56',\n # 'formattedWriteThreadSeconds': '0.49',\n # 'instance': 'appliance0',\n # 'maxETLPercentage': '0',\n # 'pvCount': '36582',\n # 'secondsConsumedByWritter': '0.48627441860465126',\n # 'status': 'Working',\n # 'timeForOverallETLInSeconds(0)': '0',\n # 'timeForOverallETLInSeconds(1)': '0',\n # 'totalETLRuns(0)': '0',\n # 'totalETLRuns(1)': '0'}],\n # 'duration': 0.028889894485473633,\n # 'start': 1601028901.436821}\n\n# detailed metrics\nDET = []\nwith open(\"metrics_det.jsonl\", \"rt\") as f:\n for line in f.readlines():\n DET.append(json.loads(line))\n #{'data': [{'name': 'Appliance Identity',\n # 'source': 'mgmt',\n # 'value': 'appliance0'},\n # {'name': 'Total PV count', 'source': 'engine', 'value': '2103'},\n # {'name': 'Disconnected PV count', 'source': 'engine', 'value': '0'},\n # {'name': 'Connected PV count', 'source': 'engine', 'value': '2103'},\n # {'name': 'Paused PV count', 'source': 'engine', 'value': '0'},\n # {'name': 'Total channels', 'source': 'engine', 'value': '16824'},\n # {'name': 'Approx pending jobs in engine queue',\n # 'source': 'engine',\n # 'value': '1'},\n # {'name': 'Event Rate (in events/sec)',\n # 'source': 'engine',\n # 'value': '2,093.91'},\n # {'name': 'Data Rate (in bytes/sec)',\n # 'source': 'engine',\n # 'value': '46,975.96'},\n # {'name': 'Data Rate in (GB/day)',\n # 'source': 'engine',\n # 'value': '3.78'},\n # {'name': 'Data Rate in (GB/year)',\n # 'source': 'engine',\n # 'value': '1,379.69'},\n # {'name': 'Time consumed for writing samplebuffers to STS (in secs)',\n # 'source': 'engine',\n # 'value': '0.1'},\n # {'name': 'Benchmark - writing at (events/sec)',\n # 'source': 'engine',\n # 'value': '216,425.2'},\n # {'name': 'Benchmark - writing at (MB/sec)',\n # 'source': 'engine',\n # 'value': '4.63'},\n # {'name': 'PVs pending computation of meta info',\n # 'source': 'engine',\n # 'value': '0'},\n # {'name': 'Total number of reference counted channels',\n # 'source': 'engine',\n # 'value': '2103'},\n # {'name': 'Total number of CAJ channels',\n # 'source': 'engine',\n # 'value': '2103'},\n # {'name': 'Channels with pending search requests',\n # 'source': 'engine',\n # 'value': '0 of 2103'},\n # {'name': 'PVs in archive workflow',\n # 'source': 'mgmt',\n # 'value': '18753'},\n # {'name': 'Capacity planning last update',\n # 'source': 'mgmt',\n # 'value': 'Sep/25/2020 10:41:38 +00:00'},\n # {'name': 'Engine write thread usage', 'source': 'mgmt', 'value': '0'},\n # {'name': 'Aggregated appliance storage rate (in GB/year)',\n # 'source': 'mgmt',\n # 'value': '5,950.75'},\n # {'name': 'Aggregated appliance event rate (in events/sec)',\n # 'source': 'mgmt',\n # 'value': '10,129.47'},\n # {'name': 'Aggregated appliance PV count',\n # 'source': 'mgmt',\n # 'value': '10,000'},\n # {'name': 'Incremental appliance storage rate (in GB/year)',\n # 'source': 'mgmt',\n # 'value': '5,950.75'},\n # {'name': 'Incremental appliance event rate (in events/sec)',\n # 'source': 'mgmt',\n # 'value': '10,129.47'},\n # {'name': 'Incremental appliance PV count',\n # 'source': 'mgmt',\n # 'value': '10,000'}],\n # 'duration': 0.0041654109954833984,\n # 'start': 1601031014.5272684}\n\n# memory metrics\nMEM = []\nwith open(\"metrics_mem.jsonl\", \"rt\") as f:\n for line in f.readlines():\n MEM.append(json.loads(line))\n #{'data': [{'data': [[1601198632000, 2.54],\n # [1601203852000, 18.47],\n # [1601203912000, 17.61]],\n # 'label': 'system_load (%)'},\n # {'data': [[1601198632000, 5.784291436430067],\n # [1601198993000, 35.940306703560054],\n # [1601203912000, 23.69133603060618]],\n # 'label': 'engine_heap (%)'},\n # {'data': [[1601198633000, 5.833119561430067],\n # [1601198933000, 24.62394153699279],\n # [1601203913000, 27.25578915560618]],\n # 'label': 'etl_heap (%)'},\n # {'data': [[1601198635000, 5.881947686430067],\n # [1601198695000, 16.95973655441776],\n # [1601203915000, 21.66814556112513]],\n # 'label': 'retrieval_heap (%)'}],\n # 'duration': 0.0038259029388427734,\n # 'start': 1601203959.5360134}\n\ndef get_args():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--start', '-s', type=dateutil_parse_local)\n parser.add_argument('--end', '-e', type=dateutil_parse_local)\n return parser.parse_args()\n\nargs = get_args()\n\ndef filter_start_end(ds, start=None, end=None):\n if args.start:\n ds = [chunk for chunk in ds if chunk[\"start\"] > args.start.timestamp()]\n if args.end:\n ds = [chunk for chunk in ds if chunk[\"start\"] < args.end.timestamp()]\n return ds\n\ndef convert_start_to_datetime(ds):\n for chunk in ds:\n #chunk[\"start\"] = datetime.utcfromtimestamp(chunk[\"start\"])\n chunk[\"start\"] = datetime.fromtimestamp(chunk[\"start\"])\n return ds\n\nGEN = convert_start_to_datetime(filter_start_end(GEN, args.start, args.end))\nDET = convert_start_to_datetime(filter_start_end(DET, args.start, args.end))\nMEM = convert_start_to_datetime(filter_start_end(MEM, args.start, args.end))\n\nplots = [\n {\n 'slug': 'duration-vs-time',\n 'title': 'duration plottet against date/time',\n 'method': 'plot',\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: chunk[\"duration\"],\n },\n {\n 'slug': 'disconnectedPVCount-vs-totalPVcount',\n 'method': 'scatter',\n 'x': lambda chunk: int(chunk[\"data\"][0][\"pvCount\"]),\n 'y': lambda chunk: int(chunk[\"data\"][0][\"disconnectedPVCount\"]),\n },\n {\n 'slug': 'secondsConsumedByWritter-vs-connectedPVCount',\n 'x': lambda chunk: int(chunk[\"data\"][0][\"connectedPVCount\"]),\n 'y': lambda chunk: flt(chunk[\"data\"][0][\"secondsConsumedByWritter\"]),\n },\n {\n 'slug': 'secondsConsumedByWritter-vs-eventRate',\n 'x': lambda chunk: flt(chunk[\"data\"][0][\"eventRate\"]),\n 'y': lambda chunk: flt(chunk[\"data\"][0][\"secondsConsumedByWritter\"]),\n },\n {\n 'slug': 'connectedPVCount-vs-start',\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: int(chunk[\"data\"][0][\"connectedPVCount\"]),\n },\n {\n 'slug': 'secondsConsumedByWritter-vs-start',\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: flt(chunk[\"data\"][0][\"secondsConsumedByWritter\"]),\n },\n {\n 'slug': 'dataRate-vs-connectedPVCount',\n 'method': 'scatter',\n 'method_kwargs': {'s': 0.4},\n 'x': lambda chunk: int(chunk[\"data\"][0][\"connectedPVCount\"]),\n 'y': lambda chunk: flt(chunk[\"data\"][0][\"dataRate\"]),\n },\n {\n 'slug': \"benchmarkEventsPerS-vs-start\",\n 'data': DET,\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: flt(choose(chunk[\"data\"], \"Benchmark - writing at (events/sec)\", \"nan\")),\n },\n {\n 'slug': \"pvs-in-archive-workflow--vs--start\",\n 'data': DET,\n 'method': 'scatter',\n 'method_kwargs': {'s': 0.4},\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: int(choose(chunk[\"data\"], \"PVs in archive workflow\")),\n },\n {\n 'slug': \"pending-vs-start\",\n 'data': DET,\n 'method': 'scatter',\n 'method_kwargs': {'s': 0.4},\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: int(choose(chunk[\"data\"], \"Channels with pending search requests\", \"0 of 0\").partition(\" of \")[0]),\n },\n {\n 'slug': \"pending-vs-total\",\n 'data': DET,\n 'method': 'scatter',\n 'method_kwargs': {'s': 0.4},\n 'x': lambda chunk: int(choose(chunk[\"data\"], \"Channels with pending search requests\", \"0 of 0\").partition(\" of \")[2]),\n 'y': lambda chunk: int(choose(chunk[\"data\"], \"Channels with pending search requests\", \"0 of 0\").partition(\" of \")[0]),\n },\n {\n 'slug': \"system_load\",\n 'data': MEM,\n 'x': lambda chunk: datetime.fromtimestamp(first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"system_load (%)\", lambda x: x[\"data\"][-1][0])/1000),\n 'y': lambda chunk: first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"system_load (%)\", lambda x: x[\"data\"][-1][1]),\n },\n {\n 'slug': \"engine_heap\",\n 'data': MEM,\n 'x': lambda chunk: datetime.fromtimestamp(first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"engine_heap (%)\", lambda x: x[\"data\"][-1][0])/1000),\n 'y': lambda chunk: first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"engine_heap (%)\", lambda x: x[\"data\"][-1][1]),\n },\n {\n 'slug': \"etl_heap\",\n 'data': MEM,\n 'x': lambda chunk: datetime.fromtimestamp(first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"etl_heap (%)\", lambda x: x[\"data\"][-1][0])/1000),\n 'y': lambda chunk: first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"etl_heap (%)\", lambda x: x[\"data\"][-1][1]),\n },\n {\n 'slug': \"retrieval_heap\",\n 'data': MEM,\n 'x': lambda chunk: datetime.fromtimestamp(first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"retrieval_heap (%)\", lambda x: x[\"data\"][-1][0])/1000),\n 'y': lambda chunk: first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"retrieval_heap (%)\", lambda x: x[\"data\"][-1][1]),\n },\n\n]\n\ndef flt(val):\n return float(val.replace(\",\", \"\"))\n\ndef first_matching_from_iterable(candidates, match_func, extract_func=None):\n for candidate in candidates:\n if match_func(candidate):\n # we found our match\n if extract_func:\n return extract_func(candidate)\n else:\n return candidate\n raise ValueError(\"No match found\")\n\ndef choose(iterable, name, if_not_found=None):\n try:\n return first_matching_from_iterable(iterable, lambda x: x[\"name\"] == name, lambda x: x[\"value\"])\n except ValueError:\n return if_not_found\n\nfor plot in plots:\n print(plot.get(\"title\", plot.get(\"slug\")))\n # we have the following data sources: GEN, DET, MEM; default is GEN\n data = plot.get(\"data\", GEN)\n x = [plot[\"x\"](chunk) for chunk in data]\n y = [plot[\"y\"](chunk) for chunk in data]\n plt.figure(figsize=(10, 6))\n plt.title(plot.get(\"title\", plot.get(\"slug\")))\n method = plot.get(\"method\", \"plot\")\n getattr(plt, method)(x, y, **plot.get(\"method_kwargs\", {}))\n plt.savefig(f\"plots/{plot['slug']}.png\", dpi=200)\n plt.show()\n","sub_path":"plot_data.py","file_name":"plot_data.py","file_ext":"py","file_size_in_byte":12619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"56151252","text":" # -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 22 14:58:07 2019\n\n@author: Shachar\n\"\"\"\n\n#read from Excel the syllables, their type and their scores.\n#The function performs pre-processing: remove DC, padding zeros, decimation and normalization.\n# Returns: image, score, and true value\n#Pay attention to line 27 and 36 (path of file)\n\n\n\ndef ReadingAudio():\n import scipy\n from scipy import signal\n from scipy.io import wavfile\n from pathlib import Path\n import numpy as np\n from scipy.misc import imresize\n import xlrd\n from AudioPreProcessing import AudioPreProcessing\n from skimage import img_as_ubyte\n \n # Open the gold standard xl\n xl_workbook = xlrd.open_workbook(r\"C:\\Users\\yaniv\\Desktop\\project2019\\May\\gold standars.xlsx\")\n xl_sheet = xl_workbook.sheet_by_index(0)\n \n num_rows = xl_sheet.nrows # Number of rows\n \n Rec_path = 'E:/Recordings/Adult/2017' #yaniv\n \n Image = [None] * num_rows\n TrueLabels = [None] * num_rows\n Data = [None] * num_rows\n Precentages = [None] * num_rows\n for row_idx in range(1,num_rows): # Iterate through rows\n current_row = xl_sheet.row_values(row_idx)\n data_folder = Path(Rec_path + \"/%s relevant/%s/ch1\" %(current_row[2], current_row[1]))\n file = \"%s.wav\" %(current_row[3])\n file_to_open = data_folder / file\n sample_rate, samples = wavfile.read(file_to_open)\n PreProcessedAudio=AudioPreProcessing(sample_rate, samples)\n frequencies, times, spectrogram = signal.spectrogram(PreProcessedAudio, sample_rate)\n list_times=list( times)\n first_num = times[times>=current_row[4]][0]\n first_ind = list_times.index(first_num)\n sec_num = times[times>=current_row[5]][0]\n sect_ind = list_times.index(sec_num)\n x=spectrogram[:,first_ind:sect_ind]\n \n # DC removal\n x-=scipy.mean(x)\n \n # zero padding to size 200\n size=400\n c,r=np.shape(x)\n padr1=int((size-r)/2)\n padr2=size-r-padr1\n padc1=int((size-c)/2)\n padc2=size-c-padc1\n Padded=np.pad(x, [(padc1, padc2), (padr1, padr2)], mode='constant')\n \n # Decimation to a size of (32,32)\n DecIm=imresize(Padded, (32,32), interp='bilinear', mode=None)\n # from PIL import Image\n\n # DecIm = np.array(Image.fromarray(Padded).resize([32,32],resample = Image.BILINEAR)) \n\n # normalization\n img=DecIm/np.amax(DecIm)\n # Data[row_idx] = img\n\n Data[row_idx] = img_as_ubyte(img)\n TrueLabels[row_idx] = current_row[6]\n Precentages[row_idx] = current_row[7]\n Image[row_idx] = x\n \n return(Data,TrueLabels,Precentages,Image)\n","sub_path":"Reading data and preprocessing/ReadingAudio.py","file_name":"ReadingAudio.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"521711172","text":"# # ⚠ Warning\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\n# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# [🥭 Mango Markets](https://mango.markets/) support is available at:\n# [Docs](https://docs.mango.markets/)\n# [Discord](https://discord.gg/67jySBhxrg)\n# [Twitter](https://twitter.com/mangomarkets)\n# [Github](https://github.com/blockworks-foundation)\n# [Email](mailto:hello@blockworks.foundation)\n\nimport typing\n\nfrom decimal import Decimal\nfrom pyserum.market import Market as PySerumMarket\nfrom solana.publickey import PublicKey\n\nfrom .account import Account\nfrom .combinableinstructions import CombinableInstructions\nfrom .context import Context\nfrom .group import Group\nfrom .instructions import build_serum_consume_events_instructions, build_spot_place_order_instructions, build_cancel_spot_order_instructions, build_spot_settle_instructions, build_spot_openorders_instructions\nfrom .marketinstructionbuilder import MarketInstructionBuilder\nfrom .orders import Order\nfrom .publickey import encode_public_key_for_sorting\nfrom .spotmarket import SpotMarket\nfrom .tokenaccount import TokenAccount\nfrom .wallet import Wallet\n\n\n# # 🥭 SpotMarketInstructionBuilder\n#\n# This file deals with building instructions for Spot markets.\n#\n# As a matter of policy for all InstructionBuidlers, construction and build_* methods should all work with\n# existing data, requiring no fetches from Solana or other sources. All necessary data should all be loaded\n# on initial setup in the `load()` method.\n#\n\nclass SpotMarketInstructionBuilder(MarketInstructionBuilder):\n def __init__(self, context: Context, wallet: Wallet, group: Group, account: Account, spot_market: SpotMarket, raw_market: PySerumMarket, market_index: int, fee_discount_token_address: typing.Optional[PublicKey]):\n super().__init__()\n self.context: Context = context\n self.wallet: Wallet = wallet\n self.group: Group = group\n self.account: Account = account\n self.spot_market: SpotMarket = spot_market\n self.raw_market: PySerumMarket = raw_market\n self.market_index: int = market_index\n self.fee_discount_token_address: typing.Optional[PublicKey] = fee_discount_token_address\n\n self.open_orders_address: typing.Optional[PublicKey] = self.account.spot_open_orders[self.market_index]\n\n @staticmethod\n def load(context: Context, wallet: Wallet, group: Group, account: Account, spot_market: SpotMarket) -> \"SpotMarketInstructionBuilder\":\n raw_market: PySerumMarket = PySerumMarket.load(\n context.client.compatible_client, spot_market.address, context.serum_program_address)\n\n fee_discount_token_address: typing.Optional[PublicKey] = None\n srm_token = context.token_lookup.find_by_symbol(\"SRM\")\n if srm_token is not None:\n fee_discount_token_account = TokenAccount.fetch_largest_for_owner_and_token(\n context, wallet.address, srm_token)\n if fee_discount_token_account is not None:\n fee_discount_token_address = fee_discount_token_account.address\n\n market_index = group.find_spot_market_index(spot_market.address)\n\n return SpotMarketInstructionBuilder(context, wallet, group, account, spot_market, raw_market, market_index, fee_discount_token_address)\n\n def build_cancel_order_instructions(self, order: Order, ok_if_missing: bool = False) -> CombinableInstructions:\n if self.open_orders_address is None:\n return CombinableInstructions.empty()\n\n return build_cancel_spot_order_instructions(\n self.context, self.wallet, self.group, self.account, self.raw_market, order, self.open_orders_address)\n\n def build_place_order_instructions(self, order: Order) -> CombinableInstructions:\n return build_spot_place_order_instructions(self.context, self.wallet, self.group, self.account,\n self.raw_market, order.order_type, order.side, order.price,\n order.quantity, order.client_id,\n self.fee_discount_token_address)\n\n def build_settle_instructions(self) -> CombinableInstructions:\n if self.open_orders_address is None:\n return CombinableInstructions.empty()\n\n base_rootbank = self.group.find_token_info_by_token(self.spot_market.base).root_bank\n base_nodebank = base_rootbank.pick_node_bank(self.context)\n quote_rootbank = self.group.find_token_info_by_token(self.spot_market.quote).root_bank\n quote_nodebank = quote_rootbank.pick_node_bank(self.context)\n return build_spot_settle_instructions(self.context, self.wallet, self.account,\n self.raw_market, self.group, self.open_orders_address,\n base_rootbank, base_nodebank, quote_rootbank, quote_nodebank)\n\n def build_crank_instructions(self, open_orders_addresses: typing.Sequence[PublicKey], limit: Decimal = Decimal(32)) -> CombinableInstructions:\n if self.open_orders_address is None:\n return CombinableInstructions.empty()\n\n open_orders_to_crank: typing.Sequence[PublicKey] = [*open_orders_addresses, self.open_orders_address]\n distinct_open_orders_addresses: typing.List[PublicKey] = []\n for oo in open_orders_to_crank:\n if oo not in distinct_open_orders_addresses:\n distinct_open_orders_addresses += [oo]\n\n limited_open_orders_addresses = distinct_open_orders_addresses[0:min(\n int(limit), len(distinct_open_orders_addresses))]\n\n limited_open_orders_addresses.sort(key=encode_public_key_for_sorting)\n\n return build_serum_consume_events_instructions(self.context, self.spot_market.address, self.raw_market.state.event_queue(), limited_open_orders_addresses, int(limit))\n\n def build_redeem_instructions(self) -> CombinableInstructions:\n return CombinableInstructions.empty()\n\n def build_create_openorders_instructions(self) -> CombinableInstructions:\n return build_spot_openorders_instructions(self.context, self.wallet, self.group, self.account, self.raw_market)\n\n def __str__(self) -> str:\n return f\"« 𝚂𝚙𝚘𝚝𝙼𝚊𝚛𝚔𝚎𝚝𝙸𝚗𝚜𝚝𝚛𝚞𝚌𝚝𝚒𝚘𝚗𝙱𝚞𝚒𝚕𝚍𝚎𝚛 [{self.spot_market.symbol}] »\"\n","sub_path":"mango/spotmarketinstructionbuilder.py","file_name":"spotmarketinstructionbuilder.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"19928885","text":"import asyncio\nfrom typing import List, Callable, Awaitable, Union\n\nimport discord\nfrom discord import Message, Embed, Emoji\nfrom discord.ext.commands import Context\n\nAnyEmoji = Union[str, Emoji]\n\n\nasync def run_tabbed_message(ctx: Context, emojis: List[AnyEmoji], embeds: List[Embed], files=None, starting_index=0,\n timeout=600):\n if len(emojis) != len(embeds):\n raise ValueError('Emojis and embeds must have the same number of elements.')\n\n message = await ctx.send(files=files, embed=embeds[starting_index])\n\n async def callback(emoji):\n await message.edit(embed=embeds[emojis.index(emoji)])\n\n await run_reaction_message(ctx, message, emojis, callback, timeout)\n\n\nasync def run_dynamically_paged_message(ctx: Context, embed_generator: Callable[[int], discord.Embed], timeout=600):\n left_arrow = '◀'\n right_arrow = '▶'\n arrows = [left_arrow, right_arrow]\n\n message = await ctx.send(embed=embed_generator(0))\n\n async def callback(emoji):\n if emoji == left_arrow:\n new_embed = embed_generator(-1)\n elif emoji == right_arrow:\n new_embed = embed_generator(1)\n else:\n return\n\n if new_embed:\n await message.edit(embed=new_embed)\n\n await run_reaction_message(ctx, message, arrows, callback, timeout)\n\n\nasync def run_paged_message(ctx: Context, base_embed: discord.Embed, content: List[str], page_size: int = 15,\n header='', numbered: bool = True, timeout=600, max_tabbed_pages=4, files=None):\n if header:\n header = f'`{header}`\\n'\n\n if max_tabbed_pages > 9:\n raise ValueError('max_tabbed_pages must be 9 or less.')\n\n if not content:\n embed = base_embed.copy().set_footer(text='Page 0/0')\n message = await ctx.send(embed=embed)\n await run_deletable_message(ctx, message, timeout)\n return\n\n page_contents = [content[i:i + page_size] for i in range(0, len(content), page_size)]\n\n item_number = 0\n max_item_number_length = len(str(len(content)))\n\n def format_item(item):\n nonlocal item_number\n item_number += 1\n if numbered:\n return f'`{item_number}.{\" \" * (max_item_number_length - len(str(item_number)))} {item}`'\n else:\n return f'`{item}`'\n\n embeds = [\n base_embed.from_dict({\n **base_embed.to_dict(),\n 'description': header + '\\n'.join((format_item(i) for i in page)),\n }).set_footer(text=f'Page {i + 1}/{len(page_contents)}')\n for i, page in enumerate(page_contents)]\n\n if len(embeds) == 1:\n message = await ctx.send(embed=embeds[0])\n await run_deletable_message(ctx, message, timeout)\n return\n\n if len(embeds) <= max_tabbed_pages:\n reaction_emoji = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣']\n await run_tabbed_message(ctx, reaction_emoji[:len(embeds)], embeds, timeout=timeout)\n else:\n message = await ctx.send(embed=embeds[0], files=files or [])\n\n double_left_arrow = '⏪'\n double_right_arrow = '⏩'\n left_arrow = '◀'\n right_arrow = '▶'\n\n arrows = [double_left_arrow, left_arrow, right_arrow, double_right_arrow]\n\n index = 0\n\n async def callback(emoji):\n nonlocal index\n start_index = index\n if emoji == double_left_arrow:\n index = 0\n elif emoji == left_arrow:\n index -= 1\n elif emoji == right_arrow:\n index += 1\n elif emoji == double_right_arrow:\n index = len(embeds) - 1\n index = min(len(embeds) - 1, max(0, index))\n\n if index != start_index:\n await message.edit(embed=embeds[index])\n\n await run_reaction_message(ctx, message, arrows, callback, timeout)\n\n\nasync def run_deletable_message(ctx: Context, message: Message, timeout=600):\n await run_reaction_message(ctx, message, [], _noop, timeout=timeout)\n\n\nasync def _noop(n):\n return None\n\n\nasync def run_reaction_message(ctx: Context, message: Message, emojis: List[AnyEmoji],\n callback: Callable[[AnyEmoji], Awaitable[None]], timeout=600):\n emojis.append('❎')\n for emoji in emojis:\n await message.add_reaction(emoji)\n\n def check(rxn, usr):\n return usr == ctx.author and rxn.emoji in emojis and rxn.message.id == message.id\n\n while True:\n try:\n reaction, user = await ctx.bot.wait_for('reaction_add', timeout=timeout, check=check)\n if reaction.emoji == '❎':\n await message.delete()\n return\n await callback(reaction.emoji)\n await message.remove_reaction(reaction, user)\n except asyncio.TimeoutError:\n for emoji in emojis:\n await message.remove_reaction(emoji, ctx.bot.user)\n break\n","sub_path":"miyu_bot/commands/common/reaction_message.py","file_name":"reaction_message.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"212752232","text":"import json\nimport pika\n\nfrom send_email import enviar_email\n\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters('localhost')\n)\n\nchannel = connection.channel()\n\nchannel.queue_declare(queue=\"send_email\")\n\n\ndef email(ch, method, properties, body):\n data = json.loads(str(body)[2:-1])\n enviar_email(data['subject'], data['to'], data['from_email'], data['body'])\n\n\nchannel.basic_consume(email, queue='send_email', no_ack=True)\n\nprint(\"Inicio worker\")\n\nchannel.start_consuming()","sub_path":"rabbit_email/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325604149","text":"\"\"\"\nCommands for publishing particle cloud and pose estimate updates.\n\"\"\"\n\n# pyright: reportMissingTypeStubs=false\n\nfrom typing import Any, List\n\nfrom geometry_msgs.msg import PoseArray, PoseStamped\nimport rospy\nfrom rospy_util.controller import Cmd\nfrom std_msgs.msg import Header\n\nfrom lib.particle import Particle\nimport lib.turtle_pose as tp\nfrom lib.turtle_pose import TurtlePose\n\n\ndef update_estimated_robot_pose(pose: TurtlePose, frame_id: str) -> Cmd[PoseStamped]:\n \"\"\"\n Update the estimated robot pose.\n \"\"\"\n header = mk_header(frame_id)\n pose_stamped = PoseStamped(header, tp.to_pose(pose))\n\n return Cmd(\n topic_name=\"/estimated_robot_pose\",\n message_type=PoseStamped,\n message_value=pose_stamped,\n )\n\n\ndef update_particle_cloud(particles: List[Particle], frame_id: str) -> Cmd[PoseArray]:\n \"\"\"\n Update the particle cloud after each iteration of the particle filter.\n \"\"\"\n return publish_particle_cloud(particles, frame_id, latch=False)\n\n\ndef init_particle_cloud(particles: List[Particle], frame_id: str) -> Cmd[PoseArray]:\n \"\"\"\n Publish the the particle cloud after initialization.\n \"\"\"\n return publish_particle_cloud(particles, frame_id, latch=True)\n\n\ndef publish_particle_cloud(\n particles: List[Particle],\n frame_id: str,\n latch: bool,\n) -> Cmd[PoseArray]:\n \"\"\"\n Publish the particle cloud, optionally latching to ensure the message is\n received by new subscribers.\n \"\"\"\n pose_array = pose_array_from_particles(particles, frame_id)\n\n return Cmd(\n topic_name=\"/particle_cloud\",\n message_type=PoseArray,\n message_value=pose_array,\n latch_publisher=latch,\n )\n\n\n\"\"\"\nThe no-op command (an empty list of commands).\n\"\"\"\nnone: List[Cmd[Any]] = []\n\n\ndef pose_array_from_particles(particles: List[Particle], frame_id: str) -> PoseArray:\n \"\"\"\n Create a PoseArray message from the particle cloud.\n \"\"\"\n header = mk_header(frame_id)\n poses = [tp.to_pose(p.pose) for p in particles]\n return PoseArray(header, poses)\n\n\ndef mk_header(frame_id: str) -> Header:\n \"\"\"\n Create a ROS message header for the current time and specified frame.\n \"\"\"\n return Header(stamp=rospy.Time.now(), frame_id=frame_id)\n","sub_path":"scripts/lib/controller/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"276926122","text":"# -*- coding: utf-8 -*-\nfrom plone import api\nfrom plone.app.upgrade.utils import loadMigrationProfile\nfrom Products.CMFCore.utils import getToolByName\nfrom zope.container.interfaces import INameChooser\nfrom zope.component import getUtility\nfrom zope.component import getMultiAdapter\n\nfrom plone.portlets.interfaces import IPortletManager\nfrom plone.portlets.interfaces import IPortletAssignmentMapping\n\nfrom emc.project.content.projectfolder import IProjectFolder\nfrom emc.policy.portlets import navigation\n\ndef setupGroups(context):\n\n# import pdb\n# pdb.set_trace()\n group = api.group.create(\n groupname='System Administrators',\n title='System Administrators',\n description='EMC System Administrators',\n roles=['SysAdmin','Site Administrator', ],\n ) \n group = api.group.create(\n groupname='Secure Staffs',\n title='Secure Staffs',\n description='EMC Secure Staffs',\n roles=['SecStaff','Site Administrator', ],\n ) \n group = api.group.create(\n groupname='Secure Auditors',\n title='Secure Auditors',\n description='EMC Secure Auditors',\n roles=['SecAuditor','Site Administrator', ],\n )\n# for i in range(1,3): \n# api.user.create(\n# username='master%s' % i,\n# email='master%s@plone.org' % i,\n# password='secret$',\n# ) \n api.group.add_user(groupname='System Administrators', username='test17')\n api.group.add_user(groupname='Secure Staffs', username='test18')\n api.group.add_user(groupname='Secure Auditors', username='test19')\n\ndef add_navigator_portlet(context):\n pc = getToolByName(context, \"portal_catalog\")\n query = {\"object_provides\":IProjectFolder.__identifier__}\n bns = pc(query)\n if len(bns) == 0: return\n obj = bns[0].getObject()\n# column = getUtility(IPortletManager, name=u\"plone.leftcolumn\")\n column = getUtility(IPortletManager, name=u\"plone.rightcolumn\")\n \n # We multi-adapt the object and the column to an assignment mapping,\n # which acts like a dict where we can put portlet assignments\n manager = getMultiAdapter((obj, column,), IPortletAssignmentMapping)\n \n # We then create the assignment and put it in the assignment manager,\n # using the default name-chooser to pick a suitable name for us.\n assignment = navigation.Assignment(name=u\"项目管理\",root_uid=obj.UID(),topLevel=0)\n chooser = INameChooser(manager)\n manager[chooser.chooseName(None, assignment)] = assignment\n\ndef add_member_navigator_portlet(context):\n pc = getToolByName(context, \"portal_catalog\")\n query = {\"object_provides\":IProjectFolder.__identifier__,\"id\":\"Members\"}\n bns = pc(query)\n if len(bns) == 0: return\n obj = bns[0].getObject()\n # column = getUtility(IPortletManager, name=u\"plone.leftcolumn\")\n column = getUtility(IPortletManager, name=u\"plone.rightcolumn\")\n # We multi-adapt the object and the column to an assignment mapping,\n # which acts like a dict where we can put portlet assignments\n manager = getMultiAdapter((obj, column,), IPortletAssignmentMapping)\n \n # We then create the assignment and put it in the assignment manager,\n # using the default name-chooser to pick a suitable name for us.\n assignment = navigation.Assignment(name=u\"工作空间\",root_uid=obj.UID(),topLevel=0)\n chooser = INameChooser(manager)\n manager[chooser.chooseName(None, assignment)] = assignment\n\n# loadMigrationProfile(context, 'profile-emc.policy:to507')\n \n \n\n\n","sub_path":"emc/policy/migration.py","file_name":"migration.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"92494329","text":"#!/usr/bin/env python\n#\n# copyoverlay.py - Action which copies the currently selected overlay.\n#\n# Author: Paul McCarthy <pauldmccarthy@gmail.com>\n#\n\"\"\"This module provides the :class:`CopyOverlayAction`, a global action\nwhich creates a copy of the currently selected overlay.\n\"\"\"\n\n\nimport numpy as np\n\nimport fsl.data.image as fslimage\nimport fsl.utils.transform as transform\nimport fsl.utils.settings as fslsettings\nimport fsleyes_widgets.dialog as fsldlg\nimport fsleyes.strings as strings\nfrom . import base\n\n\nclass CopyOverlayAction(base.Action):\n \"\"\"The ``CopyOverlayAction`` does as its name suggests - it creates a\n copy of the currently selected overlay.\n\n\n .. note:: Currently this action is only capable of copying ``.Image``\n overlays.\n\n\n The user is asked to choose between the following options:\n\n - If the overlay is a 4D ``Image``, should we copy the entire 4D image,\n or extract the current 3D volume?\n\n - Should we copy all of the ``Image`` data, or create a blank\n (i.e. filled with zeros) ``Image`` of the same dimensions?\n\n - Should we copy the ``Image`` display properties\n (e.g. :attr:`.Display.overlayType`), or set the display properties\n of the copy to defaults?\n \"\"\"\n\n\n def __init__(self, overlayList, displayCtx, frame):\n \"\"\"Create a ``CopyOverlayAction``.\n\n :arg overlayList: The :class:`.OverlayList`.\n :arg displayCtx: The :class:`.DisplayContext`.\n :arg frame: The :class:`.FSLeyesFrame`.\n \"\"\"\n base.Action.__init__(self, self.__copyOverlay)\n\n self.__overlayList = overlayList\n self.__displayCtx = displayCtx\n self.__frame = frame\n self.__name = '{}_{}'.format(type(self).__name__, id(self))\n\n displayCtx .addListener('selectedOverlay',\n self.__name,\n self.__selectedOverlayChanged)\n overlayList.addListener('overlays',\n self.__name,\n self.__selectedOverlayChanged)\n\n self.__selectedOverlayChanged()\n\n\n def destroy(self):\n \"\"\"Removes listeners from the :class:`.DisplayContext` and\n :class:`.OverlayList`, and calls :meth:`.Action.destroy`.\n \"\"\"\n\n self.__displayCtx .removeListener('selectedOverlay', self.__name)\n self.__overlayList.removeListener('overlays', self.__name)\n base.Action.destroy(self)\n\n\n def __selectedOverlayChanged(self, *a):\n \"\"\"Called when the selected overlay, or overlay list, changes.\n\n Enables/disables this action depending on the nature of the selected\n overlay.\n \"\"\"\n\n ovl = self.__displayCtx.getSelectedOverlay()\n self.enabled = (ovl is not None) and isinstance(ovl, fslimage.Image)\n\n\n def __copyOverlay(self):\n \"\"\"Creates a copy of the currently selected overlay, and inserts it\n into the :class:`.OverlayList`.\n \"\"\"\n\n import wx\n\n overlay = self.__displayCtx.getSelectedOverlay()\n\n if overlay is None:\n return\n\n # TODO support for other overlay types\n if type(overlay) != fslimage.Image:\n raise RuntimeError('Currently, only {} instances can be '\n 'copied'.format(fslimage.Image.__name__))\n\n display = self.__displayCtx.getDisplay(overlay)\n\n # We ask the user questions three:\n # - Copy data, or create an empty (a.k.a. mask) image?\n # - Copy display settings?\n # - For 4D, copy 4D, or just the current 3D volume?\n #\n # Here we build a list of\n # questions and initial states.\n options = []\n states = []\n\n createMaskSetting = 'fsleyes.actions.copyoverlay.createMask'\n copyDisplaySetting = 'fsleyes.actions.copyoverlay.copyDisplay'\n copy4DSetting = 'fsleyes.actions.copyoverlay.copy4D'\n\n createMask = fslsettings.read(createMaskSetting, False)\n copyDisplay = fslsettings.read(copyDisplaySetting, False)\n copy4D = fslsettings.read(copy4DSetting, False)\n is4D = len(overlay.shape) > 3 and overlay.shape[3] > 1\n\n options.append(strings.messages['actions.copyoverlay.createMask'])\n states .append(createMask)\n\n options.append(strings.messages['actions.copyoverlay.copyDisplay'])\n states .append(copyDisplay)\n\n if is4D:\n options.append(strings.messages['actions.copyoverlay.copy4D'])\n states .append(copy4D)\n\n # Ask the user what they want to do\n dlg = fsldlg.CheckBoxMessageDialog(\n self.__frame,\n title=strings.actions[self],\n message='Copy {}'.format(display.name),\n cbMessages=options,\n cbStates=states,\n yesText='OK',\n cancelText='Cancel',\n focus='yes')\n\n if dlg.ShowModal() != wx.ID_YES:\n return\n\n createMask = dlg.CheckBoxState(0)\n copyDisplay = dlg.CheckBoxState(1)\n if is4D:\n copy4D = dlg.CheckBoxState(2)\n\n fslsettings.write(createMaskSetting, createMask)\n fslsettings.write(copyDisplaySetting, copyDisplay)\n if is4D:\n fslsettings.write(copy4DSetting, copy4D)\n\n copyImage(self.__overlayList,\n self.__displayCtx,\n overlay,\n createMask=createMask,\n copy4D=copy4D,\n copyDisplay=copyDisplay)\n\n\ndef copyImage(overlayList,\n displayCtx,\n overlay,\n createMask=False,\n copy4D=True,\n copyDisplay=True,\n name=None,\n roi=None,\n data=None):\n \"\"\"Creates a copy of the given :class:`.Image` overlay, and inserts it\n into the :class:`.OverlayList`.\n\n :arg overlayList: The :class:`.OverlayList`.\n\n :arg displayCtx: The :class:`.DisplayContext`.\n\n :arg overlay: The :class:`.Image` to be copied.\n\n :arg createMask: If ``True``, the copy will be an empty ``Image`` the\n same shape as the ``overlay``.\n\n :arg copy4D: If ``True``, and the ``overlay`` is 4D, the copy will\n also be 4D. Otherwise, the current 3D voluem is copied.\n\n :arg copyDisplay: If ``True``, the copy will inherit the display settings\n of the ``overlay``. Otherwise, the copy will be\n initialised with default display settings.\n\n :arg name: If provided, will be used as the :attr:`.Display.name`\n of the copy. Otherwise the copy will be given a name.\n\n :arg roi: If provided, the copy will be cropped to the low/high\n voxel bounds specified in the image. Must be a sequence\n of tuples, containing the low/high bounds for each voxel\n dimension. For 4D images, the bounds for the fourth\n dimension are optional.\n\n :arg data: If provided, is used as the image data for the new copy.\n Must match the shape dictated by the other arguments\n (i.e. ``copy4D`` and ``roi``). If ``data`` is provided,\n the ``createMask`` argument is ignored.\n\n :returns: The newly created :class:`.Image` object.\n \"\"\"\n\n ovlIdx = overlayList.index(overlay)\n opts = displayCtx.getOpts(overlay)\n isROI = roi is not None\n is4D = len(overlay.shape) > 3 and overlay.shape[3] > 1\n\n if name is None:\n name = '{}_copy'.format(overlay.name)\n\n if roi is None:\n roi = [(0, s) for s in overlay.shape]\n\n # If the image is 4D, and an ROI of\n # length 3 has been given, add some\n # bounds for the fourth dimension\n if is4D and copy4D and len(roi) == 3:\n roi = list(roi) + [(0, overlay.shape[3])]\n\n # If we are only supposed to copy\n # the current 3D volume of a 4D\n # image, adjust the ROI accordingly.\n if is4D and not copy4D:\n roi = list(roi[:3]) + [(opts.volume, opts.volume + 1)]\n\n shape = [hi - lo for lo, hi in roi]\n slc = tuple([slice(lo, hi) for lo, hi in roi])\n\n if data is not None: pass\n elif createMask: data = np.zeros(shape)\n else: data = np.copy(overlay[slc])\n\n # If this is an ROI, we need to add\n # an offset to the image affine\n if isROI:\n xform = overlay.voxToWorldMat\n offset = [lo for lo, hi in roi[:3]]\n offset = transform.scaleOffsetXform([1, 1, 1], offset)\n xform = transform.concat(xform, offset)\n\n else:\n xform = None\n\n # Create the copy, put it in the list\n header = overlay.header.copy()\n copy = fslimage.Image(data, name=name, header=header, xform=xform)\n\n overlayList.insert(ovlIdx + 1, copy)\n\n # Copy the Display/DisplayOpts settings\n if copyDisplay:\n\n srcDisplay = displayCtx.getDisplay(overlay)\n destDisplay = displayCtx.getDisplay(copy)\n\n for prop in srcDisplay.getAllProperties()[0]:\n\n # Don't override the name\n # that we set above\n if prop == 'name':\n continue\n\n val = getattr(srcDisplay, prop)\n setattr(destDisplay, prop, val)\n\n # And after the Display has been configured\n # copy the DisplayOpts settings.\n srcOpts = displayCtx.getOpts(overlay)\n destOpts = displayCtx.getOpts(copy)\n\n for prop in srcOpts.getAllProperties()[0]:\n\n # But don't clobber the transform, and related,\n # properties, as it is (typically) automatically\n # controlled via the DisplayContext.displaySpace\n if prop in ('transform', 'bounds'):\n continue\n\n val = getattr(srcOpts, prop)\n setattr(destOpts, prop, val)\n\n return copy\n","sub_path":"fsleyes/actions/copyoverlay.py","file_name":"copyoverlay.py","file_ext":"py","file_size_in_byte":10000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"43519583","text":"'''\r\nGoogle Code Jam 2016\r\nRound 1C\r\nProblem A - Senate Evacuation\r\n'''\r\n\r\ncases = int(raw_input())\r\n\r\nfor case in range (cases):\r\n\tn = int(raw_input())\r\n\tp = raw_input().split(\" \")\r\n\talphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n\t# find total senate members\r\n\ttotal = 0\r\n\tfor i in range (n):\r\n\t\ttotal = total + int(p[i])\r\n\t\tp[i] = [int(p[i]), alphabet[i]]\r\n\tp.sort(reverse = True)\r\n\t\r\n\ty = \"\"\r\n\twhile total > 0:\r\n\t\tcount = 0\r\n\t\tfor i in range (n):\r\n\t\t\tif p[i][0] == p[0][0]:\r\n\t\t\t\tcount = count + 1\r\n\t\tif count == len(p) and len(p) > 2:\r\n\t\t\ty = y + p[0][1] + \" \"\r\n\t\t\tp[0][0] = p[0][0] - 1\r\n\t\t\ttotal = total - 1\r\n\t\t\tp.sort(reverse = True)\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\ty = y + p[0][1]\r\n\t\t\tp[0][0] = p[0][0] - 1\r\n\t\t\ttotal = total - 1\r\n\t\t\tif p[1][0] < total / 2:\r\n\t\t\t\ty = y + p[0][1] + \" \"\r\n\t\t\t\tp[0][0] = p[0][0] - 1\r\n\t\t\t\ttotal = total - 1\r\n\t\t\telse:\r\n\t\t\t\ty = y + p[1][1] + \" \"\r\n\t\t\t\tp[1][0] = p[1][0] - 1\r\n\t\t\t\ttotal = total - 1\r\n\t\t\tp.sort(reverse = True)\r\n\t\r\n\tprint (\"Case #{}: {}\".format(case + 1, y))","sub_path":"codes/CodeJamCrawler/16_3_1_neat/16_3_1_ronaudinho_A.py","file_name":"16_3_1_ronaudinho_A.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"430159334","text":"\n'''\nimport matplotlib.pyplot as plt\nfrom scipy.fftpack import fft\nfrom scipy.io import wavfile # get the api\nfs, data = wavfile.read('Amogh.wav') # load the data\n\ndata0 = data[:0]\nprint(data0)\n\na = data.T[0] # this is a two channel soundtrack, I get the first track\nb=[(ele/2**8.)*2-1 for ele in a] # this is 8-bit track, b is now normalized on [-1,1)\nc = fft(b) # calculate fourier transform (complex numbers list)\nd = len(c)/2 # you only need half of the fft list (real signal symmetry)\nplt.plot(abs(c[:(d-1)]),'r') \nplt.show()\n'''\nimport wave, struct\n\nwavefile = wave.open('Amogh.wav', 'r')\n\nlength = wavefile.getnframes()\nfor i in range(0, length):\n wavedata = wavefile.readframes(13)\n data = struct.unpack(\"<13h\", wavedata)\n print(int(data[0]))\n\n","sub_path":"Sonic Auth/Data Transfer/sssa.py","file_name":"sssa.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"301706741","text":"# myAgentP3.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n# This file was based on the starter code for student bots, and refined \n# by Mesut (Xiaocheng) Yang\n\n\nfrom captureAgents import CaptureAgent\nimport random, time, util\nfrom game import Directions\nimport game\nfrom util import nearestPoint\n\n#########\n# Agent #\n#########\nclass MyAgent(CaptureAgent):\n \"\"\"\n YOUR DESCRIPTION HERE\n \"\"\"\n\n def registerInitialState(self, gameState):\n \"\"\"\n This method handles the initial setup of the\n agent to populate useful fields (such as what team\n we're on).\n\n A distanceCalculator instance caches the maze distances\n between each pair of positions, so your agents can use:\n self.distancer.getDistance(p1, p2)\n\n IMPORTANT: This method may run for at most 15 seconds.\n \"\"\"\n\n # Make sure you do not delete the following line. \n # If you would like to use Manhattan distances instead \n # of maze distances in order to save on initialization \n # time, please take a look at:\n # CaptureAgent.registerInitialState in captureAgents.py.\n CaptureAgent.registerInitialState(self, gameState)\n self.start = gameState.getAgentPosition(self.index)\n\n def chooseAction(self, gameState):\n \"\"\"\n Picks among actions randomly.\n \"\"\"\n teammateActions = self.receivedBroadcast\n # Process your teammate's broadcast! \n # Use it to pick a better action for yourself\n\n actions = gameState.getLegalActions(self.index)\n\n filteredActions = actionsWithoutReverse(actionsWithoutStop(actions), gameState, self.index)\n\n currentAction = random.choice(actions) # Change this!\n return currentAction\n\ndef actionsWithoutStop(legalActions):\n \"\"\"\n Filters actions by removing the STOP action\n \"\"\"\n legalActions = list(legalActions)\n if Directions.STOP in legalActions:\n legalActions.remove(Directions.STOP)\n return legalActions\n\ndef actionsWithoutReverse(legalActions, gameState, agentIndex):\n \"\"\"\n Filters actions by removing REVERSE, i.e. the opposite action to the previous one\n \"\"\"\n legalActions = list(legalActions)\n reverse = Directions.REVERSE[gameState.getAgentState(agentIndex).configuration.direction]\n if len (legalActions) > 1 and reverse in legalActions:\n legalActions.remove(reverse)\n return legalActions\n","sub_path":"PacPack_Spring_2019/myAgent.py","file_name":"myAgent.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"60290397","text":"gbif_base_url = 'http://api.gbif.org/v1/species'\n\ndef gbif_name_backbone(name, rank = None, kingdom = None, phylum = None,\n clazz = None, order = None, family = None, genus = None, strict = False,\n start = None, limit = 500, **kwargs):\n\n url = gbif_base_url + '/match'\n args = {'name': name, 'rank': rank, 'kingdom': kingdom,\n 'phylum': phylum, 'class': clazz, 'order': order, 'family': family,\n 'genus': genus, 'strict': strict, 'verbose': True, 'offset': start,\n 'limit': limit}\n return Refactor(url, payload=args, request='get').json()\n\ndef gbif_name_lookup(query = None, rank = None, higherTaxonKey = None, status = None,\n nameType = None, datasetKey = 'd7dddbf4-2cf0-4f39-9b2a-bb099caae36c',\n limit = 500, start = None, **kwargs):\n\n url = gbif_base_url + '/search'\n args = {'q': query, 'rank': rank, 'higherTaxonKey': higherTaxonKey,\n 'status': status, 'nameType': nameType, 'datasetKey': datasetKey,\n 'limit': limit, 'offset': start}\n return Refactor(url, payload=args, request='get').json()\n","sub_path":"pytaxize/gbif_utils.py","file_name":"gbif_utils.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286994390","text":"import pytest\nimport SPL.driver.driver_factory as p_driver_factory\n\nfrom MobileApps.libs.flows.ios.smart.flow_container import FlowContainer\nfrom MobileApps.resources.const.ios.const import *\n\npytest.app_info = \"SMART\"\n\nclass Test_suite_01_ios_smart_scan_from_camera_ga(object):\n\n @pytest.fixture(scope=\"class\", autouse=\"true\")\n def class_setup(cls, session_setup, load_printers_session):\n\n cls = cls.__class__\n\n cls.driver = session_setup\n cls.fc = FlowContainer(cls.driver)\n\n # Initializing Printer\n cls.sys_config = ma_misc.load_system_config_file()\n cls.p = load_printers_session\n # cls.printer_ip = cls.p.p_obj.ipAddress\n cls.printer_info = cls.p.get_printer_information()\n\n # Printer variables\n cls.printer_ip = cls.printer_info['ip address']\n\n cls.fc.go_home(verify_ga=True)\n\n def test_01_scan_by_camera_max_ga(self):\n\n\n self.fc.add_printer_by_ip(printer_ip=self.printer_ip)\n self.fc.go_camera_screen_from_home()\n self.fc.fd[\"camera\"].capture_manual_photo_by_camera()\n self.fc.fd[\"preview\"].verify_preview_screen()\n self.fc.fd[\"scan_edit\"].select_scan_editing_for_rotate_and_crop(SCAN_EDIT_ROTATE.LEFT, SCAN_EDIT_CROP.A4)\n self.fc.fd[\"preview\"].verify_preview_screen()\n self.fc.fd[\"preview\"].handle_share_preview_screen()\n self.fc.fd[\"preview\"].select_file_converting_format(PREVIEW_FILE_TYPE.PDF)\n self.fc.fd[\"preview\"].select_save()\n # Clean up Steps\n self.fc.fd[\"scan\"].select_back()\n self.fc.fd[\"scan\"].verify_preview_navigate_back_popup()\n self.fc.fd[\"preview\"].select_yes_btn()\n\n def test_02_scan_by_camera_print_edit_max_ga(self):\n\n self.fc.go_camera_screen_from_home()\n self.fc.fd[\"camera\"].capture_manual_photo_by_camera()\n self.fc.fd[\"preview\"].verify_preview_screen()\n self.fc.fd[\"preview\"].select_add_page()\n self.fc.fd[\"camera\"].verify_camera_screen()\n self.fc.fd[\"camera\"].capture_manual_photo_by_camera()\n self.fc.fd[\"preview\"].verify_preview_screen()\n self.fc.fd[\"print_edit\"].select_print_edit_options_for_ga(re_size=PRINT_EDIT_RESIZE_AND_MOVE.MANUAL)","sub_path":"MobileApps/tests/ios/smart/ga/camera/test_suite_01_ios_smart_scan_from_camera_ga.py","file_name":"test_suite_01_ios_smart_scan_from_camera_ga.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"506234371","text":"from rest_framework import serializers\n\nfrom dataprocessing.serializers import userProfileSerializer\nfrom workprogramsapp.folders_ans_statistic.models import Folder, WorkProgramInFolder\nfrom workprogramsapp.serializers import WorkProgramShortForExperiseSerializer\n\n\nclass WorkProgramInFolderSerializer(serializers.ModelSerializer):\n class Meta:\n model = WorkProgramInFolder\n fields = \"__all__\"\n\n def to_representation(self, value):\n self.fields['work_program'] = WorkProgramShortForExperiseSerializer(many=False)\n return super().to_representation(value)\n\n\nclass FolderCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = Folder\n fields = [\"id\", \"name\", \"description\"]\n\n\nclass FolderSerializer(serializers.ModelSerializer):\n class Meta:\n model = Folder\n fields = [\"id\", \"name\", \"description\", \"owner\", 'work_program_in_folder']\n\n def update(self, instance, validated_data):\n print(validated_data)\n # ... logic to save ingredients for this recipe instance\n return instance\n\n def to_representation(self, value):\n self.fields['owner'] = userProfileSerializer(many=False)\n #self.fields['work_program'] = WorkProgramShortForExperiseSerializer(many=True)\n self.fields['work_program_in_folder'] = WorkProgramInFolderSerializer(many=True)\n return super().to_representation(value)\n","sub_path":"application/workprogramsapp/folders_ans_statistic/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"200964797","text":"import bpy\r\nn='dp'\r\ndef a(ob):\r\n s=bpy.context.scene\r\n bpy.ops.object.select_all(action='DESELECT')\r\n ob.select=True\r\n s.objects.active=ob\r\n \r\nobs=bpy.context.selected_objects\r\ns=bpy.context.scene\r\n\r\nfor ob in obs:\r\n s.cursor_location=ob.matrix_world.translation\r\n a(ob)\r\n d=max(ob.dimensions.x,ob.dimensions.y,ob.dimensions.z)\r\n #bpy.ops.object.editmode_toggle()\r\n #bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=3, size=d/2, view_align=False, enter_editmode=False)\r\n #bpy.ops.mesh.select_all(action='INVERT')\r\n #bpy.ops.mesh.delete(type='VERT')\r\n\r\n #bpy.ops.object.editmode_toggle()\r\n #\r\n #bpy.ops.object.shade_smooth()\r\n bpy.ops.object.metaball_add(type='BALL', view_align=False, enter_editmode=False)\r\n bpy.context.object.name = n\r\n \r\n m=bpy.context.active_object\r\n m.scale*=ob.dimensions.z*.6\r\n m.data.resolution=0.2\r\nbpy.ops.object.editmode_toggle()\r\nbpy.ops.object.editmode_toggle()\r\n\r\n","sub_path":"presets/macros/metabolize.py","file_name":"metabolize.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"1814144","text":"from django.db import models\nfrom django.utils import timezone\n\nclass Tweeeet(models.Model):\n author = models.ForeignKey('auth.User', on_delete=models.CASCADE)\n text = models.CharField(max_length=280)\n tweeeted_date = models.DateTimeField(\n default = timezone.now)\n\n def tweeet(self):\n self.tweeeted_date = timezone.now()\n self.save()\n\n","sub_path":"twiitter/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"334242436","text":"import webapp2\nfrom models import *\nfrom google.appengine.api import users\nimport main\n\n\nclass LoginScreenHandler(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n\n if user:\n user_profile = Profile.query(Profile.user_key == user.user_id()).get()\n if user_profile is not None:\n self.redirect(\"/\")\n\n template_values = {'profile': None}\n template = main.jinja.get_template('pages/profile/login.html')\n self.response.write(template.render(template_values))","sub_path":"pages/profile/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102544923","text":"__author__ = 'Keith Colbert'\n\n# A simple game to demonstrate use of sourceprotector to detect cheating\n\n\nimport time\nimport examplesourceprotector\n\n\nname = input('Enter your name: ')\n\nstart = time.time()\n\ninput('Quick, press enter!')\n\nend = time.time()\n\nelapsed = end - start\n\nscore = int(100 / elapsed)\n\nexamplesourceprotector.savescore(score)","sub_path":"Examples/highscores/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302572734","text":"\n\nfrom collections import defaultdict, deque\nimport csv\n\n\n\n\ndef load_data(file_path):\n\tgraph, hero_to_id, id_to_hero = defaultdict(set), {}, {}\n\n\tdef get_or_set_id(key):\n\t\tif key not in hero_to_id:\n\t\t\tid = get_or_set_id._max_id = get_or_set_id._max_id +1\n\t\t\thero_to_id[key], id_to_hero[id] = id, key\n\t\treturn hero_to_id[key]\n\n\tget_or_set_id._max_id = 0\n\n\tcsv_reader = csv.reader(open(file_path, 'rb'), delimiter='\\t')\n\tfor hero, comic in csv_reader:\n\t\thero_id = get_or_set_id(hero)\n\t\tgraph[hero_id].add(comic)\n\t\tgraph[comic].add(hero_id)\n\n\treturn (graph, id_to_hero, hero_to_id)\n\n\ndef update_edge(graph, one, two):\n\tgraph[one][two] = graph[one].get(two, 0) + 1\n\tgraph[two][one] = graph[two].get(one, 0) + 1\n\n\ndef build_edges(graph, id_to_hero):\n\tresult = defaultdict(dict)\n\n\tfor hero in id_to_hero:\n\t\tfor comic in graph[hero]:\n\t\t\tfor other_hero in graph[comic]:\n\t\t\t\tif other_hero < hero:\n\t\t\t\t\tupdate_edge(result, hero, other_hero)\n\n\tfor one in result:\n\t\tfor two in result[one]:\n\t\t\tresult[one][two] = 1.0 / result[one][two]\n\treturn result\n\n\n\ndef find_hop_path(graph, start, goal):\n\tfrontier, explored = deque([[start]]), set()\n\n\twhile frontier:\n\t\tcurrent_path = frontier.popleft()\n\t\tlast_node = current_path[-1]\n\t\texplored.add(last_node)\n\n\t\tfor successor in graph[last_node]:\n\t\t\tif successor not in explored:\n\t\t\t\tif successor == goal: return current_path + [successor]\n\t\t\t\tfrontier.append(current_path + [successor])\n\n\n\ndef find_weighted_path(graph, start, goal):\n\treturn []\n\n\n\n\ndef main():\n\tfile_path = 'marvel.tsv'\n\tgraph, id_to_hero, hero_to_id = load_data(file_path)\n\tgraph = build_edges(graph, id_to_hero)\n\n\tmain_heroes = ('SPIDER-MAN/PETER PAR',) #, 'GREEN GOBLIN/NORMAN ', 'WOLVERINE/LOGAN ', 'PROFESSOR X/CHARLES ', 'CAPTAIN AMERICA')\n\n\tresult = 0\n\n\tfor hero_name in main_heroes:\n\t\thero = hero_to_id[hero_name]\n\t\tfor other_hero in id_to_hero:\n\t\t\tif other_hero == hero: continue\n\n\t\t\thop_path = find_hop_path(graph, hero, other_hero)\n\t\t\tweighted_path = find_weighted_path(graph, hero, other_hero)\n\t\t\tif hop_path != weighted_path: result += 1\n\t\t\tprint('{}, {}: {}'.format(hero, other_hero, hop_path))\n\n\tprint(result)\n\n\n\n# def main():\n# \tfile_path = 'marvel.tsv'\n# \tgraph, id_to_hero = load_data(file_path)\n# \tedges = build_edges(graph, id_to_hero)\n# \tresult = map_hero_names(get_top_k_edges(edges, 4), id_to_hero)\n# \tprint(result)\n\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"Week5/Assignments/weighted_marvel__2.py","file_name":"weighted_marvel__2.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"137945108","text":"# Import the framework\nimport flask_api\nfrom flask import request\nfrom flask_api import status, exceptions\nimport pugsql\n\n# Import the dotenv to load variables from the environment\n# to run Flask using Foreman\nfrom dotenv import load_dotenv\nload_dotenv()\n\n# Create instance of Flask using the Flask API\napp = flask_api.FlaskAPI(__name__)\napp.config.from_envvar('APP_CONFIG')\n\nqueries = pugsql.module('queries/')\nqueries.connect(app.config['DATABASE_URL'])\n\n@app.cli.command('init')\ndef init_db():\n with app.app_context():\n db = queries._engine.raw_connection()\n with app.open_resource('entries.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n# Home page\n@app.route('/', methods=['GET'])\ndef home():\n #return 'Welcome to Nic\\'s localhost'\n return '''<h1>Welcome to Fake Reddit!</h1>'''\n\n# ---- Posting Microservice ----\n\n# List all entries\n@app.route('/api/v1/entries/all', methods=['GET'])\ndef all_entries():\n all_entries = queries.all_entries()\n return list(all_entries)\n\n# GET/DELETE given an id (also shows upvotes and downvotes)\n@app.route('/api/v1/entries/<int:id>', methods=['GET','DELETE'])\ndef entry(id):\n if request.method == 'GET':\n return get_entry_with_id(id)\n elif request.method == 'DELETE':\n queries.delete_entry(id=id)\n return { 'message': f'Deleted post with id {id}' }, status.HTTP_200_OK\n\n# General GET/POST\n@app.route('/api/v1/entries', methods=['GET','POST'])\ndef entries():\n if request.method == 'GET':\n return filter_entries(request.args)\n elif request.method == 'POST':\n return create_entry(request.data)\n\n# GET n most recent entries, specific community\n@app.route('/api/v1/entries/<string:community>/recent/<int:numOfEntries>', methods=['GET'])\ndef get_community_recent(community, numOfEntries):\n community_entries = queries.entry_by_community(community=community, numOfEntries=numOfEntries)\n myList = list(community_entries)\n return myList\n\n# GET n most recent entries, all communities\n@app.route('/api/v1/entries/all/recent/<int:numOfEntries>', methods=['GET'])\ndef get_all_recent(numOfEntries):\n all_entries = queries.all_entries_sorted(numOfEntries=numOfEntries)\n myList = list(all_entries)\n return myList\n\n# ---- Voting Microservice ----\n\n# GET n top-scoring entries, all communities\n@app.route('/api/v1/votes/top/<int:numOfEntries>', methods=['GET'])\ndef get_top_scoring(numOfEntries):\n top_entries = queries.entry_by_votes(numOfEntries=numOfEntries)\n myList = list(top_entries)\n return myList\n\n\n# Report an entry's number of upvotes/downvotes, upvote or downvote the entry\n@app.route('/api/v1/votes/<int:id>', methods=['GET', 'PUT', 'PATCH'])\ndef report_votes(id):\n if request.method == 'GET':\n report_votes = queries.report_votes(id=id)\n if report_votes:\n return report_votes\n else:\n return { 'message': f'Entry with id {id} does not exist' }, status.HTTP_404_NOT_FOUND\n\n # using PUT method to upvote entry\n elif request.method == 'PUT':\n up_vote_entry = queries.up_vote_entry(id=id)\n if up_vote_entry:\n return { 'message': f'Entry with id {id} has been upvoted' }, status.HTTP_200_OK\n else:\n return { 'message': f'Entry with id {id} can\\'t be upvoted' }, status.HTTP_400_BAD_REQUEST\n\n # using PATCH method to downvote entry\n elif request.method == 'PATCH':\n down_vote_entry = queries.down_vote_entry(id=id)\n if down_vote_entry:\n return { 'message': f'Entry with id {id} has been downvoted' }, status.HTTP_200_OK\n else:\n return { 'message': f'Entry with id {id} can\\'t be downvoted' }, status.HTTP_400_BAD_REQUEST\n\n# Given a list of post identifiers, return the list sorted by score\n@app.route('/api/v1/votes/scorelist', methods=['POST'])\ndef score_list():\n #entries_by_list = queries.entries_by_list(request.data)\n idList = request.json['id']\n entries_by_list = queries.entries_by_list(idList=idList)\n if entries_by_list:\n return list(entries_by_list)\n else:\n return { 'message': 'Posts could not be retrieved' }, status.HTTP_400_BAD_REQUEST\n\n# Create a new entry\ndef create_entry(entry):\n required_fields = ['id', 'title', 'bodyText', 'community', 'url', 'username', 'datePosted']\n\n if not all([field in entry for field in required_fields]):\n raise exceptions.ParseError()\n try:\n entry['id'] = queries.create_entry(**entry)\n except Exception as e:\n return { 'error': str(e) }, status.HTTP_409_CONFLICT\n\n return entry, status.HTTP_201_CREATED, {\n 'Location': f'/api/v1/entries/{entry[\"id\"]}'\n }\n\n# Filter entries given user input\ndef filter_entries(query_parameters):\n id = query_parameters.get('id')\n\n query = \"SELECT * FROM entries WHERE\"\n to_filter = []\n\n if id:\n query += ' id=? AND'\n to_filter.append(id)\n if not (id):\n raise exceptions.NotFound()\n\n query = query[:-4] + ';'\n\n results = queries._engine.execute(query, to_filter).fetchall()\n\n return list(map(dict, results))\n\n# Return entry given an id\ndef get_entry_with_id(id):\n entry = queries.entry_by_id(id=id)\n if entry:\n return entry\n else:\n raise exceptions.NotFound()\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"431908866","text":"from ctypes import cdll\nfrom ctypes import Structure\nfrom ctypes import c_int\nfrom ctypes import c_long\nfrom ctypes import c_double\nfrom ctypes import byref\nfrom ctypes import POINTER\nfrom datetime import datetime, timezone\nfrom SHDatetime_struct import Timeshift, SHDatetime, make_dt_copy\nimport sys\n\nlib = cdll.LoadLibrary('./libdt.so')\n\n\nclass MonthDay:\n month = 0\n day = 0\n\n def __init__(self,month,day):\n self.month = month\n self.day = day\n\ndef compareDTtoPyDt(dt,pdt):\n if dt.year != pdt.timetuple()[0]:\n return False\n if dt.month != pdt.timetuple()[1]:\n return False\n if dt.day != pdt.timetuple()[2]:\n return False\n if dt.hour != pdt.timetuple()[3]:\n return False\n if dt.minute != pdt.timetuple()[4]:\n return False\n if dt.second != pdt.timetuple()[5]:\n return False\n return True\n\ndef testCTimeExhaustive(lowBound,upBound):\n incr = 1 if upBound > lowBound else -1\n error = c_int(0)\n dt = SHDatetime()\n ans = c_double(-1)\n print(lowBound)\n for i in range(lowBound,upBound,incr):\n ts=c_double(i)\n lib.tryTimestampToDt(ts,0,byref(dt),byref(error))\n try:\n pts = datetime.fromtimestamp(i,tz=timezone.utc)\n if not compareDTtoPyDt(dt,pts):\n dateStr = \"year {} month:{} day:{}\".format(\n dt.year,dt.month,dt.day)\n print(\"{}___\".format(dateStr))\n return -1\n pdt = datetime(dt.year,dt.month,dt.day,dt.hour,dt.minute, dt.second\n ,tzinfo = timezone.utc)\n if error.value:\n print(\"\\ntimestamp to dt ended with error code {}\\n\".format(error.value))\n print(\"timestamp: {}\".format(ans.value))\n return -1\n lib.tryDtToTimestamp(byref(dt),byref(ans),byref(error))\n if ans.value != pdt.timestamp():\n print(\"\\nresult does not match python timestamp {}\\n\".format(ans.value))\n return -1\n if error.value:\n print(\"\\ndt to timestamp ended with error code {}\\n\".format(error.value))\n return -1\n \n\n if i % 86400 == 0:\n dateStr = \"year {} month:{} day:{}\".format(\n dt.year,dt.month,dt.day)\n print(\"{}___\".format(dateStr),end=\"\\r\",flush=True)\n if ans.value != i:\n print(\"\\nExpected value: {} actual value: {}\\n\".format(\n i,ans.value))\n return -1\n except:\n print(sys.exc_info()[1])\n print(\"i is: {}\".format(i))\n dateStr = \"year {} month:{} day:{}\".format(\n dt.year,dt.month,dt.day)\n print(\"{}___\".format(dateStr))\n return -1\n\n return 0\n\n\n\nif __name__ == \"__main__\":\n lowBound = 0\n upBound = sys.maxsize\n if len(sys.argv) > 1:\n lowBound = int(sys.argv[1])\n if len(sys.argv) > 2:\n upBound = int(sys.argv[2])\n exitCode = testCTimeExhaustive(lowBound,upBound)\n if exitCode == 0:\n print(\"Process done successfully\")\n sys.exit(exitCode)\n","sub_path":"cl_dt_all.py","file_name":"cl_dt_all.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"155124079","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\nimport json\nimport logging\nfrom typing import Sequence\nfrom urllib.parse import urlparse\n\nfrom opentelemetry.metrics import Counter, Measure, Metric\nfrom opentelemetry.sdk.metrics.export import (\n MetricRecord,\n MetricsExporter,\n MetricsExportResult,\n)\nfrom opentelemetry.sdk.util import ns_to_iso_str\n\nfrom azure_monitor import protocol, utils\nfrom azure_monitor.exporter import BaseExporter\n\nlogger = logging.getLogger(__name__)\n\n\nclass AzureMonitorMetricsExporter(BaseExporter, MetricsExporter):\n def __init__(self, **options):\n super(AzureMonitorMetricsExporter, self).__init__(**options)\n\n def export(\n self, metric_records: Sequence[MetricRecord]\n ) -> MetricsExportResult:\n envelopes = map(self.metric_to_envelope, metric_records)\n envelopes_to_export = map(\n lambda x: x.to_dict(),\n tuple(self.apply_telemetry_processors(envelopes)),\n )\n try:\n result = self._transmit(envelopes_to_export)\n if result == MetricsExportResult.FAILED_RETRYABLE:\n self.storage.put(envelopes, result)\n if result == utils.ExportResult.SUCCESS:\n # Try to send any cached events\n self._transmit_from_storage()\n return utils.get_metrics_export_result(result)\n except Exception:\n logger.exception(\"Exception occurred while exporting the data.\")\n\n def metric_to_envelope(\n self, metric_record: MetricRecord\n ) -> protocol.Envelope:\n\n if not metric_record:\n return None\n envelope = protocol.Envelope(\n ikey=self.options.instrumentation_key,\n tags=dict(utils.azure_monitor_context),\n time=ns_to_iso_str(\n metric_record.metric.get_handle(\n metric_record.label_set\n ).last_update_timestamp\n ),\n )\n envelope.name = \"Microsoft.ApplicationInsights.Metric\"\n\n data_point = protocol.DataPoint(\n ns=metric_record.metric.name,\n name=metric_record.metric.description,\n value=metric_record.aggregator.checkpoint,\n kind=protocol.DataPointType.MEASUREMENT,\n )\n\n properties = {}\n for label_tuple in metric_record.label_set.labels:\n properties[label_tuple[0]] = label_tuple[1]\n\n data = protocol.MetricData(metrics=[data_point], properties=properties)\n envelope.data = protocol.Data(base_data=data, base_type=\"MetricData\")\n return envelope\n","sub_path":"azure_monitor/src/azure_monitor/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542110176","text":"import numpy as np\n\n\nclass LinearProgram:\n \"\"\"\n A class to store a linear program.\n\n Attributes\n ----------\n num_eq : int\n num_var : int\n A : matrix of size num_eq x num_var\n b : vector of size num_eq\n cost : np.array\n\n The LP is of the form A x = b, x >= 0.\n \"\"\"\n\n def __init__(self, A: np.array, b: np.array, cost: np.array):\n\n self.num_eq = len(A) # number of equations\n self.num_var = len(A[0]) # number of variables\n\n if len(cost) != self.num_var:\n print(\n \"Error: Number of rows of A does not match\\\n the number of rows of the cost function.\"\n )\n return\n if len(b) != self.num_eq:\n print(\"Error: Number of rows of A does not match the number of rows of b.\")\n return\n\n self.A = np.array(A)\n self.b = np.array(b)\n self.cost = np.array(cost)\n\n def print(self):\n \"Prints the system of equations.\"\n\n print(\"Minimize: \")\n for i in range(self.num_var):\n print(str(self.cost[i]) + \"*x_\" + str(i), end=\" + \")\n print(str(self.cost[self.num_var - 1]) + \"*x_\" + str(self.num_var - 1))\n\n print(\"Subject to constraints:\")\n for i in range(self.num_eq):\n for j in range(self.num_var - 1):\n print(str(self.A[i][j]) + \"*x_\" + str(j), end=\" + \")\n print(\n str(self.A[i][self.num_var - 1]) + \"*x_\" + str(self.num_var - 1),\n end=\" = \",\n )\n print(self.b[i])\n for i in range(self.num_var):\n print(\"x_\" + str(i) + \" >= 0\")\n\n\nclass SimplexMethod:\n \"\"\"\n A class for implementing Simplex Method.\n\n Attributes\n ----------\n lp: LinearProgram\n basis_columns:\n vertex\n B_inv\n\n \"\"\"\n\n def __init__(self, lp: LinearProgram, basis_columns: np.array):\n\n self.lp = lp\n self.basis_columns = np.array(basis_columns)\n self.update_inv_naive()\n self.calculate_vertex()\n\n def update_inv_naive(self):\n self.B_inv = np.linalg.inv(self.lp.A[:, self.basis_columns])\n\n def calculate_vertex(self):\n\n self.vertex = np.zeros(self.lp.num_var)\n\n # aux_vertex = B^{-1} * b\n aux_vertex = np.matmul(self.B_inv, self.lp.b)\n\n # put the values of `aux_vertex` into appropriate \"spots\".\n for i in range(self.lp.num_var):\n if i in self.basis_columns:\n self.vertex[i] = aux_vertex[(np.where(self.basis_columns == i))[0]]\n\n def cost(self):\n return np.dot(self.lp.cost, self.vertex)\n\n def reduced_cost_naive(self, index: int):\n \"Returns the reduced cost in the direction `j`: c'_j = c_j - c'_B * B^{-1} * A_j\"\n cB = self.lp.cost[self.basis_columns]\n reduced_cost = self.lp.cost[index] - np.matmul(\n cB, np.matmul(self.B_inv, self.lp.A[:, index])\n )\n return reduced_cost\n\n def step(self, i: int):\n\n # u = B^{-1} * A_i\n u = np.matmul(self.B_inv, self.lp.A[:, i])\n\n # values in `u` that are positive\n u_pos = u[u > 0]\n\n # If no-coordinates of `u` are positive,\n # then there is no vertex in this direction.\n if len(u_pos) == 0:\n return False\n\n # Basis vectors corresponding to the positive entries in `u`\n b_pos = self.basis_columns[u > 0]\n\n # Coordinates of `x` corresponding to the positive values of `u`\n x = self.vertex[b_pos]\n\n # normalize the positive coordinates and find the min values\n thetas = x / u_pos\n theta_argmin = np.argmin(thetas)\n theta_min = min(thetas)\n\n # Replace the i^th basis_column with the `theta_argmin` one\n self.basis_columns[theta_argmin] = i\n self.update_inv_naive()\n self.calculate_vertex()\n\n # Coordinates of the new vertex\n # self.vertex = [\n # self.vertex[i] - theta_min * u[i] for i in range(len(self.vertex))\n # ]\n # self.vertex[theta_argmin] = theta_min\n\n # new_vertex = np.zeros(self.lp.num_var)\n # for i in range(self.lp.num_eq):\n # new_vertex[self.basis_columns[i]] = (\n # self.vertex[self.basis_columns[i]] - theta_min * u[i]\n # )\n # new_vertex[self.basis_columns[theta_argmin]] = theta_min\n # self.vertex = new_vertex\n\n return True\n\n def solve(self, reduced_cost_calc=reduced_cost_naive):\n # Loop over the indices `i` which are not in one of the basis_columns.\n for i in range(self.lp.num_var):\n if not (i in self.basis_columns):\n\n # Calculate the reduced cost in the `i` direction.\n reduced_cost = self.reduced_cost_naive(i)\n\n # If the reduced cost is negative,\n # then move in the direction of `i` to the next vertex.\n if reduced_cost < 0:\n # in the direction of `i`\n # if search for the next direction is succesful,\n # restart the process from the new vertex\n # else the cost is -infinity\n if self.step(i):\n break\n return -1\n\n # If all reduced costs are non-negative\n # then `i` is the optimal solution\n return i\n\n self.solve()\n\n def print_solution(self):\n\n print(\"-\" * 20)\n self.lp.print()\n\n print(\"-\" * 20)\n print(\"Solution:\")\n for i in range(len(self.vertex)):\n print(\"x_\" + str(i) + \" = \" + str(round(self.vertex[i], 2)))\n print(\"Minimal cost = \", round(self.cost(), 2))\n return\n\n\nlp = LinearProgram(\n A=[[1, 2, 2, 1, 0, 0], [2, 1, 2, 0, 1, 0], [2, 2, 1, 0, 0, 1]],\n b=[20, 20, 20],\n cost=[-10, -12, -12, 0, 0, 0],\n)\n\nsimplex = SimplexMethod(lp, basis_columns=[3, 4, 5])\n\nsimplex.solve()\n\nsimplex.print_solution()\n","sub_path":"simplex.py","file_name":"simplex.py","file_ext":"py","file_size_in_byte":5950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"449064271","text":"# vim: ai ts=4 sts=4 et sw=4\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom django.db import models\n\nfrom filebrowser_safe.fields import FileBrowseFormField\n\nfrom clubhouse.core import widgets\n\nclass FileBrowseImageField(models.ImageField):\n def __init__(self,*args,**kwargs):\n self.extensions = kwargs.pop('extensions', '')\n super(FileBrowseImageField,self).__init__(*args,**kwargs)\n\n def formfield(self, **kwargs):\n attrs = {}\n attrs[\"directory\"] = self.upload_to\n attrs[\"extensions\"] = self.extensions\n attrs[\"format\"] = 'Image'\n defaults = {\n 'form_class': FileBrowseFormField,\n 'widget': widgets.FileBrowseImageWidget(attrs=attrs),\n 'directory': self.upload_to,\n 'extensions': self.extensions,\n 'format': 'Image'\n }\n defaults.update(kwargs)\n return super(FileBrowseImageField, self).formfield(**defaults)\n","sub_path":"clubhouse/core/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"617279207","text":"from enum import Enum\n\n\nclass HTTPMethod(Enum):\n \"\"\"Enum with http methods\"\"\"\n \n POST = 'POST'\n GET = 'GET'\n PUT = 'PUT'\n DELETE = 'DELETE'\n\n\nclass FileType(Enum):\n \"\"\"Enum with file sheet types\"\"\"\n\n EXCEL = 'EXCEL'\n CSV = 'CSV'\n\n\nclass HeaderOption(Enum):\n \"\"\"Enum with options to fine column headers\"\"\"\n\n DEFAULT = 'DEFAULT'\n FIND = 'FIND'\n EXACT = 'EXACT'\n\n\nclass TaskType(Enum):\n \"\"\"Enum with types of tasks\"\"\"\n\n IMPORT_CREATE = 'IMPORT_CREATE'\n IMPORT_EDIT = 'IMPORT_EDIT'\n BULK_EDIT = 'BULK_EDIT'\n\n\nclass ExecutionType(Enum):\n \"\"\"Enum with the types of job executions\"\"\"\n \n NOW = 'NOW'\n SCHEDULED = 'SCHEDULED'\n RECURRING = 'RECURRING'\n\n\nclass ProductStatus(Enum):\n \"\"\"Enum with product statuses\"\"\"\n\n ACTIVE = 'ACTIVE'\n DRAFT = 'DRAFT'\n ARCHIVED = 'ARCHIVED'\n\n\nclass JobStatus(Enum):\n SUBMITTED = 'SUBMITTED'\n PREPARING = 'PREPARING'\n RUNNING = 'RUNNING'\n COMPLETED = 'COMPLETED'\n PARTIAL_COMPLETE = 'PARTIALLY COMPLETED'\n FAILED = 'FAILED'","sub_path":"src/datamodel/custom_enums.py","file_name":"custom_enums.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"28404363","text":"################################################################################\n# The MIT License\n#\n# Copyright (c) 2019-2021, Prominence AI, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all 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\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n################################################################################\n\n#!/usr/bin/env python\n\nimport sys\nsys.path.insert(0, \"../../\")\nfrom dsl import *\n\nuri_file = \"../../test/streams/sample_1080p_h264.mp4\"\n\n# Filespecs for the Primary GIE and IOU Trcaker\nprimary_infer_config_file = '../../test/configs/config_infer_primary_nano.txt'\nprimary_model_engine_file = '../../test/models/Primary_Detector_Nano/resnet10.caffemodel_b8_gpu0_fp16.engine'\ntracker_config_file = '../../test/configs/iou_config.txt'\n\nPGIE_CLASS_ID_VEHICLE = 0\nPGIE_CLASS_ID_BICYCLE = 1\nPGIE_CLASS_ID_PERSON = 2\nPGIE_CLASS_ID_ROADSIGN = 3\n\nTILER_WIDTH = DSL_DEFAULT_STREAMMUX_WIDTH\nTILER_HEIGHT = DSL_DEFAULT_STREAMMUX_HEIGHT\nWINDOW_WIDTH = DSL_DEFAULT_STREAMMUX_WIDTH\nWINDOW_HEIGHT = DSL_DEFAULT_STREAMMUX_HEIGHT\n#WINDOW_WIDTH = 1280\n#WINDOW_HEIGHT = 720\n\n## \n# Function to be called on XWindow KeyRelease event\n## \ndef xwindow_key_event_handler(key_string, client_data):\n print('key released = ', key_string)\n if key_string.upper() == 'P':\n dsl_pipeline_pause('pipeline')\n elif key_string.upper() == 'R':\n dsl_pipeline_play('pipeline')\n elif key_string.upper() == 'Q' or key_string == '\u001B' or key_string == '\u0003':\n dsl_main_loop_quit()\n \n## \n# Function to be called on XWindow Delete event\n## \ndef xwindow_delete_event_handler(client_data):\n print('delete window event')\n dsl_main_loop_quit()\n\n## \n# Function to be called on End-of-Stream (EOS) event\n## \ndef eos_event_listener(client_data):\n print('Pipeline EOS event')\n dsl_main_loop_quit()\n\n## \n# Function to be called on every change of Pipeline state\n## \ndef state_change_listener(old_state, new_state, client_data):\n print('previous state = ', old_state, ', new state = ', new_state)\n if new_state == DSL_STATE_PLAYING:\n dsl_pipeline_dump_to_dot('pipeline', \"state-playing\")\n\n## \n# Function to create all required RGBA Color Types\n## \ndef create_colors():\n retval = dsl_display_type_rgba_color_new('opaque-red', red=1.0, green=0.0, blue=0.0, alpha = 0.2)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('opaque-yellow', red=1.0, green=1.0, blue=0.0, alpha = 0.1)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('full-grey', red=0.5, green=0.5, blue=0.5, alpha = 1.0)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('opaque-black', red=0.0, green=0.0, blue=0.0, alpha = 0.2)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('full-white', red=1.0, green=1.0, blue=1.0, alpha = 1.0)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('opaque-white', red=1.0, green=1.0, blue=1.0, alpha = 1.0)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('full-blue', red=0.0, green=0.0, blue=1.0, alpha = 1.0)\n\n return retval\n\n \n## \n# Function to create all required RGBA Display Types\n## \ndef create_fonts_text_and_shapes():\n\n ## Import Note: all coordinates and dimensions are relative to the Stream Muxer and Tiler Dimensions\n retval = dsl_display_type_rgba_font_new('arial-15-white', font='arial', size=15, color='full-white')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n retval = dsl_display_type_rgba_font_new('arial-20-blue', font='arial', size=20, color='full-blue')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n # New RGBA Rectangle to use as a background for summation display. Using the full black with alpha=1.0\n retval = dsl_display_type_rgba_rectangle_new('grey-rectangle', left=10, top=45, width=190, height=110, \n border_width=0, color='full-grey', has_bg_color=True, bg_color='full-grey')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n # A second RGBA Rectangle to use as a dropped shadow for summation display. Using the opaque black\n retval = dsl_display_type_rgba_rectangle_new('black-shadow', left=16, top=51, width=190, height=110, \n border_width=0, color='opaque-black', has_bg_color=True, bg_color='opaque-black')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n # A new RGBA Circle to be used as a custom arrow head.\n retval = dsl_display_type_rgba_circle_new('blue-circle', x_center=530, y_center=50, radius=5, \n color='full-blue', has_bg_color=True, bg_color='full-blue')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n retval = dsl_display_type_rgba_line_new('blue-line', x1=530, y1=50, x2=730, y2=50, width=2, color='full-blue')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_text_new('blue-text', 'Shared Trigger Area', x_offset=733, y_offset=30, \n font='arial-20-blue', has_bg_color=False, bg_color=None)\n\n # New RGBA Rectangle to use with an ODE Area as Trigger criteria, shared between Person and Vehicle Class Id's \n retval = dsl_display_type_rgba_rectangle_new('shared-rectangle', left=500, top=0, width=60, height=1089, \n border_width=0, color='opaque-yellow', has_bg_color=True, bg_color='opaque-yellow')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n # A second RGBA Rectangle use with a second ODE Area, used by the Person Class Id only\n return dsl_display_type_rgba_rectangle_new('person-rectangle', left=200, top=0, width=10, height=1089, \n border_width=0, color='opaque-yellow', has_bg_color=True, bg_color='opaque-yellow')\n \n## \n# \n## \ndef main(args):\n\n # Since we're not using args, we can Let DSL initialize GST on first call\n while True:\n\n # create all required RGBA colors\n retval = create_colors(); \n if retval != DSL_RETURN_SUCCESS:\n break\n \n # create all required RGBA fonts, text and shapes for adding display metadata\n retval = create_fonts_text_and_shapes(); \n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Create a new Action to add all display data to every frame\n retval = dsl_ode_action_display_meta_add_many_new('add-display-meta', display_types=\n ['grey-rectangle', 'black-shadow', 'blue-circle', 'blue-line', 'blue-text', None])\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Create an Always triger to overlay our Display Types on every frame - single source, so no filter\n retval = dsl_ode_trigger_always_new('always-trigger', source=None, when=DSL_ODE_PRE_OCCURRENCE_CHECK)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('always-trigger', action='add-display-meta')\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # Create two areas to be used as criteria for ODE Occurrence. The first area\n # will be for the Person class alone... and defines a vertical rectangle to \n # the left of the pedestrian sidewalk. The pixel values are relative to the\n # This area's background will be shaded yellow for caution\n retval = dsl_ode_area_inclusion_new('person-area', 'person-rectangle', display=True)\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # The second area will be shared by both Person and Vehicle classes... and defines\n # a vertical area/rectangle to the right of the sidewalk and left of the street\n # This area's background will be shaded yellow for caution\n retval = dsl_ode_area_inclusion_new('shared-area', 'shared-rectangle', display=True)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Create a new Fill Action that will fill the Object's rectangle with a shade of red to indicate that\n # overlap with one or more of the defined Area's has occurred, i.e. ODE occurrence. The action will be\n # used with both the Person and Car class Ids to indicate thay have entered the area of caution\n retval = dsl_ode_action_fill_object_new('red-fill-action', 'opaque-red')\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Create a new Capture Action to capture the full-frame to jpeg image, and save to file. \n # The action will be triggered on firt occurrence of a bicycle and will be save to the current dir.\n retval = dsl_ode_action_capture_frame_new('bicycle-capture', outdir=\"./\", annotate=True)\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # Create a new Action used to display all Object detection summations for each frame. Use the classId\n # to add an additional vertical offset so the one action can be shared accross classId's\n retval = dsl_ode_action_display_new('display-action', x_offset=24, y_offset=55, y_offset_with_classId=True,\n font='arial-15-white', has_bg_color=False, bg_color=None)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n \n # New Occurrence Trigger, filtering on the Person Class Id, with no limit on the number of occurrences\n # Add the two Areas as Occurrence (overlap) criteria and the action to Fill the background red on occurrence\n retval = dsl_ode_trigger_occurrence_new('person-area-overlap', source=None, class_id=PGIE_CLASS_ID_PERSON, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_area_add_many('person-area-overlap', areas=['person-area', 'shared-area', None])\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('person-area-overlap', action='red-fill-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # New Occurrence Trigger, filtering on the Vehicle ClassId, with no limit on the number of occurrences\n # Add the single Shared Area and the action to Fill the background red on occurrence \n retval = dsl_ode_trigger_occurrence_new('vehicle-area-overlap', source=None, class_id=PGIE_CLASS_ID_VEHICLE, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_area_add('vehicle-area-overlap', area='shared-area')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('vehicle-area-overlap', action='red-fill-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # New Occurrence Trigger, filtering on the Bicycle ClassId, with a limit of one occurrence\n # Add the capture-frame action to the first occurrence event\n retval = dsl_ode_trigger_occurrence_new('bicycle-first-occurrence', source=None, class_id=PGIE_CLASS_ID_BICYCLE, limit=1)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('bicycle-first-occurrence', action='bicycle-capture')\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # New ODE Triggers for Object summation - i.e. new ODE occurrence on detection summation.\n # Each Trigger will share the same ODE Display Action\n retval = dsl_ode_trigger_summation_new('Vehicles:', source=None, class_id=PGIE_CLASS_ID_VEHICLE, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('Vehicles:', action='display-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_summation_new('Bicycles:', source=None, class_id=PGIE_CLASS_ID_BICYCLE, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('Bicycles:', action='display-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_summation_new('Pedestrians:', source=None, class_id=PGIE_CLASS_ID_PERSON, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('Pedestrians:', action='display-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # A hide action to use with two occurrence Triggers, filtering on the Person Class Id and Vehicle Class Id\n # We will use an every occurrece Trigger to hide the Display Text and Rectangle Border for each object detected\n # We will leave the Bicycle Display Text and Border untouched\n retval = dsl_ode_action_hide_new('hide-action', text=True, border=True)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_occurrence_new('person-every-occurrence', source=None, class_id=PGIE_CLASS_ID_PERSON, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('person-every-occurrence', action='hide-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_occurrence_new('vehicle-every-occurrence', source=None, class_id=PGIE_CLASS_ID_VEHICLE, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('vehicle-every-occurrence', action='hide-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New ODE Pad Probe Handler to handle all ODE Triggers with their Areas and Actions \n retval = dsl_pph_ode_new('ode-hanlder')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_pph_ode_trigger_add_many('ode-hanlder', triggers=[\n 'vehicle-area-overlap',\n 'person-area-overlap', \n 'bicycle-first-occurrence',\n 'always-trigger',\n 'Vehicles:',\n 'Bicycles:',\n 'Pedestrians:',\n 'person-every-occurrence',\n 'vehicle-every-occurrence',\n None])\n if retval != DSL_RETURN_SUCCESS:\n break\n \n \n ############################################################################################\n #\n # Create the remaining Pipeline components\n \n # New URI File Source using the filespec defined above\n retval = dsl_source_uri_new('uri-source', uri_file, False, 0, 0, 0)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New Primary GIE using the filespecs above with interval = 0\n retval = dsl_gie_primary_new('primary-gie', primary_infer_config_file, primary_model_engine_file, 4)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New IOU Tracker, setting max width and height of input frame\n retval = dsl_tracker_iou_new('iou-tracker', tracker_config_file, 480, 272)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New Tiled Display, setting width and height, use default cols/rows set by source count\n retval = dsl_tiler_new('tiler', TILER_WIDTH, TILER_HEIGHT)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n retval = dsl_tiler_pph_add('tiler', handler='ode-hanlder', pad=DSL_PAD_SINK)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New OSD with clock and text enabled... using default values.\n retval = dsl_osd_new('on-screen-display', True, True)\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # New Window Sink, 0 x/y offsets and same dimensions as Tiled Display\n retval = dsl_sink_window_new('window-sink', 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Add all the components to our pipeline\n retval = dsl_pipeline_new_component_add_many('pipeline', \n ['uri-source', 'primary-gie', 'iou-tracker', 'tiler', 'on-screen-display', 'window-sink', None])\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Add the XWindow event handler functions defined above\n retval = dsl_pipeline_xwindow_key_event_handler_add(\"pipeline\", xwindow_key_event_handler, None)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_pipeline_xwindow_delete_event_handler_add(\"pipeline\", xwindow_delete_event_handler, None)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n ## Add the listener callback functions defined above\n retval = dsl_pipeline_state_change_listener_add('pipeline', state_change_listener, None)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_pipeline_eos_listener_add('pipeline', eos_event_listener, None)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Play the pipeline\n retval = dsl_pipeline_play('pipeline')\n if retval != DSL_RETURN_SUCCESS:\n break\n\n dsl_main_loop_run()\n retval = DSL_RETURN_SUCCESS\n break\n\n # Print out the final result\n print(dsl_return_value_to_string(retval))\n\n # Cleanup all DSL/GST resources\n dsl_delete_all()\n \nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","sub_path":"examples/python/ode_triggers_areas_actions_display_types.py","file_name":"ode_triggers_areas_actions_display_types.py","file_ext":"py","file_size_in_byte":18262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"108754124","text":"import os\n\nimport findspark\nimport pytest\n\n\nclass SparkHome(object):\n\n def __init__(self, pytest_config):\n self.config = pytest_config\n\n self._path, source_name = self._detect_path()\n if self._path:\n self._path = os.path.abspath(self._path)\n if not os.path.exists(self._path):\n raise OSError(\n \"SPARK_HOME path specified in %s does not exist: %s\"\n % (source_name, self._path))\n\n @property\n def path(self):\n return self._path\n\n @property\n def version(self):\n if self.path:\n return self._get_spark_version(self.path)\n\n def _get_spark_version(self, spark_home):\n release_info_filename = os.path.join(spark_home, 'RELEASE')\n if os.path.exists(release_info_filename):\n with open(release_info_filename) as release_info:\n return release_info.read()\n\n def _locations(self):\n yield (\n self.config.option.spark_home,\n 'config (command line option \"--spark_home\")',\n )\n yield (self.config.getini('spark_home'), 'config (pytest.ini)')\n yield (os.environ.get('SPARK_HOME'), 'ENV')\n\n def _detect_path(self):\n for path, description in self._locations():\n if path:\n return path, description\n return None, None\n\n\ndef pytest_addoption(parser):\n parser.addini('spark_home', 'Spark install directory (SPARK_HOME).')\n parser.addoption(\n '--spark_home',\n dest='spark_home',\n help='Spark install directory (SPARK_HOME).',\n )\n\n\ndef pytest_configure(config):\n spark_home = SparkHome(config).path\n\n if spark_home:\n findspark.init(spark_home)\n\n\ndef pytest_report_header(config, startdir):\n spark_ver = SparkHome(config).version\n if spark_ver:\n spark_ver = spark_ver.strip().replace('\\n', ' | ')\n return \"spark version -- \" + spark_ver\n\n\ndef reduce_logging(sc):\n \"\"\"Reduce logging in SparkContext instance.\"\"\"\n\n logger = sc._jvm.org.apache.log4j\n logger.LogManager.getLogger(\"org\").setLevel(logger.Level.OFF)\n logger.LogManager.getLogger(\"akka\").setLevel(logger.Level.OFF)\n\n\n@pytest.fixture(scope='session')\ndef _spark_session():\n \"\"\"Internal fixture for SparkSession instance.\n\n Yields SparkSession instance if it is supported by the pyspark\n version, otherwise yields None.\n\n Required to correctly initialize `spark_context` fixture after\n `spark_session` fixture.\n\n ..note::\n It is not possible to create SparkSession from the existing\n SparkContext.\n \"\"\"\n\n try:\n from pyspark.sql import SparkSession\n except ImportError:\n yield\n else:\n session = SparkSession.builder.enableHiveSupport().getOrCreate()\n yield session\n session.stop()\n\n\n@pytest.fixture(scope='session')\ndef spark_context(_spark_session):\n \"\"\"Return a SparkContext instance with reduced logging\n (session scope).\n \"\"\"\n\n if _spark_session is None:\n from pyspark import SparkContext\n\n # pyspark 1.x: create SparkContext instance\n sc = SparkContext()\n else:\n # pyspark 2.x: get SparkContext from SparkSession fixture\n sc = _spark_session.sparkContext\n\n reduce_logging(sc)\n yield sc\n\n if _spark_session is None:\n sc.stop() # pyspark 1.x: stop SparkContext instance\n\n\n@pytest.fixture(scope='session')\ndef spark_session(_spark_session):\n \"\"\"Return a Hive enabled SparkSession instance with reduced logging\n (session scope).\n\n Available from Spark 2.0 onwards.\n \"\"\"\n\n if _spark_session is None:\n raise Exception(\n 'The \"spark_session\" fixture is only available on spark 2.0 '\n 'and above. Please use the spark_context fixture and instanciate '\n 'a SQLContext or HiveContext from it in your tests.'\n )\n else:\n reduce_logging(_spark_session.sparkContext)\n yield _spark_session\n","sub_path":"pytest_spark/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"98965991","text":"####################\nimport requests\nimport qrcode\nfrom flask import Flask\nfrom flask import render_template\n####################\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n# order\n@app.route('/<item>')\ndef order(item=None):\n # fetch the correct price here\n import lib.price as price\n can_price = price.get()\n url = 'bitcoincash:qz8zcxumuzd8fx4cxc73qlhs8kta4jv6wu9knfn567?amount='\n url += str(can_price)\n img = qrcode.make(url)\n img.save('static/qr.png')\n return render_template('order.html', item=item, price=round(can_price, 4))\n\n####################\n# checking the payment\n\napp.run(debug=True, port=666, host='127.0.0.1')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"511252227","text":"import speech_recognition as sr # import the library\r\nimport webbrowser as wb #\r\n\r\n\r\n\r\nchrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'\r\n\r\nr = sr.Recognizer() # initialize recognizer\r\n\r\nwith sr.Microphone() as source: # mention source it will be either Microphone or audio files.\r\n print('Say Something!')\r\n audio = r.listen(source) # listen to the source\r\n print('done,')\r\n\r\n\r\ntry:\r\n text = r.recognize_google(audio) # use recognizer to convert our audio into text part\r\n lang = 'en'\r\n print(text)\r\n if 'search in google' in text.lower():\r\n f_text = 'https://www.google.co.in/search?q=' + text[16:]\r\n wb.get(chrome_path).open(f_text)\r\n elif 'search website' in text.lower():\r\n wb.get(chrome_path).open(text[14:])\r\n else:\r\n print(text)\r\n\r\n\r\nexcept:\r\n print(\"xmis amocnoba ver moxerxda\") # In case of voice not recognized clearly\r\n","sub_path":"main3.py","file_name":"main3.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"252195309","text":"#coding:utf8\nfrom flask import jsonify,redirect, url_for, session, request, render_template, Blueprint\nimport copy\nimport model\nimport jsons\n\nac = Blueprint('star', __name__)\n\n@ac.route('/action/star/<int:urlid>')\ndef star(urlid):\n if 'username' not in session:\n return redirect(url_for('account.login'))\n else:\n userid = session['id']\n db = model.star(userid, urlid)\n if db.star() == True:\n return redirect(url_for('index.index'))\n else:\n errs = copy.copy(jsons.err)\n errs['decription'] = 'start false'\n return jsonify(errs)\n\n@ac.route('/action/unstar/<int:urlid>')\ndef unstar(urlid):\n if 'username' not in session:\n return redirect(url_for('account.login'))\n else:\n userid = session['id']\n db = model.star(userid, urlid)\n if db.unstar() == True:\n return redirect(url_for('index.index'))\n else:\n errs = copy.copy(jsons.err)\n errs['decription'] = 'unstart false'\n return jsonify(errs)\n\n@ac.route('/user/<username>/stars')\ndef stars(username):\n userid = model.user(username).get()[0]\n db_up = model.update(userid).updateStars()\n db_stars = model.star(userid).get_stars()\n stars = {\n 'page':'stars',\n 'sum':len(db_stars),\n 'url':db_stars\n }\n return jsonify(stars)","sub_path":"easyurl/webSite/controllers/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"620661838","text":"k = 2\nkeywords = [\"anacell\", \"betacellular\", \"cetracular\", \"deltacellular\", \"eurocell\"]\nreviews = [\n \"I love anacell Best services; Best services provided by anacell\",\n \"betacellular has great services\",\n \"deltacellular provides much better services than betacellular\",\n \"cetracular is worse than anacell\",\n \"Betacellular is better than deltacellular.\",\n]\n\nimport re\nfrom collections import Counter\nimport heapq\n\nclass Element:\n def __init__(self, word, freq):\n self.word = word\n self.freq = freq\n \n def __lt__(self, other):\n if self.freq == other.freq:\n return self.word > other.word\n return self.freq < other.freq\n\ndef topKFrequent(k, keywords, reviews):\n '''\n k: int\n keywwords: list of string\n reviews: list of string\n '''\n word_list = []\n \n for review in reviews:\n word_list += list(review.lower().replace('[^a-z0-9]', '').split())\n \n print (word_list)\n count = Counter(word_list)\n \n heap = []\n \n for word, freq in count.items():\n if word in keywords:\n heapq.heappush(heap, Element(word, freq))\n if len(heap) > k:\n heapq.heappop(heap)\n \n return [heapq.heappop(heap).word for _ in range(k)][::-1]\n \n\nprint(topKFrequent(k, keywords, reviews))","sub_path":"ama_oa/10_top_k_frequent_mentioned_keywords.py","file_name":"10_top_k_frequent_mentioned_keywords.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"651123471","text":"import numpy as np\n\nimport keras\nfrom keras import backend as K\nfrom keras.engine.topology import Layer\n\nfrom keras.models import Sequential\n\nimport tensorflow as tf\n\n\n\nclass TaylorMap(Layer):\n def __init__(self, output_dim, order=1,\n weights_regularizer = None,\n initial_weights = None,\n aperture = 50e-5,\n **kwargs):\n self.output_dim = output_dim\n self.order = order\n self.initial_weights = initial_weights\n self.weights_regularizer = weights_regularizer\n self.aperture = aperture\n \n \n super(TaylorMap, self).__init__(**kwargs)\n\n\n def build(self, input_shape):\n input_dim = input_shape[1]\n self.input_dim = input_dim\n \n \n nsize = 1\n self.W = []\n self.nsizes = [nsize]\n \n for i in range(self.order+1):\n if self.initial_weights is None:\n initial_weight_value = np.zeros((nsize, self.output_dim))\n else:\n initial_weight_value = self.initial_weights[i]\n nsize*=input_dim\n self.nsizes.append(nsize)\n self.W.append(K.variable(initial_weight_value))\n\n if self.initial_weights is None:\n self.W[1] = (K.variable(np.eye(N=input_dim, M=self.output_dim)))\n\n self.trainable_weights = self.W\n\n return\n\n def call(self, x, mask=None):\n ans = self.W[0]\n tmp = x\n x_vectors = tf.expand_dims(x, -1)\n \n # particle loss, nan for lost particle\n # get x coordinate\n tmp_x, tmp_xp = tf.unstack(x, axis=1) \n aper = tf.constant(self.aperture, shape=None)\n # find particle outside aperture\n condition = tf.greater_equal(abs(tmp_x), aper)\n # set nan for x for lost particles\n res = tf.where(condition, np.nan, tmp_x)\n # join new x coordiantes with xp coordinates\n tmp = tf.stack([res,tmp_xp], axis=1 )\n \n # layer transformation\n for i in range(1, self.order+1):\n ans = ans + K.dot(tmp, self.W[i])\n\n if(i == self.order):\n continue\n xext_vectors = tf.expand_dims(tmp, -1)\n x_extend_matrix = tf.matmul(x_vectors, xext_vectors, adjoint_a=False, adjoint_b=True)\n tmp = tf.reshape(x_extend_matrix, [-1, self.nsizes[i+1]])\n\n if self.weights_regularizer:\n self.add_loss(self.weights_regularizer(self.W))\n \n \n return ans\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], self.output_dim)\n\n\n def get_output_shape_for(self, input_shape):\n return (input_shape[0], self.output_dim)\n","sub_path":"tm_pnn/layers/Taylor_Map_loss_method_nan.py","file_name":"Taylor_Map_loss_method_nan.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384027291","text":"# Copyright 2017 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\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\n\nfrom tripleo_common.image import base\n\nif sys.version_info[0] < 3:\n import codecs\n _open = open\n open = codecs.open\n\n\nclass KollaImageBuilder(base.BaseImageManager):\n \"\"\"Build images using kolla-build\"\"\"\n\n logger = logging.getLogger(__name__ + '.KollaImageBuilder')\n handler = logging.StreamHandler(sys.stdout)\n\n @staticmethod\n def imagename_to_regex(imagename):\n if not imagename:\n return\n # remove any namespace from the start\n imagename = imagename.split('/')[-1]\n\n # remove any tag from the end\n imagename = imagename.split(':')[0]\n\n # remove supported base names from the start\n imagename = re.sub(r'^(centos|rhel)-', '', imagename)\n\n # remove install_type from the start\n imagename = re.sub(r'^(binary|source|rdo|rhos)-', '', imagename)\n\n # what results should be acceptable as a regex to build one image\n return imagename\n\n def build_images(self, kolla_config_files=None):\n\n cmd = ['kolla-build']\n if kolla_config_files:\n for f in kolla_config_files:\n cmd.append('--config-file')\n cmd.append(f)\n\n container_images = self.load_config_files(self.CONTAINER_IMAGES) or []\n container_images.sort(key=lambda i: i.get('imagename'))\n for i in container_images:\n image = self.imagename_to_regex(i.get('imagename'))\n if image:\n cmd.append(image)\n\n self.logger.info('Running %s' % ' '.join(cmd))\n env = os.environ.copy()\n process = subprocess.Popen(cmd, env=env)\n process.wait()\n if process.returncode != 0:\n raise subprocess.CalledProcessError(process.returncode, cmd)\n","sub_path":"tripleo_common/image/kolla_builder.py","file_name":"kolla_builder.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"206677358","text":"import unittest\nimport math\n\nfrom . import quaternion\n\n\nclass QuaternionTest(unittest.TestCase):\n\n def test_multiply(self):\n qa = [1, 0, 0, 0]\n qb = [0, 1, 0, 0]\n qc = quaternion.multiply(qa, qb)\n self.assertEqual(qc, qb) # identity\n\n qd = quaternion.multiply(qb, qb)\n self.assertEqual(qd, [-1, 0, 0, 0]) # twice rotation by 90deg\n\n qdd = quaternion.multiply(qd, qd)\n self.assertEqual(qdd, qa) # identity\n\n# vim: expandtab sw=4 ts=4\n","sub_path":"osgar/lib/test_quaternion.py","file_name":"test_quaternion.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595597698","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author : Joshua\n@Time : 2018/9/5 18:42\n@File : proxy_manager.py\n@Desc : 代理池管理,调度抓取、验证、入库\n\"\"\"\n\nfrom multiprocessing import Value, Queue, Process\nfrom api.apiServer import start_api_server\nfrom proxy_pipeline import SqlitePipeline\n\nfrom proxy_validator import ValidatorScheduler, Validator\nfrom proxy_crawler import start_proxycrawl\n\nfrom setting import TASK_QUEUE_SIZE\n\ndef start_all():\n myip = Validator.get_myip()\n DB_PROXY_NUM = Value('i', 0)\n task_queue = Queue(maxsize=TASK_QUEUE_SIZE)\n verified_queue = Queue()\n\n process_list =[]\n p0 = Process(target=start_api_server)\n process_list.append(p0)\n p1 = Process(target=start_proxycrawl, args=(task_queue, DB_PROXY_NUM, myip))\n process_list.append(p1)\n p2 = Process(target=ValidatorScheduler.validator, args=(task_queue, verified_queue, myip))\n process_list.append(p2)\n p3 = Process(target=SqlitePipeline.save_data, args=(verified_queue, DB_PROXY_NUM))\n process_list.append(p3)\n\n for i in process_list:\n i.daemon = True\n i.start()\n\n for i in process_list:\n i.join()\n\nif __name__ == \"__main__\":\n start_all()","sub_path":"spider/strong_spider/spider/antispider/proxypool/proxy_manager.py","file_name":"proxy_manager.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"379787666","text":"\"\"\"Свои типы полей\"\"\"\n\nfrom django.db import models\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\nclass OrderField(models.PositiveIntegerField):\n \"\"\"\n Собственное поле сортировки (для определения порядка для содержимого курсов).\n Наследуэмся от PositiveIntegerField и реализовуем две дополнительные функции:\n 1) автоматическое назначение порядкового номера, если он не был задан\n явно. Когда создается новый объект и пользователь не указывает порядок,\n поле будет заполняться автоматически, основываясь на том, сколько\n объектов уже создано для модуля. Например, если уже есть два объекта\n с порядковыми номерами 1 и 2, то новому будет присвоен 3;\n 2) сортировка объектов по порядку номеров. Модули курсов и содержимое\n модулей всегда будут возвращаться отсортированными внутри своего\n родительского объекта.\n \"\"\"\n\n def __init__(self, for_fields=None, *args, **kwargs):\n self.for_fields = for_fields\n super(OrderField, self).__init__(*args, **kwargs)\n\n def pre_save(self, model_instance, add):\n if getattr(model_instance, self.attname) is None:\n # Значение пусто.\n try:\n qs = self.model.objects.all()\n if self.for_fields:\n # Фильтруем объекты с такими же значениями полей, перечисленных в \"for_fields\".\n query = {field: getattr(model_instance, field) for field in self.for_fields}\n qs = qs.filter(**query)\n # Получаем заказ последнего объекта.\n last_item = qs.latest(self.attname)\n value = last_item.order + 1\n except ObjectDoesNotExist:\n value = 0\n setattr(model_instance, self.attname, value)\n return value\n else:\n return super(OrderField, self).pre_save(model_instance, add)\n","sub_path":"myeduca/src/courses/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"427704385","text":"\"\"\"\nSupport for Xiaomi Mi Home Air Conditioner Companion (AC Partner)\n\nFor more details about this platform, please refer to the documentation\nhttps://home-assistant.io/components/climate.xiaomi_miio\n\"\"\"\nimport logging\nimport asyncio\nfrom functools import partial\nfrom datetime import timedelta\nimport voluptuous as vol\n\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.entity import ToggleEntity\nfrom homeassistant.components.climate import (\n PLATFORM_SCHEMA, ClimateDevice, ATTR_TARGET_TEMP_HIGH,\n ATTR_TARGET_TEMP_LOW, ATTR_OPERATION_MODE,\n SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_HIGH,\n SUPPORT_TARGET_TEMPERATURE_LOW, SUPPORT_OPERATION_MODE, SUPPORT_FAN_MODE,\n SUPPORT_SWING_MODE, SUPPORT_ON_OFF, )\nfrom homeassistant.const import (\n TEMP_CELSIUS, ATTR_TEMPERATURE, ATTR_UNIT_OF_MEASUREMENT,\n CONF_NAME, CONF_HOST, CONF_TOKEN, CONF_TIMEOUT, STATE_ON, STATE_OFF,\n STATE_IDLE, )\n\nfrom homeassistant.helpers.event import async_track_state_change\nimport homeassistant.helpers.config_validation as cv\n\n_LOGGER = logging.getLogger(__name__)\n\n# REQUIREMENTS = ['python-miio>=0.3.6']\nREQUIREMENTS = ['https://github.com/rytilahti/python-miio/archive/'\n 'fc5799a05c217be123985f196e71aad57197f11c.zip#'\n 'python-miio']\n\nDEPENDENCIES = ['sensor']\n\nSUCCESS = ['ok']\n\nDEFAULT_TOLERANCE = 0.3\nDEFAULT_NAME = 'Xiaomi AC Companion'\n\nDEFAULT_TIMEOUT = 10\nDEFAULT_RETRY = 3\n\nDEFAULT_MIN_TEMP = 16\nDEFAULT_MAX_TEMP = 30\nDEFAULT_STEP = 1\n\nSTATE_HEAT = 'heat'\nSTATE_COOL = 'cool'\nSTATE_AUTO = 'auto'\n\nSTATE_LOW = 'low'\nSTATE_MEDIUM = 'medium'\nSTATE_HIGH = 'high'\n\nATTR_AIR_CONDITION_MODEL = 'ac_model'\nATTR_AIR_CONDITION_POWER = 'ac_power'\nATTR_SWING_MODE = 'swing_mode'\nATTR_FAN_SPEED = 'fan_speed'\nATTR_LOAD_POWER = 'load_power'\nATTR_LED = 'led'\n\nDEFAULT_OPERATION_MODES = [STATE_HEAT, STATE_COOL, STATE_AUTO, STATE_OFF]\nDEFAULT_SWING_MODES = [STATE_ON, STATE_OFF]\nDEFAULT_FAN_MODES = [STATE_LOW, STATE_MEDIUM, STATE_HIGH, STATE_AUTO]\n\nSUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_TARGET_TEMPERATURE_HIGH |\n SUPPORT_TARGET_TEMPERATURE_LOW | SUPPORT_FAN_MODE |\n SUPPORT_OPERATION_MODE | SUPPORT_SWING_MODE | SUPPORT_ON_OFF)\n\nCONF_SENSOR = 'target_sensor'\nCONF_CUSTOMIZE = 'customize'\n\nSCAN_INTERVAL = timedelta(seconds=15)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_HOST): cv.string,\n vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,\n vol.Required(CONF_SENSOR, default=None): cv.entity_id,\n vol.Optional(CONF_CUSTOMIZE, default=None): dict,\n})\n\n\n# pylint: disable=unused-argument\n@asyncio.coroutine\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\n \"\"\"Set up the air conditioning companion from config.\"\"\"\n host = config.get(CONF_HOST)\n name = config.get(CONF_NAME) or DEFAULT_NAME\n token = config.get(CONF_TOKEN)\n sensor_entity_id = config.get(CONF_SENSOR)\n customize = config.get(CONF_CUSTOMIZE)\n\n async_add_devices([XiaomiAirConditioningCompanion(\n hass, name, host, token, sensor_entity_id, customize)],\n update_before_add=True)\n\n\nclass XiaomiAirConditioningCompanion(ClimateDevice):\n \"\"\"Representation of a Xiaomi Air Conditioning Companion.\"\"\"\n\n def __init__(self, hass, name, host, token, sensor_entity_id, customize):\n\n \"\"\"Initialize the climate device.\"\"\"\n self.hass = hass\n self._state = None\n self._state_attrs = {\n ATTR_AIR_CONDITION_MODEL: None,\n ATTR_AIR_CONDITION_POWER: None,\n ATTR_TEMPERATURE: None,\n ATTR_SWING_MODE: None,\n ATTR_FAN_SPEED: None,\n ATTR_OPERATION_MODE: None,\n ATTR_LOAD_POWER: None,\n ATTR_LED: None,\n }\n self._air_condition_model = None\n\n self._name = name if name else DEFAULT_NAME\n self._unit_of_measurement = TEMP_CELSIUS\n self._host = host\n self._token = token\n self._sensor_entity_id = sensor_entity_id\n self._customize = customize\n\n self._target_temperature = None\n self._target_humidity = None\n self._current_temperature = None\n self._current_humidity = None\n self._current_swing_mode = None\n self._current_operation = None\n self._current_fan_mode = None\n\n self._operation_list = DEFAULT_OPERATION_MODES\n self._away = None\n self._hold = None\n self._aux = None\n self._target_temperature_high = DEFAULT_MAX_TEMP\n self._target_temperature_low = DEFAULT_MIN_TEMP\n self._max_temp = DEFAULT_MAX_TEMP + 1\n self._min_temp = DEFAULT_MIN_TEMP - 1\n self._target_temp_step = DEFAULT_STEP\n\n if self._customize and ('fan' in self._customize):\n self._customize_fan_list = list(self._customize['fan'])\n self._fan_list = self._customize_fan_list\n else:\n self._fan_list = DEFAULT_FAN_MODES\n\n if self._customize and ('swing' in self._customize):\n self._customize_swing_list = list(self._customize['swing'])\n self._swing_list = self._customize_swing_list\n else:\n self._swing_list = DEFAULT_SWING_MODES\n\n if sensor_entity_id:\n async_track_state_change(\n hass, sensor_entity_id, self._async_sensor_changed)\n sensor_state = hass.states.get(sensor_entity_id)\n if sensor_state:\n self._async_update_temp(sensor_state)\n\n from miio import AirConditioningCompanion\n _LOGGER.info(\"initializing with host %s token %s\", self._host,\n self._token)\n self._climate = AirConditioningCompanion(self._host, self._token)\n\n @callback\n def _async_update_temp(self, state):\n \"\"\"Update thermostat with latest state from sensor.\"\"\"\n unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)\n\n try:\n self._current_temperature = self.hass.config.units.temperature(\n float(state.state), unit)\n except ValueError as ex:\n _LOGGER.error('Unable to update from sensor: %s', ex)\n\n @asyncio.coroutine\n def _async_sensor_changed(self, entity_id, old_state, new_state):\n \"\"\"Handle temperature changes.\"\"\"\n if new_state is None:\n return\n self._async_update_temp(new_state)\n\n @asyncio.coroutine\n def _try_command(self, mask_error, func, *args, **kwargs):\n \"\"\"Call a AC companion command handling error messages.\"\"\"\n from miio import DeviceException\n try:\n result = yield from self.hass.async_add_job(\n partial(func, *args, **kwargs))\n\n _LOGGER.debug(\"Response received: %s\", result)\n\n return result == SUCCESS\n except DeviceException as exc:\n _LOGGER.error(mask_error, exc)\n return False\n\n @asyncio.coroutine\n def async_turn_on(self: ToggleEntity, speed: str = None, **kwargs) -> None:\n \"\"\"Turn the miio device on.\"\"\"\n result = yield from self._try_command(\n \"Turning the miio device on failed.\", self._climate.on)\n\n if result:\n self._state = True\n\n @asyncio.coroutine\n def async_turn_off(self: ToggleEntity, **kwargs) -> None:\n \"\"\"Turn the miio device off.\"\"\"\n result = yield from self._try_command(\n \"Turning the miio device off failed.\", self._climate.off)\n\n if result:\n self._state = False\n\n @asyncio.coroutine\n def async_update(self):\n \"\"\"Update the state of this climate device.\"\"\"\n from miio import DeviceException\n\n try:\n state = yield from self.hass.async_add_job(self._climate.status)\n _LOGGER.debug(\"Got new state: %s\", state)\n\n self._state = state.is_on\n self._state_attrs = {\n ATTR_AIR_CONDITION_MODEL: state.air_condition_model,\n ATTR_AIR_CONDITION_POWER: state.air_condition_power,\n ATTR_TEMPERATURE: state.temperature,\n ATTR_SWING_MODE: state.swing_mode,\n ATTR_FAN_SPEED: state.fan_speed.name,\n ATTR_OPERATION_MODE: state.mode.name,\n ATTR_LOAD_POWER: state.load_power,\n ATTR_LED: state.led,\n }\n\n if self._air_condition_model is None:\n self._air_condition_model = state.air_condition_model\n\n self._current_operation = state.mode.name.lower()\n # BUG? The target_temperature shoudn't be updated here.\n # It's fine if state.temperature contains the target temperature.\n # self._target_temperature = state.temperature\n\n if (not self._customize) or (self._customize\n and 'fan' not in self._customize):\n self._current_fan_mode = state.fan_speed.name.lower()\n\n if (not self._customize) or (self._customize\n and 'swing' not in self._customize):\n self._current_swing_mode = \\\n STATE_ON if state.swing_mode else STATE_OFF\n\n if not self._sensor_entity_id:\n self._current_temperature = state.temperature\n\n except DeviceException as ex:\n self._state = None\n _LOGGER.error(\"Got exception while fetching the state: %s\", ex)\n\n @property\n def supported_features(self):\n \"\"\"Return the list of supported features.\"\"\"\n return SUPPORT_FLAGS\n\n @property\n def min_temp(self):\n \"\"\"Return the minimum temperature.\"\"\"\n return self._min_temp\n\n @property\n def max_temp(self):\n \"\"\"Return the maximum temperature.\"\"\"\n return self._max_temp\n\n @property\n def target_temperature_step(self):\n \"\"\"Return the target temperature step.\"\"\"\n return self._target_temp_step\n\n @property\n def should_poll(self):\n \"\"\"Return the polling state.\"\"\"\n return True\n\n @property\n def name(self):\n \"\"\"Return the name of the climate device.\"\"\"\n return self._name\n\n @property\n def available(self):\n \"\"\"Return true when state is known.\"\"\"\n return self._state is not None\n\n @property\n def temperature_unit(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return self._unit_of_measurement\n\n @property\n def current_temperature(self):\n \"\"\"Return the current temperature.\"\"\"\n return self._current_temperature\n\n @property\n def target_temperature(self):\n \"\"\"Return the temperature we try to reach.\"\"\"\n return self._target_temperature\n\n @property\n def target_temperature_high(self):\n \"\"\"Return the upper bound of the target temperature we try to reach.\"\"\"\n return self._target_temperature_high\n\n @property\n def target_temperature_low(self):\n \"\"\"Return the lower bound of the target temperature we try to reach.\"\"\"\n return self._target_temperature_low\n\n @property\n def current_humidity(self):\n \"\"\"Return the current humidity.\"\"\"\n return self._current_humidity\n\n @property\n def target_humidity(self):\n \"\"\"Return the humidity we try to reach.\"\"\"\n return self._target_humidity\n\n @property\n def current_operation(self):\n \"\"\"Return current operation ie. heat, cool, idle.\"\"\"\n return self._current_operation\n\n @property\n def operation_list(self):\n \"\"\"Return the list of available operation modes.\"\"\"\n return self._operation_list\n\n @property\n def is_away_mode_on(self):\n \"\"\"Return if away mode is on.\"\"\"\n return self._away\n\n @property\n def current_hold_mode(self):\n \"\"\"Return hold mode setting.\"\"\"\n return self._hold\n\n @property\n def is_aux_heat_on(self):\n \"\"\"Return true if aux heat is on.\"\"\"\n return self._aux\n\n @property\n def current_fan_mode(self):\n \"\"\"Return the current fan mode.\"\"\"\n return self._current_fan_mode\n\n @property\n def fan_list(self):\n \"\"\"Return the list of available fan modes.\"\"\"\n return self._fan_list\n\n @property\n def is_on(self) -> bool:\n \"\"\"Return True if the entity is on\"\"\"\n return self._state\n\n @asyncio.coroutine\n def async_set_temperature(self, **kwargs):\n \"\"\"Set target temperature.\"\"\"\n if kwargs.get(ATTR_TEMPERATURE) is not None:\n self._target_temperature = kwargs.get(ATTR_TEMPERATURE)\n\n if kwargs.get(ATTR_TARGET_TEMP_HIGH) is not None and \\\n kwargs.get(ATTR_TARGET_TEMP_LOW) is not None:\n self._target_temperature_high = kwargs.get(ATTR_TARGET_TEMP_HIGH)\n self._target_temperature_low = kwargs.get(ATTR_TARGET_TEMP_LOW)\n\n if kwargs.get(ATTR_OPERATION_MODE) is not None:\n self._current_operation = kwargs.get(ATTR_OPERATION_MODE)\n else:\n if self._target_temperature < self._target_temperature_low:\n self._current_operation = STATE_OFF\n self._target_temperature = self._target_temperature_low\n elif self._target_temperature > self._target_temperature_high:\n self._current_operation = STATE_OFF\n self._target_temperature = self._target_temperature_high\n elif self._current_temperature and (\n self._current_operation == STATE_OFF or\n self._current_operation == STATE_IDLE):\n self._current_operation = STATE_AUTO\n\n self._send_configuration()\n\n @asyncio.coroutine\n def async_set_humidity(self, humidity):\n \"\"\"Set the target humidity.\"\"\"\n self._target_humidity = humidity\n\n @asyncio.coroutine\n def async_set_swing_mode(self, swing_mode):\n \"\"\"Set target temperature.\"\"\"\n self._current_swing_mode = swing_mode\n if self._customize and ('swing' in self._customize) and \\\n (self._current_swing_mode in self._customize['swing']):\n self._send_custom_command(\n self._customize['swing'][self._current_swing_mode])\n else:\n self._send_configuration()\n\n @asyncio.coroutine\n def async_set_fan_mode(self, fan):\n \"\"\"Set the fan mode.\"\"\"\n self._current_fan_mode = fan\n if self._customize and ('fan' in self._customize) and \\\n (self._current_fan_mode in self._customize['fan']):\n self._send_custom_command(\n self._customize['fan'][self._current_fan_mode])\n else:\n self._send_configuration()\n\n @asyncio.coroutine\n def async_set_operation_mode(self, operation_mode):\n \"\"\"Set operation mode.\"\"\"\n self._current_operation = operation_mode\n self._send_configuration()\n\n @property\n def current_swing_mode(self):\n \"\"\"Return the current swing setting.\"\"\"\n return self._current_swing_mode\n\n @property\n def swing_list(self):\n \"\"\"List of available swing modes.\"\"\"\n return self._swing_list\n\n @asyncio.coroutine\n def async_turn_away_mode_on(self):\n \"\"\"Turn away mode on.\"\"\"\n self._away = True\n\n @asyncio.coroutine\n def async_turn_away_mode_off(self):\n \"\"\"Turn away mode off.\"\"\"\n self._away = False\n\n @asyncio.coroutine\n def async_set_hold_mode(self, hold):\n \"\"\"Update hold mode on.\"\"\"\n self._hold = hold\n\n @asyncio.coroutine\n def async_turn_aux_heat_on(self):\n \"\"\"Turn auxillary heater on.\"\"\"\n self._aux = True\n\n @asyncio.coroutine\n def async_turn_aux_heat_off(self):\n \"\"\"Turn auxiliary heater off.\"\"\"\n self._aux = False\n\n def _send_configuration(self):\n from miio.airconditioningcompanion import \\\n Power, OperationMode, FanSpeed, SwingMode, Led\n\n if self._air_condition_model is not None:\n yield from self._try_command(\n \"Sending new air conditioner configuration failed.\",\n self._climate.send_configuration(\n self._air_condition_model,\n Power(int(self._state)),\n OperationMode[self._current_operation.title()],\n self._target_temperature,\n FanSpeed[self._current_fan_mode.title()],\n SwingMode[self._current_swing_mode.title()],\n Led.Off,\n ), False)\n else:\n _LOGGER.error('Model number of the air condition unknown. '\n 'Configuration cannot be sent.')\n\n def _send_custom_command(self, command: str):\n if command[0:2] == \"01\":\n yield from self._try_command(\n \"Sending new air conditioner configuration failed.\",\n self._climate.send_command(command), False)\n else:\n # Learned infrared commands has the prefix 'FE'\n yield from self._try_command(\n \"Sending new air conditioner configuration failed.\",\n self._climate.send_ir_code(command), False)\n","sub_path":"custom_components/climate/xiaomi_miio.py","file_name":"xiaomi_miio.py","file_ext":"py","file_size_in_byte":17121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384211765","text":"\"\"\"\nSTEP 2: CROSS TRAINING\nThe GDNN models are trained.\n\"\"\"\nfrom s0_start import basedir\nimport sys \nsys.path.append(basedir)\n\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom os.path import join\n\nfrom ninolearn.utils import include_time_lag\nfrom ninolearn.IO.read_processed import data_reader\nfrom ninolearn.learn.models.dem import DEM\nfrom ninolearn.learn.fit import cross_training\nfrom ninolearn.pathes import infodir\n\n\n# =============================================================================\n# Determine the end of observational period and the lead times\n# =============================================================================\nfrom s0_start import start_pred_y, start_pred_m\nf = open(join(infodir,\"enddate.txt\"), \"r\")\nendyr = f.readline()\nendmth = f.readline()\nf.close()\nend_obs_m = int(endmth)\nend_obs_y = int(endyr)\n\nif end_obs_m < 10:\n endmth = '0'+endmth\n\nif start_pred_y > end_obs_y+1 or (start_pred_y > end_obs_y and start_pred_m > end_obs_m):\n raise ValueError(\"More than 1 year difference between end of observations and start of predictions.\\\n Either include more observations or let the predictions start earlier.\")\n\nlt_first = (start_pred_m - end_obs_m)%12 - 1 \nlead_times = np.arange(lt_first,lt_first+9) # prediction for 9 seasons\nnp.save(join(infodir,'lead_times'), lead_times)\n\n\n# =============================================================================\n# Process data and train model\n# =============================================================================\n\ndef pipeline(lead_time, return_persistance=False):\n \"\"\"\n Data pipeline for the processing of the data before the Deep Ensemble\n is trained.\n\n :type lead_time: int\n :param lead_time: The lead time in month.\n\n :type return_persistance: boolean\n :param return_persistance: Return as the persistance as well.\n\n :returns: The feature \"X\" (at observation time), the label \"y\" (at lead\n time), the target season \"timey\" (least month) and if selected the\n label at observation time \"y_persistance\". Hence, the output comes as:\n X, y, timey, y_persistance.\n \"\"\" \n reader = data_reader(startdate='1960-01', enddate=endyr+'-'+endmth)\n\n # indices\n oni = reader.read_csv('oni')\n dmi = reader.read_csv('dmi')\n wwv = reader.read_csv('wwv_proxy')\n\n # seasonal cycle\n cos = np.cos(np.arange(len(oni))/12*2*np.pi)\n\n # wind stress\n taux = reader.read_netcdf('taux', dataset='NCEP', processed='anom')\n\n taux_WP = taux.loc[dict(lat=slice(2.5,-2.5), lon=slice(120, 160))]\n taux_WP_mean = taux_WP.mean(dim='lat').mean(dim='lon')\n\n # include values from 3 and 6 months previously as predictor variables\n n_lags = 3\n step = 3\n\n # shift such that lead time corresponds to the definition of lead time\n shift = 3\n\n # process features\n feature_unscaled = np.stack((oni,\n wwv,\n dmi,\n cos,\n taux_WP_mean\n ), axis=1)\n\n # scale each feature\n scalerX = StandardScaler()\n Xorg = scalerX.fit_transform(feature_unscaled)\n\n # set nans to 0.\n Xorg = np.nan_to_num(Xorg)\n np.save(join(infodir,'Xorg'), Xorg) \n\n # arange the feature array\n X = Xorg[:-lead_time-shift,:]\n X = include_time_lag(X, n_lags=n_lags, step=step)\n\n # arange label\n yorg = oni.values\n y = yorg[lead_time + n_lags*step + shift:]\n\n # get the time axis of the label\n timey = oni.index[lead_time + n_lags*step + shift:]\n\n if return_persistance:\n y_persistance = yorg[n_lags*step: - lead_time - shift]\n return X, y, timey, y_persistance\n\n else:\n return X, y, timey\n\nif __name__==\"__main__\":\n cross_training(DEM, pipeline, 1, lead_times,\n layers=1, neurons = 32, dropout=0.05, noise_in=0.0, noise_sigma=0.,\n noise_mu=0., l1_hidden=0.0, l2_hidden=0.,\n l1_mu=0, l2_mu=0., l1_sigma=0,\n l2_sigma=0.0, lr=0.01, batch_size=100,\n epochs=5000, n_segments=5, n_members_segment=3, patience=25,\n activation='tanh',\n verbose=0, pdf=\"normal\", name=\"gdnn_ex_pca\")\n \nprint(\"\\n \\nStep 2 finished, continue to step 3!\")","sub_path":"predictions/s2_training.py","file_name":"s2_training.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"622852777","text":"# coding: utf-8\nfrom __future__ import print_function, unicode_literals\n\nimport os\nimport sys\nfrom strip_hints import strip_file_to_string\n\n\n# list unique types used in hints:\n# rm -rf unt && cp -pR copyparty unt && (cd unt && python3 ../scripts/strip_hints/a.py)\n# diff -wNarU1 copyparty unt | grep -E '^\\-' | sed -r 's/[^][, ]+://g; s/[^][, ]+[[(]//g; s/[],()<>{} -]/\\n/g' | grep -E .. | sort | uniq -c | sort -n\n\n\ndef pr(m):\n sys.stderr.write(m)\n sys.stderr.flush()\n\n\ndef uh(top):\n if os.path.exists(top + \"/uh\"):\n return\n\n # pr(\"building support for your python ver\")\n pr(\"unhinting\")\n files = []\n for (dp, _, fns) in os.walk(top):\n for fn in fns:\n if not fn.endswith(\".py\"):\n continue\n\n fp = os.path.join(dp, fn)\n files.append(fp)\n\n try:\n import multiprocessing as mp\n\n with mp.Pool(os.cpu_count()) as pool:\n pool.map(uh1, files)\n except Exception as ex:\n print(\"\\nnon-mp fallback due to {}\\n\".format(ex))\n for fp in files:\n uh1(fp)\n\n pr(\"k\\n\")\n with open(top + \"/uh\", \"wb\") as f:\n f.write(b\"a\")\n\n\ndef uh1(fp):\n pr(\".\")\n cs = strip_file_to_string(fp, no_ast=True, to_empty=True)\n\n # remove expensive imports too\n lns = []\n on = True\n for ln in cs.split(\"\\n\"):\n if ln.startswith(\"if True:\"):\n on = False\n continue\n\n if not on and (not ln.strip() or ln.startswith(\" \")):\n continue\n\n on = True\n lns.append(ln)\n\n cs = \"\\n\".join(lns)\n with open(fp, \"wb\") as f:\n f.write(cs.encode(\"utf-8\"))\n\n\nif __name__ == \"__main__\":\n uh(\".\")\n","sub_path":"scripts/strip_hints/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50676601","text":"import os\nfrom flask import (\n Flask, flash, render_template,\n redirect, request, session, url_for)\nfrom flask_pymongo import PyMongo\nfrom bson.objectid import ObjectId\nfrom werkzeug.security import generate_password_hash, check_password_hash \nif os.path.exists(\"env.py\"):\n import env\n\n\napp = Flask(__name__)\n\napp.config[\"MONGO_DBNAME\"] = os.environ.get(\"MONGO_DBNAME\")\napp.config[\"MONGO_URI\"] = os.environ.get(\"MONGO_URI\")\napp.secret_key = os.environ.get(\"SECRET_KEY\")\n\nmongo = PyMongo(app)\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/get_inventories\")\ndef get_inventories():\n inventories = list(mongo.db.inventories.find().sort(\"category_name\", 1))\n inventories = list(mongo.db.inventories.find().sort(\"inventory_name\", 1))\n return render_template(\"inventories.html\", inventories=inventories)\n\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n if request.method == \"POST\":\n # check if username already exists in the db\n existing_user = mongo.db.users.find_one(\n {\"username\": request.form.get(\"username\").lower()})\n\n if existing_user:\n flash(\"Username already exists\")\n return redirect(url_for(\"register\"))\n\n register = {\n \"username\": request.form.get(\"username\").lower(),\n \"password\": generate_password_hash(request.form.get(\"password\"))\n }\n mongo.db.users.insert_one(register)\n\n # put the new user into 'session' cookie\n session[\"user\"] = request.form.get(\"username\").lower()\n flash(\"Registration Successful!\")\n return redirect(url_for(\"profile\", username=session[\"user\"]))\n return render_template(\"register.html\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"POST\":\n # check if username exists in db\n existing_user = mongo.db.users.find_one(\n {\"username\": request.form.get(\"username\").lower()})\n\n if existing_user:\n # ensure hashed password matches user input\n if check_password_hash(\n existing_user[\"password\"], request.form.get(\"password\")):\n session[\"user\"] = request.form.get(\"username\").lower()\n flash(\"Welcome, {}\".format(\n request.form.get(\"username\")))\n return redirect(url_for(\n \"profile\", username=session[\"user\"]))\n else:\n # invalid password match\n flash(\"Incorrect Username and/or Password\")\n return redirect(url_for(\"login\"))\n\n else:\n # username doesn't exist\n flash(\"Incorrect Username and/or Password\")\n return redirect(url_for(\"login\"))\n\n return render_template(\"login.html\")\n\n\n@app.route(\"/profile/<username>\", methods=[\"GET\", \"POST\"])\ndef profile(username):\n # get the session user's username from db\n username = mongo.db.users.find_one(\n {\"username\": session[\"user\"]})[\"username\"]\n return render_template(\"profile.html\", username=username)\n\n\n@app.route(\"/logout\")\ndef logout():\n # remove user from session cookies\n flash(\"You have been logged out\")\n session.pop(\"user\")\n return redirect(url_for(\"login\"))\n\n\n@app.route(\"/add_inventory\", methods=[\"GET\", \"POST\"]) \ndef add_inventory():\n if request.method == \"POST\":\n inventory = {\n \"category_name\": request.form.get(\"category_name\"),\n \"inventory_name\": request.form.get(\"inventory_name\"),\n \"inventory_description\": request.form.get(\"inventory_description\"),\n \"created_by\": session[\"user\"]\n }\n mongo.db.inventories.insert_one(inventory)\n flash(\"Word Successfully Added\")\n return redirect(url_for(\"get_inventories\"))\n \n categories = mongo.db.categories.find().sort(\"category_name\", 1)\n return render_template(\"add_inventory.html\", categories=categories)\n\n\n@app.route(\"/edit_inventory/<inventory_id>\", methods=[\"GET\", \"POST\"])\ndef edit_inventory(inventory_id):\n if request.method == \"POST\":\n submit = {\n \"category_name\": request.form.get(\"category_name\"),\n \"inventory_name\": request.form.get(\"inventory_name\"),\n \"inventory_description\": request.form.get(\"inventory_description\"),\n \"created_by\": session[\"user\"]\n }\n mongo.db.inventories.update({\"_id\": ObjectId(inventory_id)}, submit)\n flash(\"Word Successfully Updated\")\n\n inventory = mongo.db.inventories.find_one({\"_id\": ObjectId(inventory_id)})\n categories = mongo.db.categories.find().sort(\"category_name\", 1)\n return render_template(\n \"edit_inventory.html\", inventory=inventory, categories=categories)\n\n\n@app.route(\"/delete_inventory/<inventory_id>\")\ndef delete_inventory(inventory_id):\n mongo.db.inventories.remove({\"_id\": ObjectId(inventory_id)})\n flash(\"Inventory Successfully Deleted\")\n return redirect(url_for(\"get_inventories\"))\n\n\n@app.route(\"/get_categories\")\ndef get_categories():\n categories = list(mongo.db.categories.find().sort(\"category_name\", 1))\n return render_template(\"categories.html\", categories=categories)\n\n\n@app.route(\"/add_category\", methods=[\"GET\", \"POST\"])\ndef add_category():\n if request.method == \"POST\":\n category = {\n \"category_name\": request.form.get(\"category_name\")\n }\n mongo.db.categories.insert_one(category)\n flash(\"New Category Added\")\n return redirect(url_for(\"get_categories\"))\n\n return render_template(\"add_category.html\")\n\n\n@app.route(\"/edit_category/<category_id>\", methods=[\"GET\", \"POST\"])\ndef edit_category(category_id):\n if request.method == \"POST\":\n submit = {\n \"category_name\": request.form.get(\"category_name\")\n }\n mongo.db.categories.update({\"_id\": ObjectId(category_id)}, submit)\n flash(\"Category Successfully Updated\")\n return redirect(url_for(\"get_categories\"))\n\n category = mongo.db.categories.find_one({\"_id\": ObjectId(category_id)})\n return render_template(\"edit_category.html\", category=category)\n\n\n@app.route(\"/delete_category/<category_id>\")\ndef delete_category(category_id):\n mongo.db.categories.remove({\"_id\": ObjectId(category_id)})\n flash(\"Category Successfully Deleted\")\n return redirect(url_for(\"get_categories\"))\n\n\nif __name__ == \"__main__\":\n app.run(host=os.environ.get(\"IP\"),\n port=int(os.environ.get(\"PORT\")),\n debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168328080","text":"#!/usr/bin/env nemesis\n#\n# ======================================================================\n#\n# Brad T. Aagaard, U.S. Geological Survey\n# Charles A. Williams, GNS Science\n# Matthew G. Knepley, University at Buffalo\n#\n# This code was developed as part of the Computational Infrastructure\n# for Geodynamics (http://geodynamics.org).\n#\n# Copyright (c) 2010-2022 University of California, Davis\n#\n# See LICENSE.md for license information.\n#\n# ======================================================================\n#\n# @file tests/pytests/topology/TestMesh.py\n#\n# @brief Unit testing of Python Mesh object.\n\nimport unittest\n\nfrom pylith.topology.Mesh import Mesh\n\n\nclass TestMesh(unittest.TestCase):\n \"\"\"Unit testing of Mesh object.\n \"\"\"\n\n def test_constructor(self):\n mesh = Mesh()\n self.assertTrue(not mesh is None)\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestMesh))\n\n from pylith.utils.PetscManager import PetscManager\n petsc = PetscManager()\n petsc.initialize()\n\n success = unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()\n\n petsc.finalize()\n\n\n# End of file\n","sub_path":"tests/pytests/topology/TestMesh.py","file_name":"TestMesh.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164004999","text":"import pymongo\r\nfrom pyquery import PyQuery as pq\r\nimport requests\r\nimport time\r\nimport os\r\nfrom string import Template\r\nimport schedule\r\nimport re\r\n\r\nos.system('cls')\r\n\r\nfund_code_list = [\r\n '000736',\r\n '100051',\r\n '161724',\r\n '270002',\r\n '000220',\r\n '206018',\r\n '519697',\r\n '519732',\r\n]\r\nclient = pymongo.MongoClient('207.148.28.234:27017')\r\ndb = client['test']\r\ndb_coll = db['fund']\r\n\r\ndef save_fund_gs( fund_code ):\r\n '获取并保存基金估算值'\r\n fund_code = fund_code\r\n fund_url = Template('http://fund.eastmoney.com/${fund_code}.html').safe_substitute(fund_code=fund_code)\r\n fund_html = requests.get(fund_url)\r\n fund_html.encoding = 'utf-8'\r\n pq_fund_html = pq(fund_html.text)\r\n gsz = pq_fund_html.find('#gz_gsz').text()\r\n gztime = pq_fund_html.find('#gz_gztime').text()\r\n fund_name = pq_fund_html.find('.funCur-FundName').text()\r\n print({\r\n 'name': fund_name,\r\n 'code': fund_code,\r\n 'gsz': gsz,\r\n 'gztime': gztime,\r\n })\r\n db_coll.update(\r\n {'fund_code' : fund_code},\r\n {\r\n '$push': {\r\n 'fund_gsz': {\r\n 'date': gztime,\r\n 'gsz': gsz,\r\n }\r\n },\r\n },\r\n upsert = True\r\n )\r\n\r\ndef job():\r\n for fund_code in fund_code_list: # 第二个实例\r\n save_fund_gs(fund_code)\r\n\r\ndef work_day_job():\r\n '每周1到5运行任务'\r\n set_time = '14:39'\r\n schedule.every().monday.at(set_time).do(job)\r\n schedule.every().tuesday.at(set_time).do(job)\r\n schedule.every().wednesday.at(set_time).do(job)\r\n schedule.every().thursday.at(set_time).do(job)\r\n schedule.every().friday.at(set_time).do(job)\r\n\r\nwork_day_job()\r\n\r\nwhile True:\r\n schedule.run_pending()\r\n time.sleep(1) # 循化检查任务\r\n\r\nos.system('pause')\r\n","sub_path":"demo/定时获取基金估值.py","file_name":"定时获取基金估值.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"269465837","text":"import csv\nimport sys\nimport string\nimport copy\nfrom collections import Counter\nfrom operator import itemgetter\nimport numpy as np\nfrom math import exp\nimport matplotlib.pyplot as plt\n\n#from tabulate import tabulate\nfrom collections import defaultdict\nfrom math import log\nfrom scipy import stats\n\ndef sigmoid(X):\n return sigmoid(X)\n\n\ntrain = 1000\ntotal=0\nproduct_id = np.zeros((train,1))\ncustomer_id = np.zeros((train,1))\nprice = np.zeros((train,1))\ndataset=np.zeros((train*3,2))\ndataset2=np.zeros((train*3,2))\ntest = 0\nwith open('test_values.csv', newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',')\n for row in spamreader:\n i = 0\n for string in row:\n if i == 1 and total > 0 and total <=train:\n #print(total)\n product_id[total-1]= float(string)\n if i == 2 and total > 0 and total <=train:\n customer_id[total-1]=(float(string))\n if i == 5 and total > 0 and total <=train:\n price[total-1]=(float(string))\n #print(i,string)\n i=i+1\n if(total<=train and total>0):\n dataset[total-1] = [customer_id[total-1],price[total-1]]\n dataset2[total-1] = [customer_id[total-1],product_id[total-1]]\n total=total+1\n test=test+1\n if(total>train):\n spamreader = csv.reader(csvfile, delimiter=',')\n for row in spamreader:\n i = 0\n for string in row:\n if i == 1:\n #print(total)\n product_id[total-test]= float(string)\n if i == 2:\n customer_id[total-test]=(float(string))\n if i == 5:\n price[total-test]=(float(string))\n #print(i,string)\n i=i+1\n dataset[total-1] = [customer_id[total-test],price[total-test]]\n dataset2[total-1] = [customer_id[total-test],product_id[total-test]]\n\n\n\ndef lr_train(train_vectors, iterations=100, reg=0.01,\n lr=0.01, stop_diff=int(1e-6)):\n\n count_w = train\n w = np.zeros((count_w,1 ))\n\n for i in range(iterations):\n grad = np.zeros((count_w, 2))\n\n for vector in train_vectors:\n\n y = vector[1]\n x = vector[0]\n\n y_hat = lr_calc_prob(w, y)\n\n grad += (y - y_hat)*x\n\n #print(grad,\"grad\",reg,\"reg\",w,\"w\")\n w = [i*reg for i in w]\n grad -= w\n w += lr * grad\n\n if np.linalg.norm(grad) <= stop_diff:\n break\n\n return w\n\ndef lr_calc_prob(w, x):\n #print(np.sum(np.dot(w,x)))\n\n denominator = 1 + exp(-1 * np.sum(np.dot(w,x)))\n\n return denominator\n\ndef lr_classify(w, x):\n\n return lr_calc_prob(w, x)\n\n\ndef lr_train_test(train_vectors, test_vectors):\n\n w = lr_train(train_vectors)\n incorrect = 0.0\n\n for vector in test_vectors:\n y = vector[0]\n x = vector[1]\n\n y_hat = lr_classify(w, x)\n\n if y_hat is not y:\n incorrect += 1\n\n return incorrect/len(test_vectors)\n\n\nzero_one_loss = lr_train(dataset)\n\ni = test\nop = [0];\nfor vector in dataset:\n y = vector[1]\n x = vector[0]\nwhile i < total:\n pred_value = zero_one_loss*op\n if pred_value - x > 10:\n print(\"failed\")\n\n\n\n\nzero_one_loss = lr_train(dataset2)\n\ni = test\nop = [0];\nfor vector in dataset2:\n y = vector[1]\n x = vector[0]\nwhile i < total:\n pred_value = zero_one_loss*op\n if pred_value - x > 10:\n print(\"failed second\")\n","sub_path":"ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"617645180","text":"# 톱니바퀴 - BOJ 14891\n# 구현\nfrom collections import deque\nchain = [deque(list(input())) for _ in range(4)]\nk = int(input())\n\ndef left(now, l, dir):\n if l < 0:\n return\n if chain[now][6] != chain[l][2]:\n left(l, l-1, -dir)\n chain[l].rotate(-dir)\n\ndef right(now, r, dir):\n if r > 3:\n return\n if chain[now][2] != chain[r][6]:\n right(r, r+1, -dir)\n chain[r].rotate(-dir)\n\nfor _ in range(k):\n num, dir = map(int, input().split())\n left(num-1, num-2, dir)\n right(num-1, num, dir)\n chain[num-1].rotate(dir)\n\nanswer = 0\nfor i in range(4):\n if chain[i][0] == \"1\":\n answer += (2**i)\n\nprint(answer)\n","sub_path":"SW역량테스트/톱니바퀴.py","file_name":"톱니바퀴.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"636992822","text":"#!/usr/bin/python\n\nimport randomfields\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn=100\nxi=0\nxl=5\n\n# Gaussian random field\nmodel = 'RMbessel(nu=0.1)'\nmy_rf = randomfields.RRandomField(model=model)\ncovA, h = my_rf.get_covariance_1D(do_print=True, xi=xi, xl=xl, n=n)\nplt.plot(h, covA)\n\nmodel = 'RMbernoulli({phi}, {t})'.format(phi=model, t=0.0)\nmy_rf = randomfields.RRandomField(model=model)\ncovB, h = my_rf.get_covariance_1D(do_print=True, xi=xi, xl=xl, n=n)\nplt.plot(h, covB)\n\ncovC = covA/2.0\nplt.plot(h, covC)\n\nplt.xlabel('distance')\nplt.ylabel('covariance')\n#plt.xlim(0,5)\n#plt.ylim(0,1)\nplt.grid(True)\n\nplt.savefig('cov.png')\n\n","sub_path":"clients/client_plot_covariance.py","file_name":"client_plot_covariance.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342617289","text":"import os.path\n\nclass File:\n __path = \"\"\n __buffer = []\n __index = 0\n\n def __init__(self, file, overwrite = False):\n self.__path = file\n if (os.path.isfile(file)):\n fs = open(file, 'r')\n self.__buffer = list(fs.read().splitlines())\n self.__index = 0\n fs.close()\n\n if overwrite:\n self.__buffer = []\n\n def Clear(self):\n self.__buffer = []\n\n def Read(self):\n if (self.__index < len(self.__buffer)):\n val = self.__buffer[self.__index]\n self.__index = self.__index + 1\n return val\n \n def Write(self, value):\n self.__buffer.append(value)\n\n def Save(self):\n if (os.path.isfile(self.__path)):\n os.remove(self.__path)\n \n fs = open(self.__path, 'w')\n for value in self.__buffer:\n fs.write(str(value) + \"\\n\")\n fs.close()\n","sub_path":"IO.py","file_name":"IO.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"407844847","text":"import functools\nimport logging\nimport os\nimport pathlib\nimport stat\nimport tempfile\nimport textwrap\n\nimport pytest\nimport salt.version\n\nlog = logging.getLogger(__name__)\n\nTESTS_PATH = pathlib.Path(__file__).resolve().parent\n\n\ntry: # pragma: no cover\n import importlib.metadata\n\n pkg_version = importlib.metadata.version\nexcept ImportError: # pragma: no cover\n try:\n import importlib_metadata\n\n pkg_version = importlib_metadata.version\n except ImportError: # pragma: no cover\n import pkg_resources\n\n def pkg_version(package):\n return pkg_resources.get_distribution(package).version\n\n\ndef pkg_version_info(package):\n return tuple(int(part) for part in pkg_version(package).split(\".\") if part.isdigit())\n\n\nif pkg_version_info(\"pytest\") >= (6, 2):\n pytest_plugins = [\"pytester\"]\nelse:\n\n @pytest.fixture\n def pytester():\n pytest.skip(\"The pytester fixture is not available in Pytest < 6.2.0\")\n\n\ndef pytest_report_header():\n return \"salt-version: {}\".format(salt.version.__version__)\n\n\nclass Tempfiles:\n \"\"\"\n Class which generates temporary files and cleans them when done\n \"\"\"\n\n def __init__(self, request):\n self.request = request\n\n def makepyfile(self, contents, prefix=None, executable=False):\n \"\"\"\n Creates a python file and returns it's path\n \"\"\"\n tfile = tempfile.NamedTemporaryFile(\"w\", prefix=prefix or \"tmp\", suffix=\".py\", delete=False)\n contents = textwrap.dedent(contents.lstrip(\"\\n\")).strip()\n tfile.write(contents)\n tfile.close()\n if executable is True:\n st = os.stat(tfile.name)\n os.chmod(tfile.name, st.st_mode | stat.S_IEXEC)\n self.request.addfinalizer(functools.partial(self._delete_temp_file, tfile.name))\n with open(tfile.name) as rfh:\n log.debug(\n \"Created python file with contents:\\n>>>>> %s >>>>>\\n%s\\n<<<<< %s <<<<<\\n\",\n tfile.name,\n rfh.read(),\n tfile.name,\n )\n return tfile.name\n\n def makeslsfile(self, contents, name=None):\n \"\"\"\n Creates an sls file and returns it's path\n \"\"\"\n if name is None:\n tfile = tempfile.NamedTemporaryFile(\"w\", suffix=\".sls\", delete=False)\n name = tfile.name\n with open(name, \"w\") as wfh:\n contents = textwrap.dedent(contents.lstrip(\"\\n\")).strip()\n wfh.write(contents)\n self.request.addfinalizer(functools.partial(self._delete_temp_file, name))\n with open(name) as rfh:\n log.debug(\n \"Created SLS file with contents:\\n>>>>> %s >>>>>\\n%s\\n<<<<< %s <<<<<\\n\",\n name,\n rfh.read(),\n name,\n )\n return name\n\n def _delete_temp_file(self, fpath):\n \"\"\"\n Cleanup the temporary path\n \"\"\"\n if os.path.exists(fpath):\n os.unlink(fpath)\n\n\n@pytest.fixture\ndef tempfiles(request):\n \"\"\"\n Temporary files fixture\n \"\"\"\n return Tempfiles(request)\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_version():\n return pkg_version(\"salt\")\n\n\n@pytest.mark.trylast\ndef pytest_configure(config):\n \"\"\"\n called after command line options have been parsed\n and all plugins and initial conftest files been loaded.\n \"\"\"\n # Expose the markers we use to pytest CLI\n config.addinivalue_line(\n \"markers\",\n \"skip_on_salt_system_install: Marker to skip tests when testing\"\n \"against salt installed in the system.\",\n )\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_runtest_setup(item):\n salt_factories_fixture = item._request.getfixturevalue(\"salt_factories\")\n if salt_factories_fixture.system_install is False:\n return\n system_install_skip_paths = (\n # There's no point on running these tests against a system install of salt\n str(TESTS_PATH / \"unit\"),\n str(TESTS_PATH / \"functional\"),\n str(TESTS_PATH / \"scenarios\" / \"examples\"),\n str(TESTS_PATH / \"integration\" / \"factories\" / \"cli\"),\n str(TESTS_PATH / \"integration\" / \"factories\" / \"daemons\" / \"sshd\"),\n str(TESTS_PATH / \"integration\" / \"factories\" / \"daemons\" / \"container\"),\n )\n if str(item.fspath).startswith(system_install_skip_paths):\n item._skipped_by_mark = True\n pytest.skip(\"Test should not run against system install of Salt\")\n\n skip_on_salt_system_install_marker = item.get_closest_marker(\"skip_on_salt_system_install\")\n if skip_on_salt_system_install_marker is not None:\n item._skipped_by_mark = True\n pytest.skip(\"Test should not run against system install of Salt\")\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"413163736","text":"from django.http import HttpResponse\nfrom .models import Driver, DriverDoestNotExist, DriverSerializer\nfrom .services import DistanceClass\nimport json\n\n\ndef register_driver(request):\n try:\n request_body = json.loads(request.body)\n except json.decoder.JSONDecodeError:\n return HttpResponse({\n 'error': True,\n })\n serializer = DriverSerializer(data=request_body)\n if serializer.is_valid():\n serializer.save()\n return HttpResponse({\n 'success': True\n })\n else:\n return HttpResponse(\n serializer.errors\n )\n\n\ndef update_location(request, driver_id):\n \"\"\"\n :param request: json.dumbs -> {\"latitude\" : 34.0023, \"longitude\": -43.0000}\n :param driver_id: driver id\n \"\"\"\n try:\n request_body = json.loads(request.body)\n except json.decoder.JSONDecodeError:\n return HttpResponse({\n 'error': True,\n })\n try:\n driver = Driver.objects.get(id=driver_id)\n except Driver.DoesNotExist:\n raise DriverDoestNotExist\n driver_data = driver.__dict__\n driver_data['latitude'] = float(request_body.get('latitude'))\n driver_data['longitude'] = float(request_body.get('longitude'))\n serializer = DriverSerializer(driver, data=driver_data)\n if serializer.is_valid():\n driver.save()\n return HttpResponse({\n 'success': True\n })\n else:\n return HttpResponse(\n serializer.errors\n )\n\n\ndef get_nearest_drivers(request):\n try:\n request_body = json.loads(request.body)\n except json.decoder.JSONDecodeError:\n return HttpResponse({\n 'error': True,\n })\n dist_class = DistanceClass()\n lat = request_body.get('latitude')\n lon = request_body.get('longitude')\n drivers = Driver.objects.exclude(\n latitude=None).exclude(longitude=None).values_list('latitude', 'longitude', 'id')\n nearby_driver_ids = list()\n for driver in drivers:\n distance = dist_class.calculate_distance(driver[0], driver[1], lat, lon)\n # ignoring all drivers who are more than 4 kms away from passenger's coordinates\n if distance <= 4:\n nearby_driver_ids.append(driver[2])\n nearby_drivers = Driver.objects.filter(id__in=nearby_driver_ids)\n serializer = DriverSerializer(nearby_drivers, many=True)\n response = serializer.data\n return HttpResponse(response)\n","sub_path":"django_application/cab_service/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"429735941","text":"from gen_wrapper import build_wrapper\nfrom gen_wrapper import APIWrapper\nimport yaml\nimport json\nimport pprint\n\nclass InfluenceExplorer(APIWrapper):\n def _process_url_query(self, query):\n \"\"\"\n Add our API key to the query.\n \"\"\"\n api_key = YOUR_API_KEY\n query = query + \"&apikey={0}\".format(api_key)\n return query\n\n def _process_url_response(self, response):\n \"\"\"\n Process the response.\n \"\"\"\n str_response = response.read().decode('utf-8')\n return json.loads(str_response)\n\ndef __main__():\n\n # Create the APIWrapper instance\n ie = InfluenceExplorer()\n ie = build_wrapper(ie)\n\n # Search for something\n resp = ie.search_entities(\"hillary clinton\")\n pprint.pprint(resp)\n\n\n__main__()\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433416349","text":"import time, cv2, os, sys\nsys.path.append('..')\nimport numpy as np\nimport tensorflow as tf\nfrom deblur_ThreeLayer import *\nfrom utils import *\nfrom tqdm import tqdm\nfrom matplotlib import pyplot as plt\ntf.set_random_seed(777)\ntf.reset_default_graph()\n\ntmp = np.load('/data1/jerry/project/deblurring/data/phantom/data_simple_square.npz')\nimg = tmp['img']\nlab = tmp['lab']\n\nprint('Train Image Size : %s'%str(img.shape))\nprint('Train Label Size : %s'%str(lab.shape))\n\nsess = tf.Session()\ndeblur = Model(sess, \"deblur\", 256, 9, 1e-3)\nsess.run(tf.global_variables_initializer())\nsaver = tf.train.Saver()\n\ncheckpoint = '/data1/jerry/project/deblurring/checkpoint'\nproject = '/square/3layers'\nnum = '/3layers'\n\nif os.path.exists(checkpoint + project + num + '.index'):\n saver.restore(sess, checkpoint + project + num + '.index')\n print(\"Restored\")\nelse :\n if not os.path.exists(checkpoint):\n os.mkdir(checkpoint+project)\n print(\"Initializatin Done\")\n \nval_tr_cost = []\n\n\nprint(\"Start Train\")\nstart = time.time()\nepochs = 2000\nbatch = 50\nfor epoch in tqdm(range(epochs)):\n avg_train_cost = 0\n \n total_batch = int(len(img)/batch)\n\n for i in range(total_batch):\n \n batch_seq = np.random.choice(len(img), batch, replace=False)\n batch_xs = img[batch_seq]\n batch_ys = lab[batch_seq]\n c, _ = deblur.train(batch_xs, batch_ys)\n avg_train_cost += c/total_batch\n \n \n val_tr_cost.append(avg_train_cost)\n\n \n \n if (epoch+1)%100 == 0:\n print(\"Epoch : %d/%d\"%(epoch+1, epochs))\n print(\"Train Cost : %.9f\"%(avg_train_cost))\n #print(\"Test Cost : %.9f\"%(avg_test_cost))\n print(\"----------------------------\\n\\n\")\n \n \nprint(\"Learning Finished!\")\nprint(\"Elapsed time : \", time.time()-start)\n\nnp.save(checkpoint+project+'/cost', val_tr_cost)\n\nsaver.save(sess, checkpoint+project+num)","sub_path":"gen01/train_lcl.py","file_name":"train_lcl.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"113156435","text":"import time\n\nimport pytest\nfrom helpers.cluster import ClickHouseCluster\nfrom helpers.cluster import ClickHouseKiller\nfrom helpers.network import PartitionManager\n\ncluster = ClickHouseCluster(__file__)\n\ndictionary_node = cluster.add_instance(\"dictionary_node\", stay_alive=True)\nmain_node = cluster.add_instance(\n \"main_node\", dictionaries=[\"configs/dictionaries/cache_ints_dictionary.xml\"]\n)\n\n\n@pytest.fixture(scope=\"module\")\ndef started_cluster():\n try:\n cluster.start()\n dictionary_node.query(\"create database if not exists test;\")\n dictionary_node.query(\"drop table if exists test.ints;\")\n dictionary_node.query(\n \"create table test.ints \"\n \"(key UInt64, \"\n \"i8 Int8, i16 Int16, i32 Int32, i64 Int64, \"\n \"u8 UInt8, u16 UInt16, u32 UInt32, u64 UInt64) \"\n \"Engine = Memory;\"\n )\n dictionary_node.query(\n \"insert into test.ints values (7, 7, 7, 7, 7, 7, 7, 7, 7);\"\n )\n dictionary_node.query(\n \"insert into test.ints values (5, 5, 5, 5, 5, 5, 5, 5, 5);\"\n )\n\n yield cluster\n finally:\n cluster.shutdown()\n\n\ndef test_simple_dict_get_or_default(started_cluster):\n assert None != dictionary_node.get_process_pid(\n \"clickhouse\"\n ), \"ClickHouse must be alive\"\n\n def test_helper():\n assert (\n \"5\"\n == main_node.query(\n \"select dictGetOrDefault('experimental_dict', 'i8', toUInt64(5), toInt8(42));\"\n ).rstrip()\n )\n assert (\n \"5\"\n == main_node.query(\n \"select dictGetOrDefault('experimental_dict', 'i16', toUInt64(5), toInt16(42));\"\n ).rstrip()\n )\n assert (\n \"5\"\n == main_node.query(\n \"select dictGetOrDefault('experimental_dict', 'i32', toUInt64(5), toInt32(42));\"\n ).rstrip()\n )\n assert (\n \"5\"\n == main_node.query(\n \"select dictGetOrDefault('experimental_dict', 'i64', toUInt64(5), toInt64(42));\"\n ).rstrip()\n )\n assert (\n \"5\"\n == main_node.query(\n \"select dictGetOrDefault('experimental_dict', 'u8', toUInt64(5), toUInt8(42));\"\n ).rstrip()\n )\n assert (\n \"5\"\n == main_node.query(\n \"select dictGetOrDefault('experimental_dict', 'u16', toUInt64(5), toUInt16(42));\"\n ).rstrip()\n )\n assert (\n \"5\"\n == main_node.query(\n \"select dictGetOrDefault('experimental_dict', 'u32', toUInt64(5), toUInt32(42));\"\n ).rstrip()\n )\n assert (\n \"5\"\n == main_node.query(\n \"select dictGetOrDefault('experimental_dict', 'u64', toUInt64(5), toUInt64(42));\"\n ).rstrip()\n )\n\n test_helper()\n\n with PartitionManager() as pm, ClickHouseKiller(dictionary_node):\n assert None == dictionary_node.get_process_pid(\"clickhouse\")\n\n # Remove connection between main_node and dictionary for sure\n pm.partition_instances(main_node, dictionary_node)\n\n # Dictionary max lifetime is 2 seconds.\n time.sleep(3)\n\n test_helper()\n","sub_path":"tests/integration/test_dictionary_allow_read_expired_keys/test_dict_get_or_default.py","file_name":"test_dict_get_or_default.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302368316","text":"#!/usr/bin/env python3\n\n# 我去,真乱,考虑到这次我拿vi写的,原谅自己了\n\nimport subprocess,multiprocessing\nfrom multiprocessing import Queue,Manager\nfrom concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import ProcessPoolExecutor\nimport argparse,time,datetime,sys\nimport json\nimport ipaddress\n\n'''\n\n+ 利用pool在多线程、多进程接口一致性的特点来构造proc/thread目的\n+ 选linux(我用的就是centos7)上的ping和nc来做实际检查的工具、\n - 所以估计只能在我这个平台上跑,主要是nc版本的问题,这货的版本我一直搞不太明白\n - 我这环境是一个python3.6应该是\n - 自己能花费的可支配的时间,不足以用python socket撸一遍\n+ 其他都是非设计性的,撞到哪儿算哪儿\n\n另外,上次也不知道哪儿是发牢骚?估计戾气重的同学才能看的出来吧\n\n关于注释究竟该写什么怎么写?\n\n+ 确实是个大主题\n+ 看看是放本周学习笔记还是下周ARTS(因为这周ARTS已经完成)打卡\n+ 这里少扯吧\n - 避免又招惹来那些莫名其妙的,只给否定式而不表达直接观点的低水平评语脏了自己的眼睛\n\n'''\n\n# 得承认没懂到底全局变量应该咋用,可能js的给我影响太大,觉不出python这么个搞法有啥意思\n# 嗷,忽然有所悟,是不是它没有声明变量的关键字搞的?\nVERBOSE = None\n\n# 后来想改成logging的,但还是保留吧\n# 当时主要写这个是因为习惯于命令行输出到管道,然后python -m json.tool格式化的,后来才意识到特么自己就是在py\ndef myPrint(*args, **kwargs):\n global VERBOSE\n if VERBOSE:\n print(\"[MYDEBUG] \",*args,file=sys.stderr,**kwargs)\n else:\n pass # 这个似乎是看conventions里让这么写的\n\n# 这个忘了炒的argparse还是getOpt了\ndef main():\n\n parser = argparse.ArgumentParser(description='山寨打包简版 ping or nc')\n parser.add_argument('-n','--nums','--worker-numbers',help='指定并发数量',\n type=int,default=multiprocessing.cpu_count()+1) # 所以python 没有三目运算符真的不太好理解,觉的表意不清?\n parser.add_argument('-f', '--tool',required=True,choices=('ping','tcp'),\n help='工作模式,ping主机段还是指定ip的1024内端口扫描') # 这个参数命名上偏奇怪,而且,挺罗嗦的后面写的,限定了一种可以接受的参数格式吧\n parser.add_argument('-ip',required=True, \n help='如果工作模式是ping,这里要指定一个我能接受的ip段...如果工作模式指定了tcp,这里只能给一个ip地址?')\n parser.add_argument('-m', '--mode' , help='多线程还是多进程,选1',default=\"thread\",choices=('proc','thread')) # 这个一直想写一个 -w 不跟参数就是缺省的文件名,跟了就是自定义的,没写就是不输出文件,不得要领\n parser.add_argument('-w', help='如果给定了该选项,保存结果到指定路径(到底-w 和选3是不是一个东西,没看懂题)')\n parser.add_argument('-v', \"--verbose\", help='是否输出更详细日志(兼选2 吧)',action=\"store_true\") # 把选2和自己的debug输出混一起了,其实想-vvv来着,先放一放\n \n args = parser.parse_args()\n myPrint(\"args type\",type(args))\n myPrint(\"args : \",args)\n if args.verbose:\n global VERBOSE\n VERBOSE = args.verbose\n with Manager() as manager:\n q = manager.Queue()\n \n cs = CopycatScanner(args.ip,args.nums,args.tool,args.mode,q)\n start=datetime.datetime.now()\n cs.scan()\n end=datetime.datetime.now()\n if(args.w):\n with open(args.w,mode='w') as f:\n json.dump(cs.result(),f)\n else:\n print(json.dumps(cs.result(),indent=4))\n myPrint(end-start)\n # ...\n\nclass CopycatScanner:\n\n def __init__(self,ip_address,workers,which_tool,mode,q):\n self.ip_addr = ip_address # 变量类型可以变来变去这种,自己写的时候很痛快,尤其静态的写多了,对这种类型可以中途换的潜意识里就会一���别人家孩子的感觉,但生产代码觉的不该这么做\n self.workers = workers\n self.excutor = ThreadPoolExecutor if mode=='thread' else ProcessPoolExecutor # 依赖查找,是不是应该扣一分,自查时候发现应该放外面好了\n self.tool = which_tool\n self.queue = q # 这个算是合理的一个依赖注入?把依赖资源的生命周期管理倒置于外部了\n\n # 还想过是不是另起一个线程那边边放这边就收集的,就不写while循环了,可是感觉也没什么特别的好处,没弄\n def result(self):\n result = {}\n while self.queue.qsize()>0:\n ele = self.queue.get()\n result[ele[0]]=ele[1]\n return result\n\n # 内部方法是不是该加前导下划线?是该看看编码风格约束的东西了\n # 好像据说我喜欢的2个空格缩进也不被提倡,歪果仁的显示器真大\n def regular_ip(self):\n self.ip_addr = str(ipaddress.ip_address(self.ip_addr))\n \n # 还是觉得应该找一个库,但是看了nmap得文档,它的target specification真不是题目这么定义的,\n # 我一开始也只想CIDR的,但是发现标准库network传单个地址不抛异常,和我预期不符,那算了...\n def regular_ips(self):\n ip_range_pair = self.ip_addr.split(\"-\")\n if len(ip_range_pair) !=2:\n raise Exception(\"format is not support\",self.ip_addr)\n \n start = [x for x in map(lambda x :int(x),ip_range_pair[0].split(\".\"))];\n end = [x for x in map(lambda x :int(x) ,ip_range_pair[1].split(\".\"))];\n if len(start) !=4 or len(end) !=4:\n raise Exception(\"format is not support\",self.ip_addr)\n \n # 这堆异常的串串可以再整整\n for i in range(0,3):\n if start[i]!=end[i]:\n raise Exception(\"only support like 192.168.0.1-192.168.0.100 , but \",\n self.ip_addr,\"and pos \",i,\" is different\")\n if start[i]<0 or start[i]>255 or end[i]<0 or end[i]>255:\n raise Exception(\"only support like 192.168.0.1-192.168.0.100 , but \",\n self.ip_addr,\n f'and pos [{i}],value {start[i]} or {end[i]} or both is out of range')\n if start[3]>=end[3]:\n raise Exception(\"only support like 192.168.0.1-192.168.0.100 , but \",\n self.ip_addr)\n\n # 推导式写这么长...估计也就是写着时候还好\n # 可是推导式断哪里感觉精气神儿也都没了...\n self.ip_addr = [f'{str(end[0])}.{str(end[1])}.{str(end[2])}.' + str(x) \n for x in range(start[3],end[3]+1 if end[3]<255 else 255)]\n\n def scan(self):\n if self.tool == 'tcp':\n self.scan_ports()\n else:\n self.scan_ips()\n\n def scan_ips(self):\n self.regular_ips()\n with self.excutor(max_workers=self.workers) as executor:\n for ip in self.ip_addr:\n executor.submit(self.scan_ip,str(ip))\n\n def scan_ip(self,ip):\n p = subprocess.run([\"ping\",\"-w 1 -c 1\",ip],\n stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) # 觉的不足以这周把python socket也撸一遍的,我一直不太确定这个run是个阻塞方法么?\n self.queue.put((ip,\"PONG\" if (p.returncode==0) else \"NO PONG\"));\n myPrint(f'ip: {ip},ping exit code: {p.returncode}')\n\n def scan_ports(self):\n self.regular_ip()\n with self.excutor(max_workers=self.workers) as executor:\n for port in range(1,1025): # 好难受,我觉得一定有办法写成1024,比如0,1024,然后下面+1,也挺二的\n executor.submit(self.scan_port,str(port))\n \n def scan_port(self,port):\n try:\n ip_addr = self.ip_addr # self 这东西挺二的,记得原来写js时候经常这样,不知道python的世界都怎么玩儿\n p = subprocess.run([\"nc\",\"-w 10\",\"-z\",ip_addr,port]) # 确实没打算离开linux跑,我这个nc版本是Ncat: Version 7.50 ( https://nmap.org/ncat ),这货的版本也一直是我没太搞明白的一个东西\n self.queue.put((port,\"Connected\" if (p.returncode==0) else \"Connect Failed\"));\n myPrint(f'port: {port},nc exit code: {p.returncode}')\n except Exception as e:\n myPrint(\"what's up? \",e) # 这货竟然也是扔到池里面的错误不用点手段不打印\n finally:\n myPrint(\"may the world peace with us ... , scan port \",port,self.queue[port]) # 一开始有个拼写错,不打印错误是用这个检查出来的,跟渣渣是一样的...线程池和标准错误连起来得有点手段?\n # time.sleep(2)\n pass\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"week03/pmap.py","file_name":"pmap.py","file_ext":"py","file_size_in_byte":8480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568572376","text":"from functools import wraps\nfrom itertools import chain\nfrom numpy import linspace, meshgrid, sort, unique, where, nan, zeros, ones, arange, fliplr\nfrom numpy import min as npmin\nfrom scipy.interpolate import griddata, interp1d\n\n\"\"\"\nGeneric tools.\n\"\"\"\n\n\ndef flatten(iterable):\n\t\"\"\"\n\tFlatten an iterable by one level.\n\t\"\"\"\n\n\treturn chain.from_iterable(iterable)\n\n\ndef sift(items, cls):\n\t\"\"\"\n\tFilter out items which are not instances of cls.\n\t\"\"\"\n\n\treturn [item for item in items if isinstance(item, cls)]\n\ndef get_mask(x,y, tx, ty):\n\tdx = (tx[-1] - tx[0])/(tx.size -1)\n\tdy = (ty[-1] - ty[0])/(ty.size -1)\n\n\td2 = dx**2 + dy**2\n\n\txgrid = meshgrid(x,tx)\n\tygrid = meshgrid(y,ty)\n\t\n\txdist = (xgrid[0] - xgrid[1])**2\n\tydist = (ygrid[0] - ygrid[1])**2\n\n\tmask = ones((tx.shape[0], ty.shape[0]))\n\t\n\tfor i in range (mask.shape[0]):\n\t\tfor j in range (mask.shape[1]):\n\t\t\tmask[i,j] = npmin(xdist[i] + ydist[j])\n\n\tmask = (mask < d2)*1\n\tmask = where(mask, mask, nan)\n\n\treturn mask.T\n\t\n\n\ndef triples_to_mesh(x, y, z, max_mesh=[-1,-1], has_mask=False):\n\t\"\"\"\n\tConvert 3 equal-sized lists of co-ordinates into an interpolated 2D mesh of z-values.\n\n\tReturns a tuple of:\n\t\tthe mesh\n\t\tthe x bounds\n\t\tthe y bounds\n\t\tthe z bounds\n\t\"\"\"\n\n\tx_values, y_values = sort(unique(x)), sort(unique(y))\n\t\n\tif (all (item > 0 for item in max_mesh)):\n\t\tdisplay_len_x = min (len(x_values), max_mesh[0])\n\t\tdisplay_len_y = min (len(y_values), max_mesh[1])\n\telse:\n\t\tdisplay_len_x = len(x_values)\n\t\tdisplay_len_y = len(y_values)\n\n\tx_space = linspace(x_values[0], x_values[-1], display_len_x)\n\ty_space = linspace(y_values[0], y_values[-1], display_len_y)\n\n\ttarget_x, target_y = meshgrid(x_space, y_space)\n\n\ttarget_z = griddata((x, y), z, (target_x, target_y), method='cubic')\n\n\tif (has_mask):\t\n\t\tmask =\tget_mask (x, y, x_space, y_space)\n\t\ttarget_z = target_z * mask\n\n\treturn (target_z, (x_values[0], x_values[-1]), (y_values[0], y_values[-1]),\n\t\t\t(min(z), max(z)))\n\ndef triples_to_mesh_y(x, y, z, max_mesh=[-1,-1]):\n\t\"\"\"\n\tConvert 3 equal-sized lists of co-ordinates into an interpolated mesh of z-values; with \n\tinterpolation along the y-axis only. The x-data must be of the form\n\t[x0,x0,x0...x1,x1,x1...,xn,xn,xn...xn] with each value xi repeaded the same number of times.\n\tOtherwiese unexpected behaviour follows.\n\n\tReturns a tuple of:\n\t\tthe mesh\n\t\tthe x bounds\n\t\tthe y bounds\n\t\tthe z bounds\n\t\"\"\"\n\tx_values, y_values = sort(unique(x)), sort(unique(y))\n\n\tdisplay_len_x = len(x_values)\n\tif (max_mesh[1]>0):\n\t\tdisplay_len_y = min (len(y_values), max_mesh[1])\n\telse:\n\t\tdisplay_len_y = len(y_values)\n\n\tx_space = x_values\n\ty_space = linspace(y_values[0], y_values[-1], display_len_y)\n\txperiod = float(len(x)) / len(x_values)\n\n\ttarget_z = zeros([display_len_x, display_len_y])\n\n\tfor i, xi in enumerate(x_space):\n\t\tyrange = arange(i*xperiod, (i+1)*xperiod-1).tolist()\n\t\tfy = interp1d (y[yrange], z[yrange], kind='cubic', bounds_error=False)\n\t\ttempy = fy(y_space)\n\t\ttarget_z[i] = tempy\n\n\ttarget_z = target_z.T\n\tif(x[0] - x[-1])>0:\n\t\ttarget_z = fliplr(target_z)\t\n\n\treturn (target_z, (x_values[0], x_values[-1]), (y_values[0], y_values[-1]),\n\t\t\t(min(z), max(z)))\n\n\nclass Enum(set):\n\t\"\"\"\n\tAn enumerated type.\n\n\t>>> e = Enum(['a', 'b', 'c'])\n\t>>> e.a\n\t'a'\n\t>>> e.d\n\t...\n\tAttributeError: 'Enum' object has no attribute 'd'\n\t\"\"\"\n\n\tdef __getattribute__(self, name):\n\t\tif name in self:\n\t\t\treturn name\n\t\telse:\n\t\t\treturn set.__getattribute__(self, name)\n\n\nclass PubDict(dict):\n\t\"\"\"\n\tA locking, publishing dictionary.\n\t\"\"\"\n\n\tdef __init__(self, lock, send, topic, *args, **kwargs):\n\t\t\"\"\"\n\t\tlock: A re-entrant lock which supports context management.\n\t\tsend: Message-sending method of a PubSub publisher.\n\t\ttopic: The topic on which to send messages.\n\t\t\"\"\"\n\n\t\tdict.__init__(self, *args, **kwargs)\n\n\t\tself.lock = lock\n\t\tself.send = send\n\t\tself.topic = topic\n\n\tdef __setitem__(self, k, v):\n\t\t\"\"\"\n\t\tNote: Values cannot be overwritten, to ensure that removal is always handled explicitly.\n\t\t\"\"\"\n\n\t\twith self.lock:\n\t\t\tif k in self:\n\t\t\t\traise KeyError(k)\n\n\t\t\tif v is None:\n\t\t\t\traise ValueError('No value given.')\n\n\t\t\tdict.__setitem__(self, k, v)\n\n\t\t\tself.send('{0}.added'.format(self.topic), name=k, value=v)\n\n\tdef __delitem__(self, k):\n\t\twith self.lock:\n\t\t\tdict.__delitem__(self, k)\n\n\t\t\tself.send('{0}.removed'.format(self.topic), name=k)\n\n\nclass Synchronized(object):\n\t\"\"\"\n\tA decorator for methods which must be synchronized within an object instance.\n\t\"\"\"\n\n\t@staticmethod\n\tdef __call__(f):\n\t\t@wraps(f)\n\t\tdef decorated(self, *args, **kwargs):\n\t\t\twith self.lock:\n\t\t\t\treturn f(self, *args, **kwargs)\n\n\t\treturn decorated\n\n\nclass Without(object):\n\t\"\"\"\n\tA no-op object for use with \"with\".\n\t\"\"\"\n\n\tdef __enter__(self, *args, **kwargs):\n\t\treturn None\n\n\tdef __exit__(self, *args, **kwargs):\n\t\treturn False\n","sub_path":"spacq/tool/box.py","file_name":"box.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"454927581","text":"from pyspark.sql import SparkSession\r\nimport yaml\r\nimport os.path\r\nfrom pyspark.sql.functions import *\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n os.environ[\"PYSPARK_SUBMIT_ARGS\"] = (\r\n '--packages \"org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.0\" pyspark-shell'\r\n )\r\n\r\n # Create the SparkSession\r\n spark = SparkSession \\\r\n .builder \\\r\n .appName(\"Read from enterprise applications\") \\\r\n .master('local[*]') \\\r\n .getOrCreate()\r\n spark.sparkContext.setLogLevel('ERROR')\r\n\r\n current_dir = os.path.abspath(os.path.dirname(__file__))\r\n app_config_path = os.path.abspath(current_dir + \"/../../../\" + \"application.yml\")\r\n app_secrets_path = os.path.abspath(current_dir + \"/../../../\" + \".secrets\")\r\n\r\n conf = open(app_config_path)\r\n app_conf = yaml.load(conf, Loader=yaml.FullLoader)\r\n secret = open(app_secrets_path)\r\n app_secret = yaml.load(secret, Loader=yaml.FullLoader)\r\n\r\n hadoop_conf = spark.sparkContext._jsc.hadoopConfiguration()\r\n hadoop_conf.set(\"fs.s3a.access.key\", app_secret[\"s3_conf\"][\"access_key\"])\r\n hadoop_conf.set(\"fs.s3a.secret.key\", app_secret[\"s3_conf\"][\"secret_access_key\"])\r\n\r\n inputDf = spark\\\r\n .readStream\\\r\n .format(\"kafka\")\\\r\n .option(\"kafka.bootstrap.servers\", app_secret[\"kafka\"][\"server\"] + \":9092\")\\\r\n .option(\"subscribe\", app_conf[\"kafka\"][\"topic\"])\\\r\n .option(\"startingOffsets\", \"earliest\")\\\r\n .load()\r\n\r\n consoleOutput = inputDf\\\r\n .selectExpr(\"CAST(value AS STRING)\")\\\r\n .withColumn(\"value\", split(\"value\", \" \"))\\\r\n .withColumn(\"value\", explode(\"value\"))\\\r\n .groupBy(\"value\")\\\r\n .agg(count(\"value\"))\\\r\n .writeStream\\\r\n .outputMode(\"complete\")\\\r\n .format(\"console\")\\\r\n .start()\\\r\n .awaitTermination()\r\n\r\n# spark-submit --packages \"org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.0\" com/dsm/kafka/complete_mode_demo.py\r\n","sub_path":"com/dsm/kafka/complete_mode_demo.py","file_name":"complete_mode_demo.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167855293","text":"import numpy as np\nimport pyqtgraph as pg\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport pyqtgraph.console\nfrom pyqtgraph.dockarea import *\nfrom pyqtgraph.parametertree import Parameter, ParameterTree\nfrom functools import partial\nimport time\nimport atexit\nimport struct\nimport sys\nfrom subprocess import PIPE, Popen\nfrom threading import Thread\nimport serial.tools.list_ports as list_ports\nimport gc\n\ntry:\n from Queue import Queue, Empty\nexcept ImportError:\n from queue import Queue, Empty # python 3.x\n\nON_POSIX = 'posix' in sys.builtin_module_names\n\n\ndef close_all():\n global serial_daemon\n serial_daemon.terminate()\n\n\ndef enqueue_output(out, queue):\n for line in iter(partial(out.read, 56), b''):\n queue.put(line)\n out.close()\n\n\n# Remember buffersize to prevent re-drawing on simple changes\nBUFFER_SIZE = 250\nLAST_TIME = 0\n\nserial_daemon = Popen('python serial_input.py', stdout=PIPE, stdin=PIPE, bufsize=1, close_fds=ON_POSIX)\nread_q = Queue()\nread_thread = Thread(target=enqueue_output, args=(serial_daemon.stdout, read_q))\nread_thread.daemon = True\nread_thread.start()\natexit.register(close_all)\n# Object Parameters\nSTATUS_STATE = \"UNKNOWN\"\nSIGNAL_STATE = \"DISCONNECTED\"\nSIGNAL_PERIOD = 0\n# Instantiate window remote plotter and dockable region\napp = QtGui.QApplication([])\nwin = QtGui.QMainWindow()\npg.setConfigOption('background', (240, 240, 240))\narea = DockArea()\nwin.setCentralWidget(area)\nwindow_size = (1366, 768)\nwindow_block = (int(window_size[0] / 32), int(window_size[1]) / 40)\nwin.resize(window_size[0], window_size[1])\nwin.setWindowTitle('Real-time Data Visualization and Control')\n\n# Create window for scrolling plot\nDATA_MATRIX = [np.zeros(250), np.zeros(250), np.zeros(250),\n np.zeros(250), np.zeros(250), np.zeros(250),\n np.zeros(250), np.zeros(250), np.zeros(250),\n np.zeros(250), np.zeros(250), np.zeros(250)]\nCURVE_LIST = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nCOLOR_MATRIX = [(255, 0, 0), (0, 0, 255), (0, 255, 0),\n (255, 255, 0), (255, 0, 255), (0, 255, 255),\n (128, 128, 0), (128, 0, 128), (0, 128, 128),\n (128, 0, 0), (0, 128, 0), (0, 0, 128)]\nDRAW_MASK = [True, True, True, True, True, True, True, True, True, True, True, True]\n\n# Sets Parameter(Tree) structure\n\nUART_params = [\n {'name': 'UART Characteristics', 'type': 'group', 'children': [\n {'name': 'Channel', 'type': 'int', 'value': 1},\n {'name': 'Port location', 'type': 'list', 'value': 'COM3'},\n {'name': 'Baudrate', 'type': 'list', 'values': [\n 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200\n ], 'value': 19200},\n {'name': 'Read Timeout', 'type': 'str', 'value': 0.000},\n {'name': 'Write Timeout', 'type': 'str', 'value': 0.000}\n ]}\n]\nparams = [\n {'name': \"Plot Settings\", 'type': 'group', 'children': [\n {'name': 'Buffer size', 'type': 'str', 'value': 250}\n ]},\n {'name': \"Streams\", 'type': 'group', 'children': [\n {'name': 'Stream 1', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': 'F00'}\n ]},\n {'name': 'Stream 2', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '00F'}\n ]},\n {'name': 'Stream 3', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '0F0'}\n ]},\n {'name': 'Stream 4', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': 'FF0'}\n ]},\n {'name': 'Stream 5', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '0FF'}\n ]},\n {'name': 'Stream 6', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': 'F0F'}\n ]},\n {'name': 'Stream 7', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '990'}\n ]},\n {'name': 'Stream 8', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '909'}\n ]},\n {'name': 'Stream 9', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '099'}\n ]},\n {'name': 'Stream 10', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '900'}\n ]},\n {'name': 'Stream 11', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '090'}\n ]},\n {'name': 'Stream 12', 'type': 'bool', 'expanded': False, 'value': True, 'children': [\n {'name': 'Color', 'type': 'color', 'value': '009'}\n ]},\n ]}\n]\n\np = Parameter.create(name='params', type='group', children=params)\nuart_p = Parameter.create(name='params', type='group', children=UART_params)\nuart_params = Parameter.create(name='params', type='group', children=params)\nuart_t = ParameterTree()\nuart_t.setHeaderHidden(True)\nuart_t.setParameters(uart_p, showTop=False)\nuart_t.setWindowTitle('pyqtgraph example: Parameter Tree')\nt = ParameterTree()\nt.setHeaderHidden(True)\nt.setParameters(p, showTop=False)\nt.setWindowTitle('pyqtgraph example: Parameter Tree')\n# Create docks and place about screen. size parameter is not constraining and docks re-shape to fill space and\n# conform to internal specifications\n#d1 = Dock(\"Altitude Orientation Indicator\", size=(window_block[0] * 24, window_block[1] * 11), hideTitle=True)\nd2 = Dock(\"Console\", size=(window_block[0] * 24, window_block[1] * 5), hideTitle=True)\nd3 = Dock(\"Data Stream\", size=(24 * window_block[0], 24 * window_block[1]), hideTitle=True)\nd4 = Dock(\"Menu\", size=(8 * window_block[0], 20 * window_block[1]), hideTitle=True)\nd6 = Dock(\"Stream Options\", size=(8 * window_block[0], 20 * window_block[1]), hideTitle=True)\narea.addDock(d3, 'left')\narea.addDock(d6, 'right', d3)\n#area.addDock(d3, 'bottom', d1)\narea.addDock(d2, 'bottom', d3)\narea.addDock(d4, 'bottom', d6)\n# Add widgets into each dock\n\n# adding dock widgets\n# w1 = pg.LayoutWidget()\n# w1_label = QtGui.QLabel(\"\"\"Will contain either 3D plot or 3 cross-sectional plots for orientation viewing\"\"\")\n# plt_1 = pg.GraphicsLayoutWidget()\n# plot_1_list = QtGui.QListWidget()\n# plot_1_list.setFixedHeight(36)\n# plot_1_list.addItems(['Stream 1', 'Stream 2', 'Stream 3', 'Stream 4', 'Stream 5', 'Stream 6',\n# 'Stream 7', 'Stream 8', 'Stream 9', 'Stream 0', 'Stream 10', 'Stream 11'])\n# plt_2 = pg.GraphicsLayoutWidget()\n# plot_2_list = QtGui.QListWidget()\n# plot_2_list.setFixedHeight(36)\n# plot_2_list.addItems(['Stream 1', 'Stream 2', 'Stream 3', 'Stream 4', 'Stream 5', 'Stream 6',\n# 'Stream 7', 'Stream 8', 'Stream 9', 'Stream 0', 'Stream 10', 'Stream 11'])\n# plt_3 = pg.GraphicsLayoutWidget()\n# plot_3_list = QtGui.QListWidget()\n# plot_3_list.setFixedHeight(36)\n# plot_3_list.addItems(['Stream 1', 'Stream 2', 'Stream 3', 'Stream 4', 'Stream 5', 'Stream 6',\n# 'Stream 7', 'Stream 8', 'Stream 9', 'Stream 0', 'Stream 10', 'Stream 11'])\n# w1.addWidget(w1_label, row=0, col=0, colspan=3)\n# w1.addWidget(plt_1, row=1, col=0, rowspan=1, colspan=1)\n# w1.addWidget(plt_2, row=1, col=1, rowspan=1, colspan=1)\n# w1.addWidget(plt_3, row=1, col=2, rowspan=1, colspan=1)\n# w1.addWidget(plot_1_list, row=2, col=0, rowspan=1, colspan=1)\n# w1.addWidget(plot_2_list, row=2, col=1, rowspan=1, colspan=1)\n# w1.addWidget(plot_3_list, row=2, col=2, rowspan=1, colspan=1)\n# d1.addWidget(w1)\n\n# Adding Stream Settings\nw6 = pg.LayoutWidget()\nw6.addWidget(uart_t, row=0, col=0, colspan=3)\nw6.addWidget(t, row=1, col=0, colspan=3)\nuart_update = QtGui.QPushButton('UPDATE UART')\nstream_update = QtGui.QPushButton('UPDATE PLOT')\nstream_all = QtGui.QPushButton('SELECT ALL')\nstream_none = QtGui.QPushButton('SELECT NONE')\nw6.addWidget(uart_update, row=2, col=0, colspan=3)\nw6.addWidget(stream_update, row=3, col=0)\nw6.addWidget(stream_all, row=3, col=1)\nw6.addWidget(stream_none, row=3, col=2)\nd6.addWidget(w6)\n\nw2 = pg.console.ConsoleWidget(namespace={\"np\": np, \"uart\": serial_daemon.stdin})\nd2.addWidget(w2)\n\n## Hide title bar on dock 3\nd3.hideTitleBar()\nw3 = pg.PlotWidget(title=\"Live Raw Data Stream\")\nw3.showGrid(10, 10, 100)\nd3.addWidget(w3)\n# Add status to d4\nw4 = pg.LayoutWidget()\nw4_label = QtGui.QLabel(\"STATUS: UNKNOWN\")\nw4_return = QtGui.QLabel(\"\")\nw4_textbox = QtGui.QLineEdit()\nw4_label.setAlignment(QtCore.Qt.AlignCenter)\nw4.addWidget(w4_label, row=0, col=0, rowspan=3, colspan=2)\nw4.addWidget(w4_textbox, row=3, col=0, rowspan=1, colspan=2)\nd4.addWidget(w4)\n\n\ndef stream_settings_update():\n global COLOR_MATRIX, CURVE_LIST, BUFFER_SIZE\n if BUFFER_SIZE != int(p.param('Plot Settings', 'Buffer size').value()):\n BUFFER_SIZE = int(p.param('Plot Settings', 'Buffer size').value())\n for idx, arr in enumerate(DATA_MATRIX):\n DATA_MATRIX[idx] = np.zeros(BUFFER_SIZE)\n for idx in range(len(DATA_MATRIX)):\n COLOR_MATRIX[idx] = p.param('Streams', 'Stream %i' % (idx + 1), 'Color').value()\n if DRAW_MASK[idx]:\n CURVE_LIST[idx].setPen(COLOR_MATRIX[idx])\n DRAW_MASK[idx] = p.param('Streams', 'Stream %i' % (idx + 1)).value()\n # w3.autoRange(items=CURVE_LIST)\n update_curvelist()\n gc.collect()\n\n\ndef update_curvelist():\n global w3\n w3.clear()\n for idx, DATA_WINDOW in enumerate(DATA_MATRIX):\n if DRAW_MASK[idx]:\n CURVE_LIST[idx] = w3.plot(DATA_WINDOW, pen=COLOR_MATRIX[idx])\n else:\n CURVE_LIST[idx] = None\n\n\ndef set_all_streams_active():\n global p\n for idx, DATA_WINDOW in enumerate(DATA_MATRIX):\n p.param(\"Streams\", \"Stream %i\" % (idx + 1)).setValue(True)\n\n\ndef set_all_streams_inactive():\n global p\n for idx in range(len(DATA_MATRIX)):\n p.param(\"Streams\", \"Stream %i\" % (idx + 1)).setValue(False)\n\ndef update_UART_list():\n uart_p.param(\"UART Characteristics\", \"Port location\").setLimits([i.device for i in list_ports.comports()])\n\ndef update_w3_state():\n global w3\n w3.getPlotItem().setTitle(\"Live Raw Data Stream: %s\"%uart_p.param(\"UART Characteristics\", \"Port location\").value())\n w3.update()\n\nupdate_curvelist()\nupdate_UART_list()\nupdate_w3_state()\n# uart_update.clicked.connect()\nstream_update.clicked.connect(stream_settings_update)\nstream_all.clicked.connect(set_all_streams_active)\nstream_none.clicked.connect(set_all_streams_inactive)\n\n\ndef update():\n global CURVE_LIST, uart_p\n if read_q.qsize() > 1e6:\n read_q.queue.clear()\n print(\"ALERT :: %s: Flushed queue to preserve memory. Indicates over-capacity throughput.\"%time.clock())\n else:\n update_data()\n for idx, DATA_WINDOW in enumerate(DATA_MATRIX):\n if CURVE_LIST[idx] != None:\n CURVE_LIST[idx].setData(DATA_WINDOW)\n\ndef update_data():\n global DATA_MATRIX, w4_label, STATUS_STATE, SIGNAL_STATE, SIGNAL_PERIOD, LAST_TIME\n print(read_q.qsize())\n try:\n line = read_q.get_nowait()\n gc.collect()\n except Empty:\n SIGNAL_STATE = \"L.O.S. @ T = %.03f\" % (time.clock())\n return\n try:\n in_data = struct.unpack(\"1I13f\", line)\n SIGNAL_PERIOD = in_data[1] - LAST_TIME\n LAST_TIME = in_data[1]\n if in_data[0] == 1096040772:\n data_point = in_data[2:]\n else:\n raise struct.error\n except struct.error as e:\n SIGNAL_STATE = \"INVALID SIGNAL\"\n print(e)\n else:\n SIGNAL_STATE = \"CONNECTED\"\n for idx, DATA_WINDOW in enumerate(DATA_MATRIX):\n DATA_MATRIX[idx] = np.roll(DATA_WINDOW, -1)\n if DRAW_MASK[idx]:\n DATA_MATRIX[idx][-1] = data_point[idx]\n else:\n DATA_MATRIX[idx][-1] = 0\n w4_label.setText(\"STATUS: %s\\nSIGNAL STATE: %s\\nSIGNAL PERIOD: %6.03f ms/sample\" % (\n STATUS_STATE, SIGNAL_STATE, SIGNAL_PERIOD * 1000.0))\n\n\ntimer = QtCore.QTimer()\ntimer.timeout.connect(update)\ntimer.start(0)\n\nuart_updater = QtCore.QTimer()\nuart_updater.timeout.connect(update_UART_list)\nuart_updater.start(2000)\n\nwin.show()\n\n## Start Qt event loop unless running in interactive mode or using pyside.\nif __name__ == '__main__':\n import sys\n\n if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):\n QtGui.QApplication.instance().exec_()\n","sub_path":"Realtime-visualization/realtime-vis.py","file_name":"realtime-vis.py","file_ext":"py","file_size_in_byte":12665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112069227","text":"# Students: David Wen, Alex Romriell, Jacob Pollard\n# MSAN 630 ML 2 Project Emotobot\n\nfrom glob import glob\nimport numpy as np\nimport seaborn\nimport matplotlib.pyplot as plt\n\n# STYLES = plt.style.available\n\nCSVDIR = \"/Users/jtpollard/MSAN/msan630/Emotobot/csvfiles/\"\nPLOTSDIR = \"/Users/jtpollard/MSAN/msan630/Emotobot/plots/\"\n\n\ndef get_csvfiles(csvdir):\n \"\"\"\n -get the csv files from the passed directory\n :param csvdir:\n :return:\n \"\"\"\n csv_filenames = glob('{}*.csv'.format(csvdir))\n\n return csv_filenames\n\n\ndef get_array_from_csv(csvfile):\n \"\"\"\n -read in a csv file containing model diagnostics and return a numpy array\n and the name components for using in the plot titles\n :param csvfile:\n :return:\n \"\"\"\n model_data = np.genfromtxt(csvfile, delimiter=\",\", skip_header=1)\n plot_title = csvfile.split(\"/\")[-1].split(\".\")[0].split(\"_\")[3:5]\n\n return model_data, plot_title\n\n\n\nif __name__ == \"__main__\":\n\n emotions = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'surprise', 'unhappy']\n\n color_map = dict()\n color_map['angry'] = 'red'\n color_map['disgust'] = 'green'\n color_map['fear'] = 'purple'\n color_map['happy'] = 'y'\n color_map['neutral'] = 'black'\n color_map['surprise'] = 'pink'\n color_map['unhappy'] = 'blue'\n\n # dict for the name of the expression to show on the graph\n graph_emos = dict()\n graph_emos['angry'] = 'Anger'\n graph_emos['disgust'] = 'Disgust'\n graph_emos['fear'] = 'Fear'\n graph_emos['happy'] = 'Happiness'\n graph_emos['neutral'] = 'Neutrality'\n graph_emos['surprise'] = 'Surprise'\n graph_emos['unhappy'] = 'Sadness'\n\n\n csv_files = get_csvfiles(CSVDIR)\n # print csv_files\n\n model_data = list()\n title_emos = list()\n for c in csv_files:\n df, tl = get_array_from_csv(c)\n model_data.append(df)\n title_emos.append(tl)\n\n n = len(model_data)\n\n for i in range(n):\n\n plt.clf()\n plt.style.use('seaborn-notebook')\n plt.rcParams['xtick.labelsize'] = 15\n plt.rcParams['ytick.labelsize'] = 15\n plt.xlabel('Number of Epochs', fontsize=15)\n plt.ylabel('Cross Entropy Loss', fontsize=15)\n # plt.title('Cross Entropy Loss for Model Classifying\\n'\n # 'Faces Expressing {} vs {}'.format(graph_emos[title_emos[i][0]], graph_emos[title_emos[i][1]]))\n epochs = model_data[i][:, 0]\n train_loss = model_data[i][:, 1]\n test_loss = model_data[i][:, 2]\n plt.plot(epochs, train_loss, color=\"blue\", label=\"Train\")\n plt.plot(epochs, test_loss, color=\"darkorange\", label=\"Test\")\n plt.legend(loc=\"best\", prop={'size': 20})\n savepath = PLOTSDIR + \"val_curve_{}_{}.png\".format(title_emos[i][0], title_emos[i][1])\n plt.savefig(savepath, dpi=500, bbox_inches=\"tight\")\n # plt.show()\n\n","sub_path":"Emotobot-/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"118159567","text":"from time import sleep\n\nimport pytest\n\n\n@pytest.fixture\ndef internal_ip(mocker):\n return lambda page, interface, ip: mocker.patch(\n f\"pt_miniscreen.pages.network.{page}.get_internal_ip\",\n lambda iface: ip if interface == iface else \"No IP address\",\n )\n\n\n@pytest.fixture(autouse=True)\ndef setup(miniscreen):\n # enter network menu\n miniscreen.down_button.release()\n sleep(1)\n miniscreen.down_button.release()\n sleep(1)\n miniscreen.select_button.release()\n sleep(1)\n\n\ndef test_wifi(miniscreen, snapshot, internal_ip, mocker):\n snapshot.assert_match(miniscreen.device.display_image, \"disconnected.png\")\n\n internal_ip(page=\"wifi\", interface=\"wlan0\", ip=\"192.168.192.168\")\n mocker.patch(\n \"pt_miniscreen.pages.network.wifi.get_wifi_network_ssid\",\n return_value=\"VM3409662\",\n )\n mocker.patch(\n \"pt_miniscreen.components.wifi_strength.get_network_strength\",\n return_value=\"80%\",\n )\n sleep(2)\n snapshot.assert_match(miniscreen.device.display_image, \"connected.png\")\n\n\ndef test_ethernet(miniscreen, snapshot, internal_ip):\n # scroll to ethernet page\n miniscreen.down_button.release()\n sleep(1)\n\n snapshot.assert_match(miniscreen.device.display_image, \"disconnected.png\")\n\n internal_ip(page=\"ethernet\", interface=\"eth0\", ip=\"10.255.10.255\")\n sleep(2)\n snapshot.assert_match(miniscreen.device.display_image, \"connected.png\")\n\n\ndef test_ap(miniscreen, snapshot, mocker):\n # scroll to ap page\n miniscreen.down_button.release()\n sleep(1)\n miniscreen.down_button.release()\n sleep(1)\n\n snapshot.assert_match(miniscreen.device.display_image, \"disconnected.png\")\n\n mocker.patch(\n \"pt_miniscreen.pages.network.ap.get_ap_mode_status\",\n return_value={\n \"ssid\": \"pitop1234\",\n \"passphrase\": \"12345678\",\n \"ip_address\": \"172.31.172.31\",\n },\n )\n sleep(2)\n snapshot.assert_match(miniscreen.device.display_image, \"connected.png\")\n\n\ndef test_usb(miniscreen, snapshot, internal_ip):\n # scroll to usb page\n miniscreen.down_button.release()\n sleep(1)\n miniscreen.down_button.release()\n sleep(1)\n miniscreen.down_button.release()\n sleep(1)\n\n snapshot.assert_match(miniscreen.device.display_image, \"disconnected.png\")\n\n internal_ip(page=\"usb\", interface=\"ptusb0\", ip=\"192.168.0.1\")\n sleep(2)\n snapshot.assert_match(miniscreen.device.display_image, \"connected.png\")\n","sub_path":"tests/network_test.py","file_name":"network_test.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26222363","text":"#coding: utf-8\n\"\"\"小程序-明星计算器\"\"\"\nimport math\nfrom lweb import request, abort, redirect\nfrom utils import db, rds1, get_ip, neo, casts, ajax, Struct, trs, trmany, trw\nimport utils\nfrom apps import common\nfrom apps.api import user as api_user\nfrom apps.api import wx_mc_func_star_login as api_wx_mc_func_star_login, micro_func_star as api_micro_func_star\n\ndef r_mc_index():\n \"\"\"\n 主页 http://www.linkeddb.org/mc_index/\n :return:\n \"\"\"\n return 'mc index'\n\n\ndef r_mc_sign():\n \"\"\"\n 授权登录 http://www.ldba.org/mc_sign/\n post请求code, encryptedData,iv,nickName,avatarUrl,\n \"\"\"\n args = casts(request.forms, code=str, encryptedData=str, iv=str, nickName=str, avatarUrl=str)\n if not args.code or not args.encryptedData or not args.iv or not args.nickName or not args.avatarUrl:\n return ajax.err(msg='args err: code / encryptedData / iv / nickName / avatarUrl')\n wx_sess_info = api_wx_mc_func_star_login.jscode2session(args.code, 1)\n user_info = {'nickName': args.nickName, 'avatarUrl': args.avatarUrl}\n de_info = None\n if wx_sess_info:\n if wx_sess_info.unionid: #有union id\n user_info['unionId'] = wx_sess_info.unionid\n else: #无union id\n de_info = api_wx_mc_func_star_login.AES_decode(args.encryptedData, wx_sess_info.session_key, args.iv, 1)\n if de_info:\n user_info['unionId'] = de_info['unionId']\n #print('wx_sess_info:', wx_sess_info)\n #print('de_info:', de_info)\n if user_info.get('unionId'):\n err, id, uoid = api_user.reg_or_log_micro_func_star(user_info)\n if err:\n return ajax.err(msg=err)\n return ajax.suc(data={'user_oid': uoid}, msg='操作成功')\n return ajax.err(msg='err: last')\n\n\n","sub_path":"py-微信-授权登录/micro_func_star.py","file_name":"micro_func_star.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"481119845","text":"'''\nCreated By: Bazil Muzaffar Kotriwala\nTimestamp: 1:14PM 15 Mar - 17\n'''\n\n\ndef convert_perm(perm1, perm2):\n '''\n This function takes any two permutations of a finite set of distinct letters and returns as an answer the smallest no of transpositions required to convert\n from one perm to another.\n :param: Two permutation strings which can both be converted to each other or vice versa\n :precondition:\n :postconditon: We get the smallest no of (adjacent) transpositions required to convert from one perm to the other or vice versa\n :return: The smallest number of (adjacent) transpositions required to convert from one perm to the other or vice versa are returned\n :complexity: Best Case = Worst Case = O(n^2), where n is the length of the base_string list\n '''\n\n basestring_list = []\n s_no_of_transpositions = 0\n for letter in perm1:\n basestring_list.append(letter)\n for letter in perm2:\n for i in range(len(basestring_list)):\n if letter == basestring_list[i]:\n s_no_of_transpositions += i\n basestring_list.pop(i)\n break\n return s_no_of_transpositions\n\n\nif __name__ == '__main__':\n perm1 = input('Enter permutation string 1: ')\n perm2 = input('Enter permutation string 2: ')\n file = open('Q2_Output.txt', 'w')\n file.write('Input Permutation 1 = ' + perm1 + '\\n' + 'Input Permutation 2 = ' + perm2 + '\\n' + 'Output (smallest number of inversion) = ' + str(convert_perm(perm1,perm2)))\n\n","sub_path":"Algorithms/Permutations - Sum base digits, Matrices, Inversions/min_transpositions.py","file_name":"min_transpositions.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"103080470","text":"# Copyright (c) 2016 Luke San Antonio Bialecki\n# All rights reserved.\n\nimport pytz\nfrom pytz import timezone\nfrom datetime import datetime\nfrom enum import Enum\n\nimport msgpack\n\nfrom . import rules, DATE_FMT, date_to_str, str_to_date\nfrom .timeutil import SECONDS_PER_DAY, LocalizedDateUtil\n\n\n# We can't use lowercase pass so just make them capital\nclass ObjType(Enum):\n User = 1\n Pass = 2\n\n\nclass LiveObj:\n \"\"\"Represents a pass or a user in a queue (with a request token).\"\"\"\n\n def __init__(self, ty, obj_id, obj_token):\n self.ty = ty\n self.id = obj_id\n self.token = obj_token\n\n @classmethod\n def fromstring(self, obj_str, ty):\n id, token = tuple(obj_str.split(':'))\n return LiveObj(ty, int(id), int(token))\n\n def __str__(self):\n return '{}:{}'.format(self.id, self.token)\n\n def __bytes__(self):\n return str(self).encode()\n\n\ndef _obj_exists(r, queue, obj):\n \"\"\"Returns whether the obj exists in the given queue.\"\"\"\n size = r.llen(queue)\n\n # No reason to call lrange if we aren't even dealing with a list, for\n # example.\n if size == 0:\n return False\n\n ###\n # Hopefully this isn't so wildly inefficient that it blows up in our\n # face later.\n ###\n contents = r.lrange(queue, 0, size)\n\n # Make sure to use bytes so that comparisons work.\n return True if bytes(obj) in contents else False\n\n\nclass FixedDaystate:\n def __init__(self, date, state_id):\n self.date = date\n self.state_id = state_id\n\n @classmethod\n def fromstring(cls, str, tz=None):\n date, state_id = tuple(str.split(':'))\n return FixedDaystate(str_to_date(date, tz), int(state_id))\n\n def __str__(self):\n return date_to_str(self.date) + ':' + str(self.state_id)\n\n def __eq__(self, other):\n return (self.date.year == other.date.year and\n self.date.month == other.date.month and\n self.date.day == other.date.day and\n self.state_id == other.state_id)\n\n def __ne__(self, other):\n return not self == other\n\n\nclass InvalidFixDate(Exception):\n def __init__(self):\n pass\n\n\nclass LiveOrg:\n \"\"\"This class manages live org data.\n\n This stuff _will not_ go into the database anytime soon (in its current\n form). It _will_ be used extensively by our background worker.\n\n \"\"\"\n\n def __init__(self, redis, org):\n self.r = redis\n\n # Can we make this immutable? That way we don't have to call the\n # active_queue_set and friend functions over and over.\n self.org_id = org.id\n self.timezone = timezone(org.timezone)\n self.date_util = LocalizedDateUtil(self.timezone)\n\n ###\n # Names of redis keys\n ###\n def _active_queue_set(self):\n \"\"\"Returns the name of the active queue set for this org.\"\"\"\n return str(self.org_id) + ':active-queues-set'\n\n def _active_queue_temp_set(self):\n return str(self.org_id) + ':active-queues-temp-set'\n\n def _active_queue_diff_set(self):\n return str(self.org_id) + ':active-queues-diff-set'\n\n def _active_queue_list(self):\n \"\"\"Returns the name of the active queue list for this org.\"\"\"\n return str(self.org_id) + ':active-queues-list'\n\n def _borrow_queue(self, day):\n \"\"\"Returns name of a day's borrow queue.\"\"\"\n return str(self.org_id) + ':' + date_to_str(day) + ':borrow'\n\n def _lend_queue(self, day):\n \"\"\"Returns name of a day's lend queue.\"\"\"\n return str(self.org_id) + ':' + date_to_str(day) + ':lend'\n\n def _user_token_hash(self):\n \"\"\"Returns the name of the hash containing user tokens.\"\"\"\n return str(self.org_id) + ':user-tokens'\n\n def _pass_token_hash(self):\n \"\"\"Returns the name of the hash containing pass tokens.\"\"\"\n return str(self.org_id) + ':pass-tokens'\n\n def _fixed_daystates_list(self):\n return str(self.org_id) + ':fixed-daystates'\n\n def _current_state_cache(self):\n return str(self.org_id) + ':current-state-cache'\n\n def _daystate_sequence(self):\n return str(self.org_id) + ':daystate-sequence'\n\n def _reoccurring_rule_list(self):\n return str(self.org_id) + ':global-rules'\n\n def _single_use_rule_bucket(self):\n return str(self.org_id) + ':single-rules'\n\n def _token_hash(self, ty):\n if ty == ObjType.User:\n return self._user_token_hash()\n elif ty == ObjType.Pass:\n return self._pass_token_hash()\n else:\n return None\n\n ###\n # Functions for a worker\n ###\n\n def cycle_active_queue(self):\n \"\"\"Returns a queue that needs to be processed.\n\n The result is pumped atomically using the redis command RPOPLPUSH, which\n means the queues will eventually repeat but multiple workers can call\n this all at once, etc.\n\n Returns the string name of a queue.\n\n \"\"\"\n return self.r.rpoplpush(\n self._active_queue_list(), self._active_queue_list()\n )\n\n def reconcile_active_queue(self):\n def find_missing_queues(pipe):\n # Get the contents of the list\n length = self.r.llen(self._active_queue_list())\n contents = self.r.lrange(self._active_queue_list(), 0, length)\n\n pipe.multi()\n\n # Clear the temporary set.\n # As long as the list doesn't change we don't need to worry, the set\n # will not have duplicates, etc.\n pipe.delete(self._active_queue_temp_set())\n\n # Add the contents of the active queue *list* to this temporary set.\n pipe.sadd(self._active_queue_temp_set(), *contents)\n\n # Check if any elements are in the set but not the list.\n pipe.sdiff(self._active_queue_diff_set(),\n self._active_queue_set(),\n self._active_queue_temp_set())\n\n # Watch the list, if it changes, it's all over. Furthermore, if the set\n # changes, we need to give it time for the list to change too so we\n # don't think its not there when it was going to eventually be there and\n # we just added a queue twice. Honestly this isn't the end of the world,\n # because it will eventually be removed (hopefully).\n num_missing = self.r.transaction(find_missing_queues,\n self._active_queue_list(),\n self._active_queue_set())[2]\n\n def add_missing_queues(pipe):\n # Add the elements missing from the list to the list.\n contents = pipe.smembers(self._active_queue_diff_set())\n\n pipe.multi()\n pipe.lpush(self._active_queue_list(), *contents)\n pipe.execute()\n\n if num_missing > 0:\n # If members were missing we need to add them!\n self.r.transaction(add_missing_queues,\n self._active_queue_diff_set(),\n self._active_queue_set(),\n self._active_queue_list())\n\n ###\n # Functions for web service\n ###\n def _activate_day_queue(self, day):\n day_str = date_to_str(day)\n\n def activate_queue(pipe):\n # Is this queue already active?\n is_member = pipe.sismember(self._active_queue_set(), day_str)\n\n pipe.multi()\n if is_member == 0:\n # Add the date to the set and list\n pipe.sadd(self._active_queue_set(), day_str)\n pipe.lpush(self._active_queue_list(), day_str)\n\n self.r.transaction(activate_queue,\n self._active_queue_set(),\n self._active_queue_list())\n\n def _deactivate_day_queue(self, day):\n day_str = date_to_str(day)\n\n def deactivate_queue(pipe):\n # Is this queue active?\n is_member = pipe.sismember(self._active_queue_set(), day_str)\n\n pipe.multi()\n if is_member == 1:\n # Remove the date to the set and list\n pipe.srem(self._active_queue_set(), day_str)\n pipe.lrem(self._active_queue_list(), 1, day_str)\n\n self.r.transaction(deactivate_queue,\n self._active_queue_set(),\n self._active_queue_list())\n\n def obj_token(self, ty, id, r=None):\n \"\"\"Returns the token of an object given its ID and type.\n\n It does so by querying into a specific redis set (hash) based on the\n type of the object. If the token doesn't exist, a new token is added.\"\"\"\n # Possibly use a different redis interface, like a pipeline\n if r is None:\n r = self.r\n\n # Which hash has our token?\n hash_str = self._token_hash(ty)\n if hash_str is None:\n return None\n\n # Add a token if it's not already there.\n r.hsetnx(hash_str, str(id), 1)\n\n # Query the token\n return r.hget(hash_str, str(id))\n\n def live_obj(self, ty, id, r=None):\n \"\"\"Returns a live object (with a token) from an ID and type.\"\"\"\n token = self.obj_token(ty, id, r)\n if token is None:\n # stderr warn?\n return None\n\n return LiveObj(ty, id, int(token))\n\n\n def live_user(self, id, r=None):\n return self.live_obj(ObjType.User, id, r)\n\n def live_pass(self, id, r=None):\n return self.live_obj(ObjType.Pass, id, r)\n\n def _refresh_obj_token(self, queue_name, obj_type, obj_id):\n \"\"\"Updates an object token and moves it to the back of the queue.\n\n This function is arguably doing more than one thing and therefore isn't\n a very good function, but I ended up coupling the operations so they can\n be done atomically. In that sense, they are very much coupled. Plus, if\n we give this function more information, that means there is less that\n has to be duplicated between refresh_user and refresh_pass, etc. It's\n either that or I just need sleep.\n\n \"\"\"\n\n def refresh_obj(pipe):\n\n # Get the current user token\n old_token = self.obj_token(obj_type, obj_id, r=pipe)\n\n # Update the token\n pipe.hincrby(self._token_hash(obj_type), str(obj_id), 1)\n\n # What's the new object supposed to look like?\n new_obj = self.live_obj(obj_type, obj_id, r=pipe)\n\n # Get the current state of the queue\n length = pipe.llen(queue_name)\n queue_contents = pipe.lrange(queue_name, 0, length)\n\n pipe.multi()\n\n for obj_str in queue_contents:\n # Get the ID and token from the string\n cur_obj = LiveObj.fromstring(obj_str)\n if cur_obj.id == new_obj.id and cur_obj.token != new_obj.token:\n # The object needs to be updated, because its token doesn't\n # match the new token we were given.\n\n if cur_obj.token != old_token and old_token != None:\n # We don't recognize this token!\n # TODO: Add a stderr warning here.\n pass\n\n # Make sure we move them to the back of the queue, if they\n # refreshed their token it means they should go to the back\n # of the line.\n\n # Remove the object.\n pipe.lrem(queue_name, 0, obj_str)\n\n # Add the obj to the back of the queue with a new token.\n pipe.lpush(queue_name, bytes(new_obj))\n\n self.r.transaction(refresh_obj, queue_name)\n\n def refresh_user(self, date, user_id):\n \"\"\"Updates a borrow token and moves it to the back of the queue.\"\"\"\n self._refresh_obj_token(\n self._borrow_queue(date), ObjType.User, user_id\n )\n\n def refresh_pass(self, date, pass_id):\n \"\"\"Updates a lend token and moves it to the back of the queue.\"\"\"\n self._refresh_obj_token(\n self._borrow_queue(date), ObjType.Pass, pass_id\n )\n\n def _enqueue_obj(self, queue, obj, check_existing=True):\n \"\"\"Adds an object to a queue, if it doesn't already exist.\n\n Returns whether or not the object was enqueued, if this is false it\n means the object was already in the queue, which is fine, it was left\n where it was.\n \"\"\"\n\n def enqueue(pipe):\n if check_existing:\n exists = _obj_exists(pipe, queue, obj)\n else:\n exists = False\n\n if not exists:\n # Add the object to the back of the queue\n\n ### IMPORTANT ### IMPORTANT ### IMPORTANT\n # The left side of the list is considered the back of the queue.\n # Don't forget to pop from the right with rpop.\n ### IMPORTANT ### IMPORTANT ### IMPORTANT\n\n pipe.lpush(queue, bytes(obj))\n\n return True\n return False\n\n return self.r.transaction(enqueue, queue, value_from_callable=True)\n\n def _dequeue_obj(self, queue, obj):\n \"\"\"Removes an object from a queue.\n\n Returns whether or not the object was removed.\n \"\"\"\n\n # TODO: Remove objects with an old token (do this by searching the\n # list and looking at every obj. We could issue a warning if the token\n # is different.\n # TODO: Remove objects by ID, not entire object because that would be\n # dependent on the token, etc.\n removed = self.r.lrem(queue, 1, bytes(obj))\n return True if removed > 0 else False\n\n def enqueue_user_borrow(self, date, user_id):\n # Active the queue if necessary\n self._activate_day_queue(date)\n # Enqueue the user onto the borrow queue\n return self._enqueue_obj(\n self._borrow_queue(date), self.live_user(user_id)\n )\n\n def dequeue_user_borrow(self, date, user_id):\n # TODO: Deactivate the queue if necessary (if it's empty).\n # Dequeue the pass from the borrow queue\n return self._dequeue_obj(\n self._borrow_queue(date), self.live_user(user_id)\n )\n\n def enqueue_pass_lend(self, date, pass_id):\n # Active the queue if necessary\n self._activate_day_queue(date)\n # Enqueue the pass onto the lend queue\n return self._enqueue_obj(\n self._lend_queue(date), self.live_pass(pass_id)\n )\n\n def dequeue_pass_lend(self, date, pass_id):\n # TODO: Deactivate the queue if necessary (if it's empty).\n # Dequeue the pass from the lend queue\n return self._dequeue_obj(\n self._lend_queue(date), self.live_pass(pass_id)\n )\n\n def set_state_sequence(self, state_ids):\n # We're using a string here because we don't really want a redis list.\n # The states list shouldn't get too big and it's more convenient to just\n # modify it in memory.\n state_ids = map(lambda x: str(x), state_ids)\n self.r.set(self._daystate_sequence(), ','.join(state_ids))\n\n def get_state_sequence(self):\n try:\n seq = self.r.get(self._daystate_sequence())\n if seq is None:\n return []\n return list(map(lambda x: int(x), seq.decode('utf-8').split(',')))\n except ValueError:\n return []\n\n def push_fixed_daystate(self, new_fixed_daystate):\n \"\"\"Fixes a date to a particular day state\n\n Behavior is undefined when the fixed state given is older than the\n newest fix in the list.\n \"\"\"\n daystate_queue = self._fixed_daystates_list()\n current_state_cache = self._current_state_cache()\n\n def do_push(pipe):\n # Make sure the new date is more recent then the previous date in\n # the queue. If we go backwards in time, expect issues.\n\n current_fix = pipe.lindex(daystate_queue, 0)\n\n if current_fix is not None:\n current_fixed_daystate = FixedDaystate.fromstring(\n current_fix, self.timezone\n )\n if new_fixed_daystate.date < current_fixed_daystate.date:\n # The new fix comes before the one already there.\n\n # Either throw an error or adjust the last fix to match\n # what this fix will effect. This seems unexpected, so just\n # throw an error for now.\n raise InvalidFixDate()\n\n pipe.multi()\n\n # Remove all cached daystate ids from the new fixed daystate onward.\n pipe.zremrangebyscore(\n current_state_cache, new_fixed_daystate.date.timestamp(), '+inf'\n )\n # Push the new daystate\n pipe.lpush(daystate_queue, str(new_fixed_daystate))\n\n self.r.transaction(do_push, daystate_queue, current_state_cache)\n\n def get_last_fixed_daystate(self):\n return FixedDaystate.fromstring(\n self.r.lindex(self._fixed_daystates_list(), 0).decode('utf-8'),\n self.timezone\n )\n\n def push_rule_set(self, rule_set: rules.RuleSet):\n def rule_str(rs, timestamp):\n new_rules = rs.rules\n if not isinstance(rs.rules, list):\n # Make sure we have a list of rules instead of a single value.\n new_rules = [rs.rules]\n return msgpack.packb([rs._replace(rules=new_rules), timestamp])\n\n if rules.pattern_reoccurs(rule_set.pattern):\n # Push to the top of the reoccurring rules list\n # Use the current UTC timestamp because we don't want daylight\n # savings or other stupid time oddity to cause a duplicate.\n time = int(datetime.now(pytz.utc).timestamp())\n self.r.lpush(\n self._reoccurring_rule_list(), rule_str(rule_set, time)\n )\n\n else:\n # Add the one-day pattern to the set sorting by timestmap.\n time = int(str_to_date(rule_set.pattern, self.timezone).timestamp())\n # Add the timestamp to the rule set and add it to the sorted set.\n self.r.zadd(\n self._single_use_rule_bucket(), time, rule_str(rule_set, time)\n )\n\n def _strip_time_stamp_from_msgpack(self, rule_sets_in):\n rule_sets = []\n for item in rule_sets_in:\n # Strip out the timestamp from all the input rule sets.\n rule_sets.append(item[0])\n\n return rule_sets\n\n def get_reoccurring_rule_sets(self, convert=True):\n res = self.r.lrange(self._reoccurring_rule_list(), 0, -1)\n\n return rules.convert_rules(\n self._strip_time_stamp_from_msgpack(res)\n ) if convert else res\n\n def get_single_use_rule_sets(self, start_time=None, end_time=None,\n convert=True):\n # Don't force the client to pick a limit.\n if start_time is None:\n start_time = '-inf'\n if end_time is None:\n end_time = '+inf'\n\n res = self.r.zrangebyscore(\n self._single_use_rule_bucket(), start_time, end_time\n )\n\n return rules.convert_rules(\n self._strip_time_stamp_from_msgpack(res)\n ) if convert else res\n\n def remove_reoccuring_rule_set(self, pattern):\n reoccurring = self.get_reoccurring_rule_sets(convert=False)\n indices=[i for i, rs in enumerate(reoccurring) if rs.pattern == pattern]\n removed = 0\n for i in indices:\n # Find the value\n element = self.r.lindex(indices)\n # Remove it from the list\n removed += self.r.lrem(self._reoccurring_rule_list(), 1, element);\n\n return removed\n\n def remove_single_use_rule_set(self, date):\n if isinstance(date, str):\n date = str_to_date(date)\n time = date.timestamp()\n return self.r.zremrangebyscore(\n self._single_use_rule_bucket(), time, time\n )\n\n def remove_rule_set(self, pattern):\n if rules.pattern_reoccurs(pattern):\n self.remove_reoccuring_rule_set(pattern)\n else:\n self.remove_single_use_rule_set(pattern)\n\n def get_rule_set(self, date):\n # Find the operative rule set for a particular day.\n start_time = date.timestamp()\n rule_sets = self.get_single_use_rule_sets(\n start_time, start_time + SECONDS_PER_DAY\n )\n\n # Add reoccurring dates that could match any given date\n rule_sets.extend(self.get_reoccurring_rule_sets())\n\n # Return the first one that matches\n for rs in rule_sets:\n if rules.pattern_matches_date(rs.pattern, date):\n return rs\n\n # No rule set matched\n return None\n\n def get_daystate_id(self, target_date):\n # Get the latest date in the cache already, if there is none use the\n # last fixed daystate.\n\n # Don't forget that what we get is actually id:timestamp where\n # timestamp is the timestamp used as the score. This is used to prevent\n # the state from being overwritten later on when the daystates go and\n # repeat themselves.\n latest_entry = self.r.zrevrank(self._current_state_cache(), -1)\n if latest_entry is not None:\n latest_state_id = int(latest_entry.split(':')[0])\n cur_timestamp = self.r.zscore(latest_entry)\n else:\n # Use the most recent daystate\n fixed_day = self.get_last_fixed_daystate()\n cur_timestamp = fixed_day.date.timestamp()\n latest_state_id = fixed_day.state_id\n\n # Find list of daystates\n daystate_seq = self.get_state_sequence()\n # Find the starting index\n curstate_i = daystate_seq.index(latest_state_id)\n\n # Now move forward by a day, we already know today's daystate.\n cur_timestamp += SECONDS_PER_DAY\n\n # Go forward day by day looking at the operative rule set, counting the\n # amount of times it needs to be incremented.\n while cur_timestamp < target_date.timestamp() + SECONDS_PER_DAY:\n # Get the rule set for this day\n current_date = self.timezone.localize(\n datetime.fromtimestamp(cur_timestamp)\n )\n rule_set = self.get_rule_set(current_date)\n if rule_set.incrday:\n curstate_i = (curstate_i + 1) % len(daystate_seq)\n\n # Cache the daystate on this day (after processing incrday).\n # Find some way to add NX in there which prevents new items from\n # being created, but redis-py doesn't support it.\n self.r.zadd(self._current_state_cache(), cur_timestamp,\n '{}:{}'.format(curstate_i, cur_timestamp))\n\n # Move on to the next day\n cur_timestamp += SECONDS_PER_DAY\n\n return daystate_seq[curstate_i]\n","sub_path":"inpassing/worker/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":22998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"422473878","text":"\n# coding: utf-8\n\n# In[27]:\n\n## === arrayの作成 === ### \nimport numpy as np\nfrom sklearn.cross_validation import train_test_split\n\nnp.random.seed(9)\n# 男女のタグ付きひらがなの名前データを読み込む\ntxtbody = open(\"data/names.txt\", encoding='utf-8')\n# Numpyのarrayに変換\njnames = np.array([x.split() for x in txtbody], dtype='U12')\nnames_train, gender_train = jnames[:, 1], jnames[:, 0]\n\n\n# In[28]:\n\n## === split_in_2words()関数の定義 === ###\ndef split_in_2words(name):\n return [name[i:i+2] for i in range(len(name)-1)]\n\nsplit_in_2words(\"とものり\")\n#split_in_2words(\"え\")\n\n\n# In[29]:\n\n# CountVectorizerオブジェクトの作成\nfrom sklearn.feature_extraction.text import CountVectorizer\nbow_t = CountVectorizer(analyzer=split_in_2words).fit(names_train)\n\nname = \"かんかん\"\nb1 = bow_t.transform([name])\n\n# print(bow_t.get_feature_names()[283])\n# print(bow_t.get_feature_names()[1898])\n\nnames_bow = bow_t.transform(names_train)\n# print(names_bow)\ntype(names_bow)\n\n\n# In[30]:\n\n# TfidfTransformerオブジェクトの生成\nfrom sklearn.feature_extraction.text import TfidfTransformer\ntfidf_t = TfidfTransformer().fit(names_bow)\n\n# 重み付けの実行\ntfidf1 = tfidf_t.transform(b1)\nprint(tfidf1)\n\n\n# In[31]:\n\n## === 学習の実行 === ##\nfrom sklearn.naive_bayes import MultinomialNB\n# 文字列の重み付けと正規化を行う\nnames_tfidf = tfidf_t.transform(names_bow)\n# 学習を実行\nnamegender_detecter = MultinomialNB().fit(names_tfidf, gender_train)\n\nprint(namegender_detecter.predict(tfidf1)[0])\n\n\n# In[43]:\n\ndef predict_gender(name):\n bow = bow_t.transform([name])\n n_tfidf = tfidf_t.transform(bow)\n return namegender_detecter.predict(n_tfidf)[0]\n\nprint(predict_gender(\"のんな\"))\n\n\n# In[ ]:\n\n\n\n","sub_path":"name_distinction.py","file_name":"name_distinction.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274191119","text":"# Created on: 10th September, 2021\n# Author: Bharadwaj Yellapragada\n\n# Day 1: How many days went since I born?\n# Language: Python\n\nimport datetime\n\ndef main():\n date = input(\"Enter your birthday in dd-mm-yyy format: \")\n date_obj = datetime.datetime.strptime(date, '%d-%m-%Y').date()\n today = datetime.date.today()\n print(\"Congratulations!, It's been\",(today-date_obj).days,\"days since you born.\")\n\nif __name__ == '__main__':\n main()","sub_path":"Day 1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"614327397","text":"#importing time to get realtime data for clock\r\nimport time\r\n#importing everything from tkinter for GUI part of clock\r\nfrom tkinter import *\r\n\r\n'''live function is taking realtime data from time.strftime and setting \r\nlabel text as data. 1000ms or 1s is time to update\r\n'''\r\ndef live():\r\n tm = time.strftime(\"%H:%M:%S\")\r\n label.config(text=tm)\r\n label.after(1000, live)\r\n \r\n#initializing tkinter, small gui window\r\nroot = Tk()\r\n#Setting title of GUI window to Cool Clock, default is Tk\r\nroot.title(\"Cool Clock\")\r\n\r\n#Setting data for label. Setting font properties, background color and foreground color\r\nlabel = Label(root, font=(\"\", 100, \"bold\"),\r\n background=\"black\", foreground=\"green\")\r\nlabel.pack(anchor=\"center\")\r\n#live function to get data and load in GUI, also updating time data 1000ms\r\nlive()\r\n#mainloop from tkinter\r\nmainloop()\r\n","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"156011467","text":"#!/usr/bin/env python\n\nimport os\nimport praw\nfrom prawoauth2 import PrawOAuth2Server\nfrom dotenv import load_dotenv, find_dotenv\n\nfrom matchan.core.retriever import Retriever\nimport schedule\n\nfrom pprint import pprint\n\nload_dotenv(find_dotenv())\n\nclass RedditRetriever(object):\n\n def __init__(self):\n user_agent = 'kinow/matchan, by u/kinow'\n self.reddit_client = praw.Reddit(user_agent=user_agent)\n app_key = os.environ.get('reddit_app_client')\n app_secret = os.environ.get('reddit_app_secret')\n scopes = ['read']\n oauthserver = PrawOAuth2Server(self.reddit_client, app_key, app_secret, state=user_agent, scopes=scopes)\n oauthserver.start()\n\n def schedule(self):\n schedule.every(5).minutes.do(self.retrieve)\n return True\n\n def retrieve(self):\n submissions = self.reddit_client.get_front_page(limit=15)\n pprint([str(x) for x in submissions])\n return []\n","sub_path":"matchan/reddit/retriever.py","file_name":"retriever.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"652302076","text":"\"\"\"Core MEANT functions.\"\"\"\n\n\nfrom __future__ import division\nfrom itertools import product\nimport logging\n\nimport munkres\nfrom textblob import TextBlob\n\n\nm = munkres.Munkres()\n\n\ndef costify(similarity_matrix):\n \"\"\"Transform a similarity matrix into a cost matrix.\"\"\"\n return munkres.make_cost_matrix(similarity_matrix, lambda s: 1 - s)\n\n\ndef similarity(one, two, lexsim):\n \"\"\"Return the combined per-word pairwise similarity of the strings\n *one* and *two*.\"\"\"\n one_words = TextBlob(one).words\n two_words = TextBlob(two).words\n word_similarities = [\n [lexsim.similarity(one_word.lower(), two_word.lower())\n for two_word in two_words]\n for one_word in one_words]\n word_alignments = m.compute(costify(word_similarities))\n return (sum(word_similarities[one_index][two_index]\n for one_index, two_index in word_alignments) /\n max(len(one_words), len(two_words)))\n\n\ndef score(hyp_frames, hyp_words, ref_frames, ref_words, lexsim):\n \"\"\"Return the MEANT score for a hypothesis against a reference.\n The *frames* arguments are lists of semantic frame dictionaries as\n returned by ``pymeant.formats.assert_tagger.parse_line()``, while\n the *words* arguments are sequences of the words in each sentence.\n The *lexsim* argument is an object with a ``similarity()`` method\n that can be used to compute the lexical similarity of two words.\"\"\"\n # Handle some edge cases.\n #\n # If both the hypothesis and reference have no frames, the F1 score\n # is 1.0. Give the translators a pat on the back.\n if not hyp_frames and not ref_frames:\n logging.debug('No frames in either hypothesis or reference; '\n 'assigning score of 1.0')\n return 1.0\n # If exactly one of the hypothesis and reference has no frames,\n # either the precision or the recall is 0.0, so the F1 is also 0.0.\n if not hyp_frames or not ref_frames:\n logging.debug('Frames in one of hypothesis or reference, but '\n 'not the other; assigning score of 0.0')\n return 0.0\n\n # Align the frames to each other.\n frame_similarities = [\n [similarity(hyp_frame['TARGET'], ref_frame['TARGET'], lexsim)\n for ref_frame in ref_frames]\n for hyp_frame in hyp_frames]\n frame_alignments = m.compute(costify(frame_similarities))\n\n # \"Possible\" counts include the predicate and all arguments.\n #\n # TODO: Implement weighted normalization.\n hyp_score = ref_score = 0.0\n hyp_possible = ref_possible = 0.0\n for hyp_index, ref_index in frame_alignments:\n hyp_frame = hyp_frames[hyp_index]\n ref_frame = ref_frames[ref_index]\n pred_similarity = frame_similarities[hyp_index][ref_index]\n logging.debug('Aligned hypothesis frame with predicate \"%s\" to '\n 'reference frame with predicate \"%s\" (%f)',\n hyp_frame['TARGET'], ref_frame['TARGET'],\n pred_similarity)\n hyp_coverage = (sum(len(x.split()) for x in hyp_frame.itervalues()) /\n len(hyp_words))\n ref_coverage = (sum(len(x.split()) for x in ref_frame.itervalues()) /\n len(ref_words))\n common_args = (frozenset(hyp_frame) & frozenset(ref_frame) -\n frozenset(['TARGET']))\n arg_similarities = 0.0\n for arg in common_args:\n arg_similarity = similarity(hyp_frame[arg], ref_frame[arg],\n lexsim)\n logging.debug('Aligned hypothesis argument %s \"%s\" to '\n 'reference argument %s \"%s\" (%f)',\n arg, hyp_frame[arg],\n arg, ref_frame[arg], arg_similarity)\n arg_similarities += arg_similarity\n hyp_score += (hyp_coverage * (pred_similarity + arg_similarities) /\n len(hyp_frame))\n ref_score += (ref_coverage * (pred_similarity + arg_similarities) /\n len(ref_frame))\n hyp_possible += hyp_coverage\n ref_possible += ref_coverage\n\n precision = hyp_score / hyp_possible\n recall = ref_score / ref_possible\n if not precision or not recall:\n return 0.0\n return 2 * (precision * recall) / (precision + recall)\n","sub_path":"project/pymeant/meant.py","file_name":"meant.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"206630899","text":"from spb.functions import (\n plot,\n plot_parametric,\n plot_contour,\n plot3d,\n plot3d_parametric_line,\n plot3d_parametric_surface,\n plot_implicit,\n polar_plot,\n geometry_plot,\n)\nfrom spb.plot_data import get_plot_data, smart_plot\n\n# from spb.interactive import iplot\nfrom spb.vectors import vector_plot\nfrom spb.complex.complex import complex_plot\n\n# from spb.backends.plotgrid import plotgrid\n\n# aliases\nparametric_plot = plot_parametric\ncontour_plot = plot_contour\np3d = plot3d\np3dpl = plot3d_parametric_line\np3dps = plot3d_parametric_surface\nimplicit_plot = plot_implicit\nplot_polar = polar_plot\nplot_geometry = geometry_plot\nplot_complex = complex_plot\n\n__all__ = [\n \"plot\",\n \"plot_parametric\",\n \"plot_contour\",\n \"plot3d\",\n \"plot3d_parametric_line\",\n \"plot3d_parametric_surface\",\n \"plot_implicit\",\n \"polar_plot\",\n \"geometry_plot\",\n \"get_plot_data\",\n \"smart_plot\",\n \"vector_plot\",\n \"complex_plot\",\n \"parametric_plot\",\n \"contour_plot\",\n \"p3dpl\",\n \"p3dps\",\n \"p3d\",\n \"implicit_plot\",\n \"plot_polar\",\n \"plot_geometry\",\n \"plot_complex\",\n]\n","sub_path":"spb/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"348355245","text":"from collections import defaultdict\n\nimport torch\n\nfrom fastNLP.core.dataset import DataSet\nfrom fastNLP.core.field import TextField, LabelField\nfrom fastNLP.core.instance import Instance\n\n\nclass Batch(object):\n \"\"\"Batch is an iterable object which iterates over mini-batches.\n\n ::\n for batch_x, batch_y in Batch(data_set):\n\n \"\"\"\n\n def __init__(self, dataset, batch_size, sampler, use_cuda):\n self.dataset = dataset\n self.batch_size = batch_size\n self.sampler = sampler\n self.use_cuda = use_cuda\n self.idx_list = None\n self.curidx = 0\n\n def __iter__(self):\n self.idx_list = self.sampler(self.dataset)\n self.curidx = 0\n self.lengths = self.dataset.get_length()\n return self\n\n def __next__(self):\n \"\"\"\n\n :return batch_x: dict of (str: torch.LongTensor), which means (field name: tensor of shape [batch_size, padding_length])\n batch_x also contains an item (str: list of int) about origin lengths,\n which means (\"field_name_origin_len\": origin lengths).\n E.g.\n ::\n {'text': tensor([[ 0, 1, 2, 3, 0, 0, 0], 4, 5, 2, 6, 7, 8, 9]]), 'text_origin_len': [4, 7]})\n\n batch_y: dict of (str: torch.LongTensor), which means (field name: tensor of shape [batch_size, padding_length])\n All tensors in both batch_x and batch_y will be cuda tensors if use_cuda is True.\n The names of fields are defined in preprocessor's convert_to_dataset method.\n\n \"\"\"\n if self.curidx >= len(self.idx_list):\n raise StopIteration\n else:\n endidx = min(self.curidx + self.batch_size, len(self.idx_list))\n padding_length = {field_name: max(field_length[self.curidx: endidx])\n for field_name, field_length in self.lengths.items()}\n origin_lengths = {field_name: field_length[self.curidx: endidx]\n for field_name, field_length in self.lengths.items()}\n\n batch_x, batch_y = defaultdict(list), defaultdict(list)\n for idx in range(self.curidx, endidx):\n x, y = self.dataset.to_tensor(idx, padding_length)\n for name, tensor in x.items():\n batch_x[name].append(tensor)\n for name, tensor in y.items():\n batch_y[name].append(tensor)\n\n batch_origin_length = {}\n # combine instances into a batch\n for batch in (batch_x, batch_y):\n for name, tensor_list in batch.items():\n if self.use_cuda:\n batch[name] = torch.stack(tensor_list, dim=0).cuda()\n else:\n batch[name] = torch.stack(tensor_list, dim=0)\n\n # add origin lengths in batch_x\n for name, tensor in batch_x.items():\n if self.use_cuda:\n batch_origin_length[name + \"_origin_len\"] = torch.LongTensor(origin_lengths[name]).cuda()\n else:\n batch_origin_length[name + \"_origin_len\"] = torch.LongTensor(origin_lengths[name])\n batch_x.update(batch_origin_length)\n\n self.curidx += endidx\n return batch_x, batch_y\n\n\nif __name__ == \"__main__\":\n \"\"\"simple running example\n \"\"\"\n texts = [\"i am a cat\",\n \"this is a test of new batch\",\n \"haha\"\n ]\n labels = [0, 1, 0]\n\n # prepare vocabulary\n vocab = {}\n for text in texts:\n for tokens in text.split():\n if tokens not in vocab:\n vocab[tokens] = len(vocab)\n print(\"vocabulary: \", vocab)\n\n # prepare input dataset \n data = DataSet()\n for text, label in zip(texts, labels):\n x = TextField(text.split(), False)\n y = LabelField(label, is_target=True)\n ins = Instance(text=x, label=y)\n data.append(ins)\n\n # use vocabulary to index data\n data.index_field(\"text\", vocab)\n\n\n # define naive sampler for batch class\n class SeqSampler:\n def __call__(self, dataset):\n return list(range(len(dataset)))\n\n\n # use batch to iterate dataset\n data_iterator = Batch(data, 2, SeqSampler(), False)\n for epoch in range(1):\n for batch_x, batch_y in data_iterator:\n print(batch_x)\n print(batch_y)\n # do stuff\n","sub_path":"fastNLP/core/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"172830562","text":"from __future__ import unicode_literals\n\nfrom datetime import datetime\nfrom django.contrib.auth.models import AbstractBaseUser, BaseUserManager\nfrom django.db import models, transaction\nfrom django.utils import timezone\n\n\nclass CheckoutNotCompleted(Exception):\n pass\n\n\nclass CustomUserManager(BaseUserManager):\n\n def create_user(self, email, name, password):\n user = self.model(\n email=email,\n name=name,\n created_at=timezone.now()\n )\n user.set_password(password)\n #setattr(user, 'name', name)\n user.save()\n return user\n\n def create_superuser(self, email, password):\n user = self.model(email=email)\n user.set_password(password)\n user.save()\n return user\n\n\nclass Category(models.Model):\n id = models.AutoField(primary_key=True)\n parent = models.ForeignKey('self', blank=True, null=True)\n name = models.CharField(max_length=255, unique=True)\n\n def __str__(self):\n return self.name\n\n class Meta:\n db_table = 'categories'\n\n\nclass Customer(AbstractBaseUser):\n id = models.AutoField(primary_key=True)\n email = models.CharField(unique=True, max_length=255)\n #password = models.CharField(max_length=255)\n name = models.CharField(max_length=255)\n created_at = models.DateTimeField(default=timezone.now)\n\n # the model must know how to identify the user\n USERNAME_FIELD = 'email'\n\n objects = CustomUserManager()\n\n def __str__(self):\n return self.name\n\n class Meta:\n db_table = 'customers'\n\n\nclass OrderItem(models.Model):\n id = models.AutoField(primary_key=True)\n order = models.ForeignKey('Order')\n product = models.ForeignKey('Product')\n quantity = models.IntegerField(default=1)\n created_at = models.DateTimeField(default=timezone.now)\n updated_at = models.DateTimeField(default=timezone.now)\n price = models.DecimalField(max_digits=10, decimal_places=2, null=True)\n\n class Meta:\n db_table = 'orderitems'\n\n @property\n def total_price(self):\n if self.order.fulfilled:\n return self.price * self.quantity\n return self.product.price * self.quantity\n\n\nclass Order(models.Model):\n id = models.AutoField(primary_key=True)\n customer = models.ForeignKey(Customer)\n fulfilled = models.BooleanField(default=False)\n created_at = models.DateTimeField(default=timezone.now)\n fulfilled_at = models.DateTimeField(blank=True, null=True)\n price = models.DecimalField(max_digits=10, decimal_places=2, null=True)\n\n class Meta:\n db_table = 'orders'\n\n @property\n def total_price(self):\n if self.fulfilled:\n return self.price\n _price = 0\n for orderitem in self.orderitem_set.all():\n _price += orderitem.total_price\n return _price\n\n @classmethod\n def update_shopping_basket(cls, updated_qty, order):\n for orderitem in order.orderitem_set.all():\n qty = int(updated_qty.get(\"quantity-%s\" % orderitem.product.id, 0))\n if not qty or qty <= 0:\n orderitem.delete()\n continue\n orderitem.quantity = min(qty, orderitem.product.stock_quantity)\n orderitem.save()\n\n @classmethod\n def fulfil(cls, updated_qty, order):\n # lock products\n price = 0\n valid = True\n with transaction.atomic():\n products = Product.objects.select_for_update().filter(id__in=map(lambda o: o.product_id, order.orderitem_set.all()))\n orderitems = order.orderitem_set.all()\n for orderitem in orderitems:\n qty = int(updated_qty.get(\"quantity-%s\" % orderitem.product.id, 0))\n if not qty or qty <= 0 or qty > orderitem.product.stock_quantity:\n valid = False\n continue\n orderitem.quantity = qty\n orderitem.price = orderitem.product.price\n orderitem.product.stock_quantity = models.F(\"stock_quantity\") - orderitem.quantity\n price += orderitem.price * orderitem.quantity\n\n if valid:\n for oi in orderitems:\n oi.product.save()\n oi.save()\n order.price = price\n order.fulfilled = True\n order.fulfilled_at = datetime.now()\n order.save()\n return True\n return False\n\n\nclass Product(models.Model):\n id = models.AutoField(primary_key=True)\n category = models.ForeignKey(Category, blank=True, null=True)\n name = models.CharField(max_length=255)\n price = models.DecimalField(max_digits=10, decimal_places=2)\n stock_quantity = models.IntegerField(blank=True, null=True)\n rating = models.FloatField()\n\n @property\n def in_stock(self):\n return self.stock_quantity > 0\n\n def __str__(self):\n return self.name\n\n class Meta:\n db_table = 'products'\n\n\nclass Review(models.Model):\n id = models.AutoField(primary_key=True)\n comment = models.CharField(max_length=4096, blank=True, null=True)\n rating = models.IntegerField()\n product = models.ForeignKey(Product)\n customer = models.ForeignKey(Customer)\n created_at = models.DateTimeField()\n\n class Meta:\n db_table = 'reviews'\n\n\n","sub_path":"website/frontend/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"184676877","text":"import os\r\nimport gym\r\nimport pickle\r\nimport numpy as np\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"\"\r\n\r\n \r\nclass TD_Optimizers:\r\n\r\n def __init__(self, vparam):\r\n # hyperparameters for loss terms, gamma is the discount coefficient\r\n self.params = {\r\n 'gamma': 0.95,\r\n }\r\n self.vparam = vparam\r\n \r\n \r\n def train(self, env, ATD_params, ALRR_params, TD_params, mc=10, max_episode=500, bsize=32, runtime_range=100, pparam=None):\r\n \r\n for j in range(mc):\r\n \r\n ''' initialization '''\r\n # ATD initialization\r\n vparam_atd = np.copy(self.vparam)\r\n lr_atd, beta, delt = ATD_params\r\n m, v, z = 0, 0, 0\r\n mean_losses_atd, losses_atd = [], []\r\n \r\n # ALRR initialization\r\n vparam_alrr = np.copy(self.vparam)\r\n lr_alrr, sig, epsilon = ALRR_params\r\n slope = 2 * sig * (lr_alrr)**(1 - lam/2)\r\n x = np.arange(bsize)\r\n param_ini = np.copy(self.vparam)\r\n vparams = [self.vparam]\r\n mean_losses_alrr, losses_alrr = [], []\r\n \r\n # TD initialization\r\n vparam_td = np.copy(self.vparam)\r\n lr_td = TD_params\r\n mean_losses_td, losses_td = [], []\r\n \r\n # estimate expected initial loss\r\n next_obs = env.reset()\r\n losses_ini = []\r\n step = 0\r\n while step < 5*bsize:\r\n obs = next_obs.copy()\r\n action = env.action_space.sample()\r\n next_obs, reward, done, _ = env.step(action)\r\n if done:\r\n next_obs = env.reset()\r\n loss_ini = (obs @ self.vparam- (reward + self.params['gamma'] * next_obs @ self.vparam * (1-done)))**2\r\n losses_ini.append(loss_ini)\r\n step += 1\r\n mean_loss_ini = np.mean(losses_ini)\r\n mean_losses_atd.append(mean_loss_ini)\r\n mean_losses_alrr.append(mean_loss_ini)\r\n mean_losses_td.append(mean_loss_ini)\r\n print(\"MC: %d, Episode: %d, ATD loss: %.5f, ALRR loss: %.5f, TD loss: %.5f\" \r\n % (j+1, 0, mean_loss_ini, mean_loss_ini, mean_loss_ini))\r\n \r\n ''' start training '''\r\n next_obs = env.reset()\r\n for episode in range(max_episode):\r\n step = 0\r\n while step < bsize:\r\n obs = next_obs.copy()\r\n action = env.action_space.sample()\r\n next_obs, reward, done, _ = env.step(action)\r\n\r\n z = self.params['gamma'] * lam * z + obs \r\n # ATD update\r\n loss_atd = (obs @ vparam_atd - (reward + self.params['gamma'] * next_obs @ vparam_atd))**2\r\n gradient = reward * z + self.params['gamma'] * (next_obs @ vparam_atd) * z - obs @ vparam_atd * z\r\n m = beta * m + (1 - beta) * gradient\r\n v = v + np.linalg.norm(gradient)**2\r\n vparam_atd = vparam_atd + lr_atd * m / np.sqrt(delt + v)\r\n losses_atd.append(loss_atd)\r\n \r\n # ALRR update\r\n loss_alrr = (obs @ vparam_alrr - (reward + self.params['gamma'] * next_obs @ vparam_alrr))**2\r\n gradient = reward * z + self.params['gamma'] * (next_obs @ vparam_alrr) * z - obs @ vparam_alrr * z\r\n vparam_alrr = vparam_alrr + lr_alrr * gradient\r\n vparams.append(vparam_alrr)\r\n if len(vparams) >= bsize:\r\n l = len(vparams)\r\n y = np.linalg.norm(np.array(vparams[l-bsize:]) - param_ini, axis=-1)\r\n slope = np.polyfit(x, y, deg=1)[0]\r\n if slope < ((sig * (lr_alrr)**(1 - lam/2)) / bsize):\r\n lr_alrr /= epsilon\r\n param_ini = np.copy(vparam_alrr)\r\n losses_alrr.append(loss_alrr)\r\n \r\n # TD update\r\n loss_td = (obs @ vparam_td - (reward + self.params['gamma'] * next_obs @ vparam_td))**2\r\n gradient = reward * z + self.params['gamma'] * (next_obs @ vparam_td) * z - obs @ vparam_td * z\r\n vparam_td = vparam_td + lr_td * gradient\r\n losses_td.append(loss_td)\r\n \r\n if done:\r\n next_obs = env.reset()\r\n z = 0\r\n step += 1\r\n \r\n mean_loss_atd = np.mean(losses_atd[(len(losses_atd)-bsize):])\r\n mean_losses_atd.append(mean_loss_atd)\r\n mean_loss_alrr = np.mean(losses_alrr[(len(losses_alrr)-bsize):])\r\n mean_losses_alrr.append(mean_loss_alrr)\r\n mean_loss_td = np.mean(losses_td[(len(losses_td)-bsize):])\r\n mean_losses_td.append(mean_loss_td)\r\n print(\"MC: %d, Episode: %d, ATD loss: %f, ALRR loss: %f, TD loss: %f\" \r\n % (j+1, episode+1, mean_loss_atd, mean_loss_alrr, mean_loss_td))\r\n \r\n if j == 0:\r\n mc_atd = np.array(mean_losses_atd)\r\n mc_alrr = np.array(mean_losses_alrr)\r\n mc_td = np.array(mean_losses_td)\r\n else:\r\n mc_atd = np.vstack((mc_atd, np.array(mean_losses_atd)))\r\n mc_alrr = np.vstack((mc_alrr, np.array(mean_losses_alrr)))\r\n mc_td = np.vstack((mc_td, np.array(mean_losses_td)))\r\n \r\n return mc_atd, mc_alrr, mc_td\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n # common params\r\n name = 'MountainCar-v0'\r\n mc = 10\r\n epi_max = 500\r\n bsize = 16\r\n lam = 0.3\r\n \r\n # custom param\r\n ATD_params = [3, 0.3, 0.01]\r\n ALRR_params = [1, 0.001, 1.2]\r\n TD_params = 0.7\r\n \r\n # initialize env and models\r\n env = gym.make(name)\r\n vparam = np.zeros(env.observation_space.shape[0])\r\n optimizers = TD_Optimizers(vparam)\r\n \r\n # training\r\n mc_atd, mc_alrr, mc_td = optimizers.train(env, ATD_params, ALRR_params, TD_params, \r\n mc, epi_max, bsize)\r\n \r\n # save results\r\n with open('mc_ATD_linear_'+name+'.pkl', 'wb') as f:\r\n pickle.dump(mc_atd, f)\r\n with open('mc_ALRR_linear_'+name+'.pkl', 'wb') as f:\r\n pickle.dump(mc_alrr, f)\r\n with open('mc_TD_linear_'+name+'.pkl', 'wb') as f:\r\n pickle.dump(mc_td, f)\r\n","sub_path":"MountainCar/lam0.3/optimizers_linear.py","file_name":"optimizers_linear.py","file_ext":"py","file_size_in_byte":6627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378512074","text":"prime_number_list= []\r\nprime_matrix=[]\r\nindex_holder=[]\r\n\r\nfor i in range(0,100):\r\n isTrue=True\r\n if i > 1:\r\n for k in range(2, i):\r\n if (i % k) == 0:\r\n isTrue = False\r\n break\r\n if isTrue == True:\r\n prime_number_list.append(i)\r\n\r\nfor i in range(0,3):\r\n row_list = []\r\n for j in range(0,10) :\r\n index=int(input(\"Please enter a number that between 0 and 25 :\"))\r\n if (index>=0)&(index<25):\r\n if index_holder.__contains__(index):\r\n print(\"please enter a different number:\")\r\n\r\n else:\r\n index_holder.append(index)\r\n row_list.append(prime_number_list[index])\r\n if(len(row_list)==3):\r\n break\r\n else:\r\n print(\"number must be on the interval 0,25\")\r\n\r\n prime_matrix.append(row_list)\r\nprint(prime_matrix)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Homeworks/HW1.py","file_name":"HW1.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554924841","text":"import hashlib\n\n\n# Concatenates the possible secret key to the input, and hashes it using MD5\ndef get_hash(input, secret_key_possibility):\n md5_input = \"%s%i\" % (input, secret_key_possibility)\n hash_object = hashlib.md5(md5_input.encode())\n return hash_object.hexdigest()\n\n\n# Generate hashes by brute force, and returns the first solution that starts with the stop-condition string\ndef find_secret_key(input, hash_stop_condition_string):\n secret_key_option = 0\n while True:\n hash = get_hash(input, secret_key_option)\n\n if hash.startswith(hash_stop_condition_string):\n return secret_key_option\n\n # Increment the secret key and try again\n secret_key_option += 1\n\n\npuzzle_input = \"ckczppom\"\nsecret_key = find_secret_key(puzzle_input, \"000000\")\nprint(secret_key)\n","sub_path":"Day4/Day4_2.py","file_name":"Day4_2.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"101925116","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urljoin\nimport re\nimport pdfkit\nimport os\n\ndef find_link(url):\n source_html = requests.get(url).text\n #print(source_html)\n soup = BeautifulSoup(source_html, 'html.parser')\n links = []\n for li in soup.select_one(\"div[id='contents']\").select_one(\"div:nth-of-type(2)\").select(\"li[class='toctree-l2']\"):\n href = li.select_one(\"a\")['href']\n links.append(urljoin(url, href))\n return links\n\ndef generate_pdf(links):\n folders = []\n index = 1\n for link in links:\n #print(link)\n match = re.search(r'en/latest/(.+?)/', link)\n fold = match.group(1)\n\n if fold not in folders:\n folders.append(fold)\n index = 1\n\n match = re.search(r'en/latest/.+?/(.+?)\\.html', link)\n name = match.group(1)\n name = name.replace('/', '-')\n\n if not os.path.exists(fold):\n os.makedirs(fold) \n\n out_file = '{}/{}-{}.pdf'.format(fold, index, name)\n index = index + 1\n pdfkit.from_url(link, out_file)\n\nif __name__ == '__main__':\n links = find_link('http://docs.celeryproject.org/en/latest/')\n generate_pdf(links)","sub_path":"pdf/gdoc.py","file_name":"gdoc.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143685206","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 15 00:24:48 2021\n\n@author: user\n\"\"\"\n\nimport numpy as np\naList=[]\nipt=input(\"請輸入N及M為:\")\nipt=ipt.split(\" \")\n\nfor b in range(int(ipt[0])):\n r_line=input(f\"輸入矩陣第{b+1}列數值為:\")\n aList+=list(r_line.split(\" \"))\n \n\ntable=np.array(aList)\ntable=table.reshape(int(ipt[0]),int(ipt[1]))\ntable=table.T\nfor n,i in enumerate(table):\n print(f\"輸出矩陣第{n+1}列為:\",end=\"\")\n for r in i:\n print(r,end=' ')\n print(\"\\n\")\n \n\n","sub_path":"10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"441464316","text":"import numpy as np\n\na = np.array([1,2,3])\nb = np.array([4,5,6])\n\naMat = np.zeros((2,3))\nbMat = np.ones((2,3))\n\n#stacking matrix, menumpuk matrix\nc = np.hstack((a,b))\nd = np.vstack((a,b))\n\ncMat = np.hstack((aMat,bMat))\ndMat = np.vstack((aMat,bMat))\n\nprint(dMat)","sub_path":"tutorial/6_stacking_matrix.py","file_name":"6_stacking_matrix.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"220565027","text":"from flask import Blueprint\nfrom flask import render_template\nfrom flask import jsonify\nimport logging\nimport json\n\ndef construct(influxdb):\n blueprint = Blueprint('measurements', __name__)\n\n @blueprint.route('/')\n def main():\n return jsonify({'just a test': True})\n\n @blueprint.route('/series/<name>/<start>/<end>')\n def measurement(name, start, end):\n safe_name = json.dumps(name)\n\n base = f'SELECT * from f{safe_name}'\n\n rs = influxdb.query(\n f'{base} WHERE time<$start ORDER BY time DESC LIMIT 1',\n bind_params={\n 'start': start,\n }\n )\n before_point = list(rs.get_points())\n\n rs = influxdb.query(\n f'{base} WHERE time>=$start AND time<$end ORDER BY time',\n bind_params={\n 'start': start,\n 'end': end,\n }\n )\n points = list(rs.get_points())\n\n rs = influxdb.query(\n f'{base} WHERE time>=$end ORDER BY time LIMIT 1',\n bind_params={\n 'end': end,\n }\n )\n after_point = list(rs.get_points())\n\n return jsonify(before_point + points + after_point)\n\n return blueprint\n","sub_path":"measurements.py","file_name":"measurements.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"440440747","text":"\"\"\"\ntodo list\n1. flask +/prdcode: 为啥报错undefined,还会自动刷新...要么直接for循环定义\n3. 策略相关...分开\n4. log 打不开?\n2. secloan字段精确化\n\n# todo\n1. refactor\n 1. 简化、改名与注释\n\"\"\"\n\nimport pandas as pd\nimport pymongo\nfrom trader_v1 import Trader\nimport codecs\nimport threading\nfrom openpyxl import load_workbook\nfrom xlrd import open_workbook\nimport datetime\nimport time\nimport functools\nimport schedule\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom stock_utils import ID2Source, get_sectype_from_code\n\nclient_local_main = pymongo.MongoClient(port=27017, host='localhost', username='admin', password='Ms123456')\ncol_global_var = client_local_main['global_var']['exposure_monitoring']\n\n# 交易日人判断\nis_trading_day_manual = True # Note1.判断交易日\nis_trading_time_manual = True # Note1. 选择上传False = post数据/True = 交易数据\n\n# 手动上传/自动上传\nupdate_postdata_manually = True # Note1.手动/自动上传选择,目前基本用手动 -> copy lastest.py\nbroker_c_without_postdata = ['hc_tradex']\n# 'gf', 'zx', 'hengt', 'hf', 'zhes', 'cj', 'gs', 'ax', 'gl', 'gy', 'swhy', 'yh', 'zxjt' checked, 加减order算出持仓正确\nbroker_m_without_postdata = ['hait_ehfz_api'] # 'zhaos', 'swhy', 'zxjt', huat, hait, gtja 已校验, 'yh'已patch todo(待验证)\n# schedule\nschedule_time = '09:05:00' # Note1.自动上传\nschedule_interval = 5 # s\n\nlogger_expo = logging.getLogger()\nlogger_expo.setLevel(logging.DEBUG)\nfh = RotatingFileHandler('data/log/exposure.log', mode='w', maxBytes=2*1024, backupCount=0)\nfh.setLevel(logging.DEBUG)\nfh.setFormatter(logging.Formatter('%(asctime)s - line:%(lineno)d - %(levelname)s: %(message)s'))\nlogger_expo.addHandler(fh)\n# logging.BasicConfig 仅适用于一个文件,多个程序运行容易写混\n# level = logging.debug < .info < warning < error < critical 每次重写, formatters %()里的都是logging自带变量\n\n\ndef ini_time_records(initialize=True):\n global is_trading_time_manual\n global is_trading_day_manual\n datetime_today = datetime.datetime.today() # + datetime.timedelta(days=0, hours=6, minutes=3) # 假装跨日/清算前\n str_date = datetime_today.strftime('%Y%m%d')\n list_dict_time = list(col_global_var.find({'DataDate': str_date}))\n # 人工调;如果无人值守newday就自动判定\n is_new_day = (len(list_dict_time) == 0)\n if is_new_day:\n end_clearing = datetime.datetime.strptime(f\"{str_date} 091500\", '%Y%m%d %H%M%S')\n start_clearing = datetime.datetime.strptime(f\"{str_date} 223000\", '%Y%m%d %H%M%S')\n is_trading_time = start_clearing > datetime_today > end_clearing\n is_trading_time_manual = is_trading_time\n is_trading_day = datetime_today.weekday() in range(5)\n is_trading_day_manual = is_trading_day\n else:\n is_trading_time = is_trading_time_manual\n is_trading_day = is_trading_day_manual\n\n dict_time = {'IsTradeDay': is_trading_day, 'IsTradeTime': is_trading_time,\n 'RawFinished': False, 'FmtFinished': False, 'PosFinished': False}\n if col_global_var.find_one({'DataDate': str_date}) is None:\n dict_time.update({'RawUpdateTime': None, 'FmtUpdateTime': None, 'PositionUpdateTime': None})\n col_global_var.update_one({'DataDate': str_date}, {'$set': dict_time}, upsert=True)\n if initialize:\n # is newday有延迟,用is_newday多线程时会导致上传多个 (upsert -> insert)\n col_global_var.update_one({'DataDate': str_date}, {'$set': dict_time}, upsert=True)\n return [datetime_today, str_date, is_trading_day, is_trading_time]\n\n\ndef run_process(func):\n @functools.wraps(func)\n def wrapper(self, *args, **kwargs):\n def f():\n if func.__name__ == 'update_fmtdata':\n while not col_global_var.find_one({'DataDate': self.str_day})['RawFinished']: # 等待updateraw开始1s\n time.sleep(1)\n self.lock.acquire()\n func(self, *args, **kwargs)\n self.lock.release()\n print('Function: ', func.__name__, 'finished, go to sleep')\n schedule.every().day.at(schedule_time).do(f)\n while True:\n self.dt_day, self.str_day, self.is_trading_day, self.is_trading_time = ini_time_records(initialize=False)\n if self.is_trading_day:\n if self.is_trading_time: # 清算只跑一次; 只跑一次测试\n if func.__name__ == 'update_fmtdata':\n while not col_global_var.find_one({'DataDate': self.str_day})['RawFinished']:\n time.sleep(1)\n logger_expo.info('RawUpdateTime: ' +\n col_global_var.find_one({'DataDate': self.str_day})['RawUpdateTime'])\n if func.__name__ == 'update_position':\n while not col_global_var.find_one({'DataDate': self.str_day})['FmtFinished']:\n time.sleep(1)\n logger_expo.info('FmtUpdateTime: ' +\n col_global_var.find_one({'DataDate': self.str_day})['FmtUpdateTime'])\n if func.__name__ == 'exposure_analysis':\n while not col_global_var.find_one({'DataDate': self.str_day})['PosFinished']:\n time.sleep(1)\n logger_expo.info('PositionUpdateTime: ' +\n col_global_var.find_one({'DataDate': self.str_day})['PositionUpdateTime'])\n self.lock.acquire() # 只有上面三个变量可以大家都调用, 其余公共变量锁住\n func(self, *args, **kwargs) # 测试时注释掉\n self.lock.release()\n print('Function: ', func.__name__, 'finished')\n if func.__name__ == 'exposure_analysis':\n # record_update_raw_time = \"13:00:00\"\n pass\n time.sleep(60)\n else: # 手动post放在最后\n if update_postdata_manually:\n if func.__name__ == 'update_fmtdata':\n while not col_global_var.find_one({'DataDate': self.str_day})['RawFinished']:\n time.sleep(1)\n func(self, *args, **kwargs)\n print('Function: ', func.__name__, 'finished, go to sleep')\n time.sleep(60)\n else:\n print(self.str_day)\n time.sleep(60*60)\n else:\n raise ValueError('今天不是交易日') # 睡6小时\n return wrapper\n\n\nclass ReadRaw: # 包含post\n def __init__(self):\n self.dt_day, self.str_day, self.is_trading_day, self.is_trading_time = ini_time_records()\n self.record_update_raw_time = None\n self.finish_upload_flag = False\n\n self.db_trddata = client_local_main['trade_data']\n self.db_posttrddata = client_local_main['post_trade_data']\n self.db_basicinfo = client_local_main['basic_info']\n self.col_acctinfo = self.db_basicinfo['acctinfo']\n\n self.path_basic_info = 'data/basic_info.xlsx'\n self.path_patch = 'data/data_patch.xlsx'\n self.upload_basic_info()\n\n self.list_warn = []\n\n self.event = threading.Event()\n self.lock = threading.Lock()\n return\n\n def upload_basic_info(self):\n df = pd.read_excel(self.path_basic_info, index_col=False, sheet_name=None, dtype=str)\n\n for sheet_name in df.keys():\n list_records = []\n df[sheet_name] = df[sheet_name].where(df[sheet_name].notnull(), None)\n for i, row in df[sheet_name].iterrows():\n rec = dict(row)\n rec.update({'DataDate': self.str_day})\n list_records.append(rec)\n self.db_basicinfo[sheet_name].delete_many({'DataDate': self.str_day})\n self.db_basicinfo[sheet_name].insert_many(list_records)\n\n df2 = pd.read_excel(self.path_patch, index_col=False, sheet_name=None, dtype=str)\n list_records = []\n for sheet_name in df2.keys():\n df2[sheet_name] = df2[sheet_name].where(df2[sheet_name].notnull(), None)\n if len(df2[sheet_name].index) == 1:\n rec = dict(df2[sheet_name].iloc[0])\n rec.update({'DataDate': self.str_day, 'SheetName': sheet_name})\n list_records.append(rec)\n continue\n for i, row in df2[sheet_name].iterrows():\n rec = dict(row)\n rec.update({'DataDate': self.str_day, 'SheetName': sheet_name})\n list_records.append(rec)\n self.db_basicinfo['data_patch'].delete_many({'DataDate': self.str_day})\n if len(list_records) == 1:\n self.db_basicinfo['data_patch'].insert_one(list_records[0])\n else:\n self.db_basicinfo['data_patch'].insert_many(list_records)\n\n return\n\n def read_rawdata_from_trdclient(self, fpath, sheet_type, data_source_type, accttype, idinfo):\n \"\"\"\n 从客户端下载数据,并进行初步清洗。为字符串格式。\n tdx倒出的txt文件有“五粮液错误”,使用xls格式的可解决\n\n 已更新券商处理格式:\n 华泰: hexin, txt, cash, margin, fund, holding\n 国君: 富易, csv\n 海通: ehtc, xlsx, cash, fund, holding\n 申宏: alphabee, txt\n 建投: alphabee, txt\n 中信: tdx, txt, vip, cash, fund, holding,\n 民生: tdx, txt\n 华福: tdx, txt\n\n :param idinfo: dict broker - acctidbymxz\n :param fpath:\n :param accttype: c: cash, m: margin, f: future\n :param sheet_type: ['fund', 'holding', 'order', 'secloan']\n :param data_source_type:\n\n :return: list: 由dict rec组成的list\n \"\"\"\n # todo : 注释改进, 有空再精简一下, 古老版本得加上 idinfo部分\n\n list_ret = []\n if sheet_type == 'fund':\n dict_rec_fund = {}\n if data_source_type in ['huat_hx', 'hait_hx', 'zhes_hx', 'tf_hx', 'db_hx', 'wk_hx'] and accttype == 'c':\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()[0:6]\n for dataline in list_datalines:\n list_data = dataline.strip().split(b'\\t')\n for data in list_data:\n list_recdata = data.strip().decode('gbk').split(':')\n dict_rec_fund[list_recdata[0].strip()] = list_recdata[1].strip()\n if dict_rec_fund:\n list_ret.append(dict_rec_fund)\n\n elif data_source_type in ['yh_hx'] and accttype in ['c']:\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n list_keys = list_datalines[5].decode('gbk').split()\n list_values = list_datalines[6].decode('gbk').split()\n list_ret.append(dict(zip(list_keys, list_values)))\n\n elif data_source_type in ['yh_datagrp']:\n df_read = pd.read_excel(fpath, nrows=2)\n dict_rec_fund = df_read.to_dict('records')[0]\n if dict_rec_fund:\n list_ret.append(dict_rec_fund)\n\n elif data_source_type in ['huat_hx', 'hait_hx', 'wk_hx'] and accttype == 'm':\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()[5:14]\n for dataline in list_datalines:\n if dataline.strip():\n list_data = dataline.strip().split(b'\\t')\n else:\n continue\n for data in list_data:\n list_recdata = data.strip().decode('gbk').split(':')\n if len(list_recdata) != 2:\n list_recdata = data.strip().decode('gbk').split(':')\n dict_rec_fund[list_recdata[0].strip()] = \\\n (lambda x: x if x.strip() in ['人民币'] else list_recdata[1].strip())(list_recdata[1])\n if dict_rec_fund:\n list_ret.append(dict_rec_fund)\n\n elif data_source_type in ['gtja_fy'] and accttype in ['c', 'm']:\n wb = open_workbook(fpath, encoding_override='gbk')\n ws = wb.sheet_by_index(0)\n list_keys = ws.row_values(5)\n list_values = ws.row_values(6)\n list_ret.append(dict(zip(list_keys, list_values)))\n\n elif data_source_type in ['hait_ehtc'] and accttype == 'c':\n df_read = pd.read_excel(fpath, skiprows=1, nrows=1)\n dict_rec_fund = df_read.to_dict('records')[0]\n if dict_rec_fund:\n list_ret.append(dict_rec_fund)\n\n elif data_source_type in ['hait_datagrp']:\n df_read = pd.read_excel(fpath, nrows=2)\n dict_rec_fund = df_read.to_dict('records')[0]\n if dict_rec_fund:\n list_ret.append(dict_rec_fund)\n\n elif data_source_type in ['xc_tdx', 'zx_tdx', 'ms_tdx'] and accttype in ['c', 'm']:\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n dataline = list_datalines[0][8:]\n list_recdata = dataline.strip().decode('gbk').split()\n for recdata in list_recdata:\n list_recdata = recdata.split(':')\n list_ret.append({list_recdata[0]: list_recdata[1]})\n\n elif data_source_type in ['wk_tdx', 'zhaos_tdx', 'huat_tdx', 'hf_tdx', 'gx_tdx'] and accttype in ['c',\n 'm']:\n # 已改为xls版本,避免'五粮液错误'\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n list_keys = list_datalines[0].strip().decode('gbk').replace('=', '').replace('\"', '').split(\n '\\t')\n list_values = list_datalines[1].strip().decode('gbk').replace('=', '').replace('\"', '').split(\n '\\t')\n list_ret.append(dict(zip(list_keys, list_values)))\n\n elif data_source_type in ['zxjt_alphabee', 'swhy_alphabee'] and accttype in ['c', 'm']:\n fpath = fpath.replace('<YYYYMMDD>', self.str_day)\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n list_keys = list_datalines[0].decode('gbk').split()\n list_values = list_datalines[1].decode('gbk').split()\n list_ret.append(dict(zip(list_keys, list_values)))\n\n elif data_source_type in ['swhy_alphabee_dbf2csv', 'ax_custom']:\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n list_keys = list_datalines[0].decode('gbk').split(',')\n list_values = list_datalines[1].decode('gbk').split(',')\n list_ret.append(dict(zip(list_keys, list_values)))\n\n elif data_source_type in ['patch']:\n pass\n\n elif data_source_type in ['zx_wealthcats']:\n fpath = fpath.replace('YYYY-MM-DD', self.dt_day.strftime('%Y-%m-%d'))\n with codecs.open(fpath, 'rb', 'utf-8-sig') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund_wealthcats = dict(zip(list_keys, list_values))\n if dict_fund_wealthcats['账户'] in idinfo:\n dict_fund_wealthcats['AcctIDByMXZ'] = idinfo[dict_fund_wealthcats['账户']]\n list_ret.append(dict_fund_wealthcats)\n\n elif data_source_type in ['db_wealthcats']:\n # todo weathcats账户和basic_info里对不上\n fpath = fpath.replace('YYYY-MM-DD', self.dt_day.strftime('%Y-%m-%d'))\n with codecs.open(fpath, 'rb', 'utf-8-sig') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund_wealthcats = dict(zip(list_keys, list_values))\n if dict_fund_wealthcats['账户'] in idinfo:\n dict_fund_wealthcats['AcctIDByMXZ'] = idinfo[dict_fund_wealthcats['账户']]\n list_ret.append(dict_fund_wealthcats)\n\n elif data_source_type in ['ax_jzpb']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with open(fpath, encoding='ansi') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n if dict_fund['账户编号'] in idinfo:\n dict_fund['AcctIDByMXZ'] = idinfo[dict_fund['账户编号']]\n list_ret.append(dict_fund)\n\n elif data_source_type in ['zxjt_xtpb', 'zhaos_xtpb', 'zhes_xtpb', 'hf_xtpb', 'gl_xtpb', 'swhy_xtpb',\n 'cj_xtpb', 'hengt_xtpb', 'zygj_xtpb']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s' % fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n if dict_fund['资金账号'] in idinfo:\n dict_fund['AcctIDByMXZ'] = idinfo[dict_fund['资金账号']]\n list_ret.append(dict_fund)\n\n elif data_source_type in ['hait_ehfz_api']: # 有改动\n for acctidbybroker in idinfo:\n try:\n fpath_ = fpath.replace('YYYYMMDD', self.str_day).replace('<ID>', acctidbybroker)\n with codecs.open(fpath_, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s' % fpath_)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n dict_fund['AcctIDByMXZ'] = idinfo[acctidbybroker] # fpath里自带交易账户, idinfo仅一个\n list_ret.append(dict_fund)\n except FileNotFoundError as e:\n e = str(e)\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n\n elif data_source_type in ['huat_matic_tsi']: # 有改动\n for acctidbybroker in idinfo:\n try:\n fpath_ = fpath.replace('<YYYYMMDD>', self.str_day).replace('<ID>', acctidbybroker)\n with codecs.open(fpath_, 'rb', encoding='gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath_)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n if dict_fund['fund_account'] == acctidbybroker:\n dict_fund['AcctIDByMXZ'] = idinfo[acctidbybroker]\n list_ret.append(dict_fund) # 有改动\n except FileNotFoundError as e:\n e = str(e)\n\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n\n elif data_source_type in ['gy_htpb', 'gs_htpb', 'gj_htpb']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n if dict_fund['资金账户'] in idinfo:\n dict_fund['AcctIDByMXZ'] = idinfo[dict_fund['资金账户']]\n list_ret.append(dict_fund)\n\n elif data_source_type in ['gtja_pluto']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n if dict_fund['单元序号'] in idinfo:\n dict_fund['AcctIDByMXZ'] = idinfo[dict_fund['单元序号']]\n list_ret.append(dict_fund)\n elif data_source_type in ['yh_apama'] and accttype == 'c': # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath) as f:\n list_datalines = f.readlines()\n list_keys = ['请求编号', '资金账号', '币种', '可用余额', '可取金额', '冻结金额', '总资产', '证券市值', '资金资产']\n for dataline in list_datalines:\n dataline = dataline.strip('\\n')\n split_line = dataline.split('|')\n list_values = split_line[:-1]\n for other_value in split_line[-1].split('&'): # 扩展字段\n ind = other_value.find('=')\n list_values.append(other_value[ind+1:]) # 'fl=; 'ml=\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n dict_fund['AcctIDByMXZ'] = list(idinfo.values())[0] # fpath里自带交易账户, idinfo仅一个\n list_ret.append(dict_fund)\n else:\n logger_expo.warning('strange fund keys of yh_apama %s'%fpath)\n elif data_source_type in ['yh_apama'] and accttype == 'm':\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath) as f:\n list_datalines = f.readlines()\n list_keys = ['请求编号', '资金账号', '币种', '可用余额', '可取金额', '冻结金额', '总资产', '证券市值',\n '资金资产', '总负债', '融资负债', '融券负债', '融资息费', '融券息费', '融资可用额度',\n '融券可用额度', '担保证券市值', '维持担保比例', '实时担保比例']\n for dataline in list_datalines:\n dataline = dataline.strip('\\n')\n split_line = dataline.split('|')\n list_values = split_line[:-1]\n for other_value in split_line[-1].split('&'): # 扩展字段\n ind = other_value.find('=')\n list_values.append(other_value[ind + 1:]) # 'fl=; 'ml=\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n dict_fund['AcctIDByMXZ'] = list(idinfo.values())[0] # fpath里自带交易账户, idinfo仅一个\n list_ret.append(dict_fund)\n else:\n logger_expo.warning('strange fund key of yh_apama %s'%fpath)\n elif data_source_type in ['gf_tyt']:\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_fund = dict(zip(list_keys, list_values))\n if dict_fund['projectid'] in idinfo:\n dict_fund['AcctIDByMXZ'] = idinfo[dict_fund['projectid']]\n list_ret.append(dict_fund)\n else:\n e = 'Field data_source_type not exist in basic info!'\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n\n elif sheet_type == 'holding':\n if data_source_type in ['xc_tdx', 'zx_tdx', 'ms_tdx'] and accttype in ['c', 'm']:\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n start_index_holding = None\n for index, dataline in enumerate(list_datalines):\n if '证券代码' in dataline.decode('gbk'):\n start_index_holding = index\n list_keys = [x.decode('gbk') for x in list_datalines[start_index_holding].strip().split()]\n list_keys_2b_dropped = ['折算汇率', '备注', '历史成交', '资讯']\n for key_2b_dropped in list_keys_2b_dropped:\n if key_2b_dropped in list_keys:\n list_keys.remove(key_2b_dropped)\n i_list_keys_length = len(list_keys)\n\n for dataline in list_datalines[start_index_holding + 1:]:\n list_data = dataline.strip().split()\n if len(list_data) == i_list_keys_length:\n list_values = [x.decode('gbk') for x in list_data]\n dict_rec_holding = dict(zip(list_keys, list_values))\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['wk_tdx', 'zhaos_tdx', 'huat_tdx', 'hf_tdx', 'gx_tdx'] and accttype in ['c',\n 'm']:\n # 避免五粮液错误\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n list_list_data = [\n dataline.decode('gbk').replace('=', '').replace('\"', '').split('\\t')\n for dataline in list_datalines\n ]\n start_index_holding = None\n for index, list_data in enumerate(list_list_data):\n if '证券代码' in list_data:\n start_index_holding = index\n list_keys = list_list_data[start_index_holding]\n i_list_keys_length = len(list_keys)\n acctidbybroker = list(idinfo.values())[0] # 假定只有一个\n for list_values in list_list_data[start_index_holding + 1:]:\n if '没有' in list_values[0]:\n print(f'{acctidbybroker}: {list_values[0]}')\n else:\n if len(list_values) == i_list_keys_length:\n dict_rec_holding = dict(zip(list_keys, list_values))\n list_ret.append(dict_rec_holding)\n else:\n logger_expo.warning(f'{acctidbybroker}_{data_source_type}_{list_values} not added into database')\n\n elif data_source_type in ['huat_hx', 'yh_hx', 'wk_hx', 'hait_hx',\n 'zhes_hx', 'db_hx', 'tf_hx'] and accttype in ['c', 'm']:\n # 注: 证券名称中 有的有空格, 核新派以制表符分隔\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n start_index_holding = None\n for index, dataline in enumerate(list_datalines):\n if '证券代码' in dataline.decode('gbk'):\n start_index_holding = index\n list_keys = [x.decode('gbk') for x in list_datalines[start_index_holding].strip().split()]\n list_keys_2b_dropped = ['折算汇率', '备注']\n for key_2b_dropped in list_keys_2b_dropped:\n if key_2b_dropped in list_keys:\n list_keys.remove(key_2b_dropped)\n i_list_keys_length = len(list_keys)\n\n for dataline in list_datalines[start_index_holding + 1:]:\n list_data = dataline.strip().split(b'\\t')\n if len(list_data) == i_list_keys_length:\n list_values = [x.decode('gbk') for x in list_data]\n dict_rec_holding = dict(zip(list_keys, list_values))\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['hait_datagrp', 'yh_datagrp']:\n df_read = pd.read_excel(\n fpath,\n skiprows=3,\n dtype={'股东代码': str},\n converters={'代码': lambda x: str(x).zfill(6), '证券代码': lambda x: str(x).zfill(6)}\n )\n list_dicts_rec_holding = df_read.to_dict('records')\n list_ret = list_dicts_rec_holding\n\n elif data_source_type in ['gtja_fy'] and accttype in ['c', 'm']:\n wb = open_workbook(fpath, encoding_override='gbk')\n ws = wb.sheet_by_index(0)\n list_keys = ws.row_values(8)\n for i in range(9, ws.nrows):\n list_values = ws.row_values(i)\n if '' in list_values:\n continue\n str_values = ','.join(list_values)\n if '合计' in str_values:\n continue\n dict_rec_holding = dict(zip(list_keys, list_values))\n if accttype == 'm':\n if '证券代码' in dict_rec_holding:\n secid = dict_rec_holding['证券代码']\n if secid[0] in ['0', '1', '3']:\n dict_rec_holding['交易市场'] = '深A'\n else:\n dict_rec_holding['交易市场'] = '沪A'\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['hait_ehtc'] and accttype == 'c':\n wb_ehtc = load_workbook(fpath)\n ws = wb_ehtc.active\n i_target_row = 10\n for row in ws.rows:\n for cell in row:\n if cell.value == '持仓':\n i_target_row = cell.row\n df_holding = pd.read_excel(fpath, skiprows=i_target_row)\n list_dicts_rec_holding = df_holding.to_dict('records')\n list_ret = list_dicts_rec_holding\n\n elif data_source_type in ['zxjt_alphabee', 'swhy_alphabee'] and accttype in ['c', 'm']:\n fpath = fpath.replace('<YYYYMMDD>', self.str_day)\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n list_keys = list_datalines[0].decode('gbk').split()\n for dataline in list_datalines[1:]:\n list_values = dataline.decode('gbk').split()\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['swhy_alphabee_dbf2csv', 'ax_custom'] and accttype in ['c', 'm']:\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n list_keys = list_datalines[3].decode('gbk').split(',')\n for dataline in list_datalines[4:]:\n list_values = dataline.decode('gbk').split(',')\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['zx_wealthcats']:\n fpath = fpath.replace('YYYY-MM-DD', self.dt_day.strftime('%Y-%m-%d'))\n with codecs.open(fpath, 'rb', 'utf-8-sig') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n if dict_rec_holding['SymbolFull'].split('.')[1] == 'SZ':\n dict_rec_holding['交易市场'] = '深A'\n elif dict_rec_holding['SymbolFull'].split('.')[1] == 'SH':\n dict_rec_holding['交易市场'] = '沪A'\n else:\n raise ValueError('Unknown exchange mark.')\n if dict_rec_holding['账户'] in idinfo:\n dict_rec_holding['AcctIDByMXZ'] = idinfo[dict_rec_holding['账户']]\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['ax_jzpb']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with open(fpath, encoding='ansi') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n if dict_rec_holding['账户编号'] in idinfo:\n dict_rec_holding['AcctIDByMXZ'] = idinfo[dict_rec_holding['账户编号']]\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['zxjt_xtpb', 'zhaos_xtpb', 'zhes_xtpb', 'hf_xtpb', 'gl_xtpb',\n 'swhy_xtpb', 'cj_xtpb', 'hengt_xtpb', 'zygj_xtpb']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n if dict_rec_holding['资金账号'] in idinfo:\n dict_rec_holding['AcctIDByMXZ'] = idinfo[dict_rec_holding['资金账号']]\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['hait_ehfz_api']: # 有改动\n for acctidbybroker in idinfo:\n fpath_ = fpath.replace('YYYYMMDD', self.str_day).replace('<ID>', acctidbybroker)\n try:\n with codecs.open(fpath_, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath_)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n dict_rec_holding['AcctIDByMXZ'] = idinfo[acctidbybroker]\n list_ret.append(dict_rec_holding)\n except FileNotFoundError as e:\n e = str(e)\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n\n elif data_source_type in ['huat_matic_tsi']: # 有改动\n for acctidbybroker in idinfo:\n fpath_ = fpath.replace('<YYYYMMDD>', self.str_day).replace('<ID>', acctidbybroker)\n try:\n with codecs.open(fpath_, 'rb', encoding='gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath_)\n continue\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_holding = dict(zip(list_keys, list_values))\n # if dict_holding['fund_account'] == acctidbybroker:\n dict_holding['AcctIDByMXZ'] = idinfo[acctidbybroker]\n list_ret.append(dict_holding)\n except FileNotFoundError as e:\n e = str(e)\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n\n elif data_source_type in ['gy_htpb', 'gs_htpb', 'gj_htpb']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n if dict_rec_holding['资金账户'] in idinfo:\n dict_rec_holding['AcctIDByMXZ'] = idinfo[dict_rec_holding['资金账户']]\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['gtja_pluto']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n if dict_rec_holding['单元序号'] in idinfo:\n dict_rec_holding['AcctIDByMXZ'] = idinfo[dict_rec_holding['单元序号']]\n list_ret.append(dict_rec_holding)\n\n elif data_source_type in ['yh_apama'] and accttype == 'm': # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath) as f:\n list_datalines = f.readlines()\n list_keys = ['请求编号', '资金账号', '证券代码', '交易市场', '股份可用', '当前持仓', '持仓成本', '最新价',\n '昨日持仓', '冻结数量', '买入冻结', '卖出冻结', '参考盈亏', '参考市值', '是否为担保品',\n '担保品折算率', '融资买入股份余额', '融资买入股份可用']\n for dataline in list_datalines:\n split_line = dataline.strip('\\n').split('|')\n list_values = split_line[:-1]\n for other_value in split_line[-1].split('&'): # 扩展字段\n ind = other_value.find('=')\n list_values.append(other_value[ind+1:]) # 'fl=; 'ml=\n if len(list_values) == len(list_keys):\n dict_holding = dict(zip(list_keys, list_values))\n dict_holding['AcctIDByMXZ'] = list(idinfo.values())[0]\n list_ret.append(dict_holding)\n else:\n logger_expo.warning('strange holidng keys of yh_apama %s'%fpath)\n elif data_source_type in ['yh_apama'] and accttype == 'c': # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath) as f:\n list_datalines = f.readlines()\n list_keys = ['请求编号', '资金账号', '证券代码', '交易市场', '股份可用', '当前持仓', '持仓成本', '最新价',\n '昨日持仓', '股东代码', '买入冻结', '买入冻结金额', '卖出冻结', '卖出冻结金额']\n for dataline in list_datalines:\n split_line = dataline.strip('\\n').split('|')\n list_values = split_line[:-1]\n for other_value in split_line[-1].split('&'): # 扩展字段\n ind = other_value.find('=')\n list_values.append(other_value[ind+1:]) # 'fl=; 'ml=\n if len(list_values) == len(list_keys):\n dict_holding = dict(zip(list_keys, list_values))\n dict_holding['AcctIDByMXZ'] = list(idinfo.values())[0]\n list_ret.append(dict_holding)\n else:\n logger_expo.warning('strange holidng keys of yh_apama %s'%fpath)\n\n elif data_source_type in ['gf_tyt']:\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_holding = dict(zip(list_keys, list_values))\n if dict_holding['projectid'] in idinfo:\n dict_holding['AcctIDByMXZ'] = idinfo[dict_holding['projectid']]\n list_ret.append(dict_holding)\n elif sheet_type == 'secloan':\n # postdata处理raw用,交易时不读\n if data_source_type in ['zhaos_tdx'] and accttype in ['m']:\n with open(fpath, 'rb') as f:\n list_datalines = f.readlines()\n start_index_secloan = None\n for index, dataline in enumerate(list_datalines):\n str_dataline = dataline.decode('gbk')\n if '证券代码' in str_dataline:\n start_index_secloan = index\n list_keys = [x.decode('gbk') for x in list_datalines[start_index_secloan].strip().split()]\n i_list_keys_length = len(list_keys)\n for dataline in list_datalines[start_index_secloan + 1:]:\n list_data = dataline.strip().split()\n if len(list_data) == i_list_keys_length:\n list_values = [x.decode('gbk') for x in list_data]\n dict_rec_secloan = dict(zip(list_keys, list_values))\n secid = dict_rec_secloan['证券代码']\n if secid[0] in ['0', '1', '3']:\n dict_rec_secloan['交易市场'] = '深A'\n else:\n dict_rec_secloan['交易市场'] = '沪A'\n list_ret.append(dict_rec_secloan)\n elif data_source_type in ['zxjt_xtpb', 'zhaos_xtpb', 'zhes_xtpb', 'hf_xtpb', 'gl_xtpb', 'swhy_xtpb',\n 'cj_xtpb', 'hengt_xtpb', 'zygj_xtpb'] and accttype in ['m']:\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_secloan = dict(zip(list_keys, list_values))\n if dict_rec_secloan['资金账号'] in idinfo:\n dict_rec_secloan['AcctIDByMXZ'] = idinfo[dict_rec_secloan['资金账号']]\n list_ret.append(dict_rec_secloan)\n\n elif data_source_type in ['hait_ehfz_api'] and accttype in ['m']:\n for acctidbybroker in idinfo:\n try:\n fpath_ = fpath.replace('YYYYMMDD', self.str_day).replace('<ID>', acctidbybroker)\n with codecs.open(fpath_, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath_)\n continue\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_secloan = dict(zip(list_keys, list_values))\n dict_rec_secloan['AcctIDByMXZ'] = idinfo[acctidbybroker]\n list_ret.append(dict_rec_secloan)\n except FileNotFoundError as e:\n e = str(e)\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n\n elif data_source_type in ['huat_matic_tsi'] and accttype in ['m']: # 有改动\n for acctidbybroker in idinfo:\n fpath_ = fpath.replace('<YYYYMMDD>', self.str_day).replace('<ID>', acctidbybroker)\n try:\n with codecs.open(fpath_, 'rb', encoding='gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath_)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_secloan = dict(zip(list_keys, list_values))\n if dict_secloan['fund_account'] == acctidbybroker:\n dict_secloan['AcctIDByMXZ'] = idinfo[acctidbybroker]\n list_ret.append(dict_secloan)\n except FileNotFoundError as e:\n e = str(e)\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n elif data_source_type in ['gtja_pluto'] and accttype in ['m']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_secloan = dict(zip(list_keys, list_values))\n if dict_rec_secloan['单元序号'] in idinfo:\n dict_rec_secloan['AcctIDByMXZ'] = idinfo[dict_rec_secloan['单元序号']]\n list_ret.append(dict_rec_secloan)\n elif sheet_type == 'order':\n # 先做这几个有secloan的(不然order没意义):\n if data_source_type in ['zxjt_xtpb', 'zhaos_xtpb', 'zhes_xtpb', 'hf_xtpb', 'gl_xtpb',\n 'swhy_xtpb', 'cj_xtpb', 'hengt_xtpb', 'zygj_xtpb']:\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s' % fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_order = dict(zip(list_keys, list_values))\n if dict_rec_order['资金账号'] in idinfo:\n dict_rec_order['AcctIDByMXZ'] = idinfo[dict_rec_order['资金账号']]\n list_ret.append(dict_rec_order)\n\n if data_source_type in ['hait_ehfz_api']:\n for acctidbybroker in idinfo:\n try:\n fpath_ = fpath.replace('YYYYMMDD', self.str_day).replace('<ID>', acctidbybroker)\n with codecs.open(fpath_, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath_)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_order = dict(zip(list_keys, list_values))\n dict_rec_order['AcctIDByMXZ'] = idinfo[acctidbybroker]\n list_ret.append(dict_rec_order)\n except FileNotFoundError as e:\n e = str(e)\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n\n elif data_source_type in ['huat_matic_tsi']: # 有改动\n for acctidbybroker in idinfo:\n try:\n fpath_ = fpath.replace('<YYYYMMDD>', self.str_day).replace('<ID>', acctidbybroker)\n with codecs.open(fpath_, 'rb', encoding='gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath_)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_order = dict(zip(list_keys, list_values))\n dict_order['AcctIDByMXZ'] = idinfo[acctidbybroker]\n list_ret.append(dict_order)\n except FileNotFoundError as e:\n e = str(e)\n if e not in self.list_warn:\n self.list_warn.append(e)\n logger_expo.error(e)\n elif data_source_type in ['gtja_pluto']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_order = dict(zip(list_keys, list_values))\n if dict_rec_order['单元序号'] in idinfo:\n dict_rec_order['AcctIDByMXZ'] = idinfo[dict_rec_order['单元序号']]\n list_ret.append(dict_rec_order)\n\n elif data_source_type in ['yh_apama']: # 成交明细不是委托明细\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath) as f:\n list_datalines = f.readlines()\n list_keys = ['请求编号', '资金账号', '证券代码', '交易市场', '委托序号', '买卖方向', '股东号', '成交时间',\n '成交编号', '成交价格', '成交数量', '成交金额', '成交类型', '委托数量', '委托价格']\n for dataline in list_datalines:\n split_line = dataline.strip('\\n').split('|')\n list_values = split_line[:-1]\n # for other_value in split_line[-1].split('&'): # order暂无扩展字段\n # ind = other_value.find('=')\n # list_values.append(other_value[ind + 1:])\n if len(list_values) == len(list_keys):\n dict_order = dict(zip(list_keys, list_values))\n dict_order['AcctIDByMXZ'] = list(idinfo.values())[0]\n list_ret.append(dict_order)\n else:\n logger_expo.warning('strange order keys of yh_apama %s' % fpath)\n\n elif data_source_type in ['ax_jzpb']:\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with open(fpath, encoding='ansi') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if '信息初始化' in list_values: # todo 最后一行莫名多出这个(标题和其他行还没有)得改\n list_values = list_values[:-1]\n if len(list_values) == len(list_keys):\n dict_rec_order = dict(zip(list_keys, list_values))\n if dict_rec_order['账户编号'] in idinfo:\n dict_rec_order['AcctIDByMXZ'] = idinfo[dict_rec_order['账户编号']]\n list_ret.append(dict_rec_order)\n elif data_source_type in ['zx_wealthcats']:\n fpath = fpath.replace('YYYY-MM-DD', self.dt_day.strftime('%Y-%m-%d'))\n with codecs.open(fpath, 'rb', 'utf-8-sig') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_order = dict(zip(list_keys, list_values))\n if dict_rec_order['账户'] in idinfo:\n dict_rec_order['AcctIDByMXZ'] = idinfo[dict_rec_order['账户']]\n list_ret.append(dict_rec_order)\n elif data_source_type in ['gy_htpb', 'gs_htpb', 'gj_htpb']: # 有改动\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_rec_holding = dict(zip(list_keys, list_values))\n if dict_rec_holding['资金账户'] in idinfo:\n dict_rec_holding['AcctIDByMXZ'] = idinfo[dict_rec_holding['资金账户']]\n list_ret.append(dict_rec_holding)\n elif data_source_type in ['gf_tyt']:\n fpath = fpath.replace('YYYYMMDD', self.str_day)\n with codecs.open(fpath, 'rb', 'gbk') as f:\n list_datalines = f.readlines()\n if len(list_datalines) == 0:\n logger_expo.warning('读取空白文件%s'%fpath)\n else:\n list_keys = list_datalines[0].strip().split(',')\n for dataline in list_datalines[1:]:\n list_values = dataline.strip().split(',')\n if len(list_values) == len(list_keys):\n dict_order = dict(zip(list_keys, list_values))\n if dict_order['projectid'] in idinfo:\n dict_order['AcctIDByMXZ'] = idinfo[dict_order['projectid']]\n list_ret.append(dict_order)\n else:\n raise ValueError('Wrong sheet name!')\n return list_ret\n\n @run_process\n def update_all_rawdata(self):\n \"\"\"\n 1. 出于数据处理留痕及增强robust考虑,将原始数据按照原格式上传到mongoDB中备份\n 2. 定义DataFilePath = ['fpath_fund_data'(source), 'fpath_holding_data'(source), 'fpath_trdrec_data(source)',]\n 3. acctinfo数据库中DataFilePath存在文件路径即触发文件数据的上传。\n 4. 添加:融券未平仓合约数据的上传\n \"\"\"\n if self.record_update_raw_time is None: # It's possible that future thread attributes value before\n self.record_update_raw_time = datetime.datetime.today().strftime('%H%M%S')\n # UpdateTime 不用过于精确,只是方便format时查找(只更新最新版)\n if self.is_trading_time: # update post-trade\n dict_col_rawdata = {'fund': self.db_trddata['trade_rawdata_fund'],\n 'holding': self.db_trddata['trade_rawdata_holding'],\n 'order': self.db_trddata['trade_rawdata_order'],\n 'secloan': self.db_trddata['trade_rawdata_secloan']}\n pathname = 'DataFilePath'\n else: # update trd\n dict_col_rawdata = {'fund': self.db_posttrddata['post_trade_rawdata_fund'],\n 'holding': self.db_posttrddata['post_trade_rawdata_holding'],\n 'order': self.db_posttrddata['post_trade_rawdata_order'],\n 'secloan': self.db_posttrddata['post_trade_rawdata_secloan']}\n\n if update_postdata_manually:\n pathname = 'PostDataFilePath'\n else:\n pathname = 'DataFilePath'\n\n # 相同datafilepath一起读, basic info 里读取文件的地址一样归类(很多账户都在一个文件里)\n\n dict_filepath2acct = {}\n for _ in self.col_acctinfo.find({'DataDate': self.str_day, 'DataDownloadMark': '1'}):\n datafilepath = _[pathname]\n if datafilepath:\n if 'DownloadDataFilter' in _ and _['DownloadDataFilter']:\n acctidbybroker = _['DownloadDataFilter']\n else:\n acctidbybroker = _['AcctIDByBroker']\n if datafilepath in dict_filepath2acct:\n dict_filepath2acct[datafilepath].update({acctidbybroker: _['AcctIDByMXZ']})\n else:\n dict_filepath2acct[datafilepath] = {\n acctidbybroker: _['AcctIDByMXZ'], 'AcctType': _['AcctType'], 'DataSourceType': _['DataSourceType']\n } # 同一地址 datasourcetype, accttype一样, 普通户和信用户肯定分开来存\n\n # Note2. 全部存成一个list,只上传一边,提高性能\n dict_list_upload_recs = {'fund': [], 'holding': [], 'order': [], 'secloan': []}\n for datafilepath in dict_filepath2acct: # RptMark 是pretrade部分\n info = dict_filepath2acct[datafilepath]\n list_fpath_data = datafilepath[1:-1].split(',')\n data_source_type = info[\"DataSourceType\"]\n accttype = info['AcctType']\n id_info = info.copy()\n del id_info['AcctType']\n del id_info['DataSourceType']\n for i in range(len(list_fpath_data)):\n fpath_relative = list_fpath_data[i] # 如果有sec,order必须空置 '; ; ;'形式\n if fpath_relative == '':\n continue\n sheet_name = ['fund', 'holding', 'order', 'secloan'][i]\n # fpath_absolute = os.path.join(self.dirpath_data_from_trdclient, fpath_relative)\n try:\n list_dicts_rec = self.read_rawdata_from_trdclient(fpath_relative, sheet_name, data_source_type,\n accttype, id_info)\n # there are some paths that I do not have access\n for dict_rec in list_dicts_rec:\n # if data_source_type == 'zx_wealthcats':\n # print(_, fpath_relative)\n dict_rec['DataDate'] = self.str_day\n dict_rec['UpdateTime'] = self.record_update_raw_time\n dict_rec['AcctType'] = accttype\n dict_rec['DataSourceType'] = data_source_type\n\n if list_dicts_rec:\n dict_list_upload_recs[sheet_name] += list_dicts_rec\n except FileNotFoundError as e:\n e = str(e)\n if e not in self.list_warn:\n logger_expo.warning(e)\n self.list_warn.append(e)\n\n for ch in dict_col_rawdata:\n if dict_list_upload_recs[ch]:\n dict_col_rawdata[ch].delete_many({'DataDate': self.str_day})\n dict_col_rawdata[ch].insert_many(dict_list_upload_recs[ch])\n # 更新全局变量\n\n # Note2.tell future thread this function has finished,因为fmt要在raw都完成才上传\n if self.finish_upload_flag: # future has finished, only update once\n col_global_var.update_one({'DataDate': self.str_day},\n {'$set': {'RawFinished': True, 'RawUpdateTime': self.record_update_raw_time}})\n self.finish_upload_flag = False # for the upload next time\n else:\n self.finish_upload_flag = True # tell future thread this function has finished\n # 如果有多个函数可以设置 list_flag, 长度为Nthread -1, 每一个finish把里面一个false改为True, 来保证只上传一次\n print('Update raw data: ', self.record_update_raw_time)\n\n @run_process\n def update_trddata_f(self):\n if self.record_update_raw_time is None:\n self.record_update_raw_time = datetime.datetime.today().strftime('%H%M%S')\n if self.is_trading_time:\n cursor_find = list(self.col_acctinfo.find({'DataDate': self.str_day, 'AcctType': 'f', 'DataDownloadMark': '1'}))\n list_exceptions = []\n for _ in cursor_find:\n list_future_data_fund = []\n list_future_data_holding = []\n list_future_data_trdrec = []\n prdcode = _['PrdCode']\n acctidbymxz = _['AcctIDByMXZ']\n acctidbyowj = _['AcctIDByOuWangJiang4FTrd']\n data_source_type = _['DataSourceType']\n try:\n trader = Trader(acctidbyowj)\n except Exception as e:\n if not(str(e) in list_exceptions):\n logger_expo.error(e)\n list_exceptions.append(str(e))\n if '连接不通' in str(e): # api 关闭\n break\n else: # 单个产品出问题\n continue\n dict_res_fund = trader.query_capital()\n if dict_res_fund:\n dict_fund_to_be_update = dict_res_fund\n dict_fund_to_be_update['DataDate'] = self.str_day\n dict_fund_to_be_update['AcctIDByMXZ'] = acctidbymxz\n dict_fund_to_be_update['AcctIDByOWJ'] = acctidbyowj\n dict_fund_to_be_update['PrdCode'] = prdcode\n dict_fund_to_be_update['DataSourceType'] = data_source_type\n dict_fund_to_be_update['UpdateTime'] = self.record_update_raw_time\n list_future_data_fund.append(dict_fund_to_be_update)\n if list_future_data_fund:\n self.db_trddata['trade_future_api_fund'].delete_many({'DataDate': self.str_day, 'AcctIDByMXZ': acctidbymxz})\n self.db_trddata['trade_future_api_fund'].insert_many(list_future_data_fund)\n\n list_list_res_holding = trader.query_holding()\n list_keys_holding = [\n 'exchange', 'instrument_id', 'direction', 'hedge', 'position', 'position_td', 'open_volume',\n 'close_volume', 'unknown1', 'unknown2', 'unknown3'\n ]\n if len(list_list_res_holding):\n list_dicts_holding_to_be_update = list_list_res_holding\n for list_holding_to_be_update in list_dicts_holding_to_be_update:\n dict_holding_to_be_update = dict(zip(list_keys_holding, list_holding_to_be_update))\n dict_holding_to_be_update['DataDate'] = self.str_day\n dict_holding_to_be_update['AcctIDByMXZ'] = acctidbymxz\n dict_holding_to_be_update['AcctIDByOWJ'] = acctidbyowj\n dict_holding_to_be_update['PrdCode'] = prdcode\n dict_holding_to_be_update['DataSourceType'] = data_source_type\n dict_holding_to_be_update['UpdateTime'] = self.record_update_raw_time\n list_future_data_holding.append(dict_holding_to_be_update)\n\n if list_future_data_holding:\n self.db_trddata['trade_future_api_holding'].delete_many({'DataDate': self.str_day, 'AcctIDByMXZ': acctidbymxz})\n self.db_trddata['trade_future_api_holding'].insert_many(list_future_data_holding)\n\n list_list_res_trdrecs = trader.query_trdrecs()\n if len(list_list_res_trdrecs):\n list_keys_trdrecs = ['instrument_id', 'direction', 'offset', 'volume', 'price', 'time', 'trader']\n for list_res_trdrecs in list_list_res_trdrecs:\n dict_trdrec = dict(zip(list_keys_trdrecs, list_res_trdrecs))\n dict_trdrec['DataDate'] = self.str_day\n dict_trdrec['AcctIDByMXZ'] = acctidbymxz\n dict_trdrec['AcctIDByOWJ'] = acctidbyowj\n dict_trdrec['PrdCode'] = prdcode\n dict_trdrec['DataSourceType'] = data_source_type\n dict_trdrec['UpdateTime'] = self.record_update_raw_time\n list_future_data_trdrec.append(dict_trdrec)\n\n if list_future_data_trdrec:\n self.db_trddata['trade_future_api_order'].delete_many({'DataDate': self.str_day, 'AcctIDByMXZ': acctidbymxz})\n self.db_trddata['trade_future_api_order'].insert_many(list_future_data_trdrec)\n\n if self.finish_upload_flag: # update_all_raw has finished\n col_global_var.update_one({'DataDate': self.str_day},\n {'$set': {'RawFinished': True, 'RawUpdateTime': self.record_update_raw_time}})\n self.finish_upload_flag = False # for the upload next time\n else:\n self.finish_upload_flag = True\n\n def run(self):\n thread_raw = threading.Thread(target=self.update_all_rawdata)\n thread_raw.start()\n if self.is_trading_time:\n thread_future = threading.Thread(target=self.update_trddata_f)\n # 要启动期货时记得 self.finish_upload_flag = False\n thread_future.start()\n else:\n self.finish_upload_flag = True\n\n\nclass FmtData: # 包含post\n def __init__(self):\n self.dt_day, self.str_day, self.is_trading_day, self.is_trading_time = ini_time_records()\n self.db_trddata = client_local_main['trade_data']\n self.db_posttrddata = client_local_main['post_trade_data']\n self.col_acctinfo = client_local_main['basic_info']['acctinfo']\n self.id2source = ID2Source(client_local_main['basic_info'], 'data/security_id.xlsx')\n\n self.record_fmt_time = None\n self.record_update_raw_time = None\n\n self.list_warn = []\n\n self.lock = threading.Lock()\n return\n\n def formulate_raw_data(self, acctidbymxz, accttype, patchpath, sheet_type, raw_list):\n\n list_dicts_fmtted = []\n\n if accttype in ['c', 'm'] and patchpath is None:\n # patch 默认 fmt\n\n # --------------- FUND 相关列表 ---------------------\n # 净资产 = 总资产-总负债 = NetAsset\n # 现金 = 总资产-总市值 普通户里= available_fund, 在资产负债表里\n # 可用资金 = 可用担保品交易资金, 有很多定义, 不在资产负债表里,交易用\n # 可取资金 = 总资产 - 当日交易股票市值-各种手续费-利息+分红, 不在资产负债表里,交易用\n list_fields_af = ['可用', 'A股可用', '可用数', '现金资产', '可用金额', '资金可用金', '可用余额', 'T+0交易可用金额',\n 'enable_balance', 'fund_asset', '可用资金', 'instravl']\n # 新加:matic_tsi_RZRQ: fund_asset, gtja_pluto:可用资金\n list_fields_ttasset = ['总资产', '资产', '总 资 产', '实时总资产', '单元总资产', '资产总额', '账户总资产',\n '担保资产', 'asset_balance', 'assure_asset', '账户资产', '资产总值']\n list_fields_na = ['netasset', 'net_asset', '账户净值', '净资产'] # 尽量避免 '产品净值' 等\n list_fields_kqzj = ['可取资金', '可取金额', 'fetch_balance', '沪深T+1交易可用', '可取余额', 'T+1交易可用金额',\n '可取数'] # 'T+1交易可用金额'不算可取\n list_fields_tl = ['总负债', 'total_debit'] #\n # list_fields_cb = [] # 券商没义务提供,得从postdata里找\n list_fields_mktvalue = ['总市值', 'market_value', '证券资产', '证券市值'] # 券商没义务提供,得按long-short算\n\n # --------------- Security 相关列表 ---------------------\n list_fields_secid = ['代码', '证券代码', 'stock_code', 'stkcode']\n list_fields_symbol = ['证券名称', 'stock_name', '股票名称', '名称']\n list_fields_shareholder_acctid = ['股东帐户', '股东账号', '股东代码']\n list_fields_exchange = ['市场代码', '交易市场', '交易板块', '板块', '交易所', '交易所名称', '交易市场',\n 'exchange_type', 'market']\n\n # 有优先级别的列表\n list_fields_longqty = [\n '当前拥股数量', '股票余额', '拥股数量', '证券余额', '证券数量', '库存数量', '持仓数量', '参考持股', '持股数量', '当前持仓',\n '当前余额', '当前拥股', '实际数量', '实时余额', 'current_amount', 'stkholdqty'\n ]\n dict_exchange2secidsrc = {'深A': 'SZSE', '沪A': 'SSE',\n '深A': 'SZSE', '沪A': 'SSE',\n '上海A': 'SSE', '深圳A': 'SZSE',\n '上海A股': 'SSE', '深圳A股': 'SZSE',\n '上海A股': 'SSE', '深圳A股': 'SZSE',\n 'SH': 'SSE', 'SZ': 'SZSE',\n '上交所A': 'SSE', '深交所A': 'SZSE',\n '上证所': 'SSE', '深交所': 'SZSE'}\n dict_ambigu_secidsrc = {'hait_ehfz_api': {'1': 'SZSE', '2': 'SSE'},\n 'gtja_pluto': {'1': 'SSE', '2': \"SZSE\"},\n 'huat_matic_tsi': {'1': 'SSE', '2': 'SZSE'},\n 'yh_apama': {'0': 'SZSE', '2': 'SSE'},\n 'ax_jzpb': {'0': 'SZSE', '1': 'SSE'}, # '市场; 市场代码'两个字段\n 'gf_tyt': {'0': 'SZSE', '1': 'SSE'}}\n\n # ------------- ORDER 相关列表 ---------------------\n # order委托/entrust除了成交时间等信息最全,不是成交(trade,deal)(没有委托量等)\n # zxjt_xtpb, zhaos_xtpb只有deal无order; deal/trade?\n # todo 撤单单独列出一个字段 + 买券还券等处理 (huat拆成两个如何合并?)\n # 带数字不明确的得再理一理\n # OrdID 最好判断下是否有一样的,(数据源可能超级加倍...)\n # 撤单数+成交数=委托数 来判断终态, ordstatus ‘部撤’有时并非终态\n\n list_fields_cumqty = ['成交数量', 'business_amount', 'matchqty', '成交量']\n list_fields_leavesqty = ['撤单数量', '撤销数量', 'withdraw_amount', 'cancelqty', '撤单量', '已撤数量']\n # apama只有成交,委托待下,成交=终态\n list_fields_side = ['买卖标记', 'entrust_bs', '委托方向', '@交易类型', 'bsflag', '交易', '买卖标识']\n list_fields_orderqty = ['委托量', 'entrust_amount', '委托数量', 'orderqty'] # XXX_deal 会给不了委托量,委托日期,委托时间,只有成交\n list_fields_ordertime = ['委托时间', 'entrust_time', 'ordertime ', '时间', '成交时间'] # yh\n list_fields_avgpx = ['成交均价', 'business_price', '成交价格', 'orderprice'] # 以后算balance用, exposure不用\n # list_fields_cumamt = ['成交金额', 'business_balance', 'matchamt', '成交额']\n dict_fmtted_side_name = {'买入': 'buy', '卖出': 'sell',\n '限价担保品买入': 'buy', '限价买入': 'buy', '担保品买入': 'buy', 'BUY': 'buy', # 担保品=券; 限价去掉,含\"...“即可\n '限价卖出': 'sell', '限价担保品卖出': 'sell', '担保品卖出': 'sell', 'SELL': 'sell',\n '0B': 'buy', '0S': 'sell', '证券买入': 'buy', '证券卖出': 'sell',\n '限价融券卖出': 'sell short', '融券卖出': 'sell short', # 快速交易的 hait=11\n '现券还券划拨': 'XQHQ', '现券还券划拨卖出': 'XQHQ',# 快速交易的 hait=15, gtja=34??\n '买券还券划拨': 'MQHQ', '买券还券': 'MQHQ', '限价买券还券': 'MQHQ', # 快速交易的 hait=13\n '撤单': 'cancel', 'ZR': 'Irrelevant', 'ZC': 'Irrelevant'} # entrust_bs表方向时值为1,2\n dict_ambigu_side_name = {'hait_ehfz_api': {'1': 'buy', '2': 'sell', '12': 'sell short',\n '15': 'XQHQ', '13': 'MQHQ', '0': 'cancel'},\n 'gtja_pluto': {'1': 'buy', '2': 'sell', '34': 'MQHQ', '32': 'sell short',\n '31': 'buy', '33': 'sell', '36': 'XQHQ'}, # 融资买入, 卖券还款\n 'huat_matic_tsi': {'1': 'buy', '2': 'sell'}} # 信用户在后面讨论(需要两个字段拼起来才行)\n # dict_datasource_ordstatus = {\n # # 参考FIX:New已报; Partially Filled=部成待撤/部成,待撤=PendingCancel不算有效cumqty,中间态\n # # 国内一般全成,部撤等都表示最终态,cumqty的数值都是有效的(Filled, Partially Canceled),其他情况的cumqty不能算\n # # 部撤 Partially Canceled(自己命名的)\n # 'hait_ehfz_api': {'5': 'Partially Canceled', '8': 'Filled', '6': 'Canceled'},\n # 'gtja_pluto': {'4': 'New', '6': 'Partially Filled', '7': 'Filled', '8': 'Partially Canceled',\n # '9': 'Canceled', '5': 'Rejected', '10': 'Pending Cancel', '2': 'Pending New'},\n # 'yh_apama': {'2': 'New', '5': 'Partially Filled', '8': 'Filled', '7': 'Partially Filled', # todo 看表确认\n # '6': 'Canceled', '9': 'Rejected', '3': 'Pending Cancel', '1': 'Pending New'},\n # 'huat_matic_tsi': {'2': 'New', '7': 'Partially Filled', '8': 'Filled', '5': 'Partially Filled',\n # '6': 'Canceled', '9': 'Rejected', '4': 'Pending Cancel', '1': 'Pending New'},\n # 'zx_wealthcats': {'部撤': 'Partially Filled', '全成': 'Filled', '全撤': 'Canceled', '废单': 'Rejected'},\n # 'xtpb': {'部成': 'Partially Filled', '已成': 'Filled', '已撤': 'Canceled', '废单': 'Rejected', '部撤': 'Partially Filled'},\n # 'gt_tyt': {'8': 'Filled'},\n # 'ax_jzpb': {'已成': 'Filled', '已撤': 'Canceled', '废单': 'Rejected',\n # '部撤': 'Partially Filled', '已报': 'New'},\n # 'htpb': {'已成': 'Filled', '已撤': 'Canceled', '废单': 'Rejected', '部撤': 'Partially Filled'},\n # }\n list_date_format = ['%Y%m%d']\n list_time_format = ['%H%M%S', '%H:%M:%S', '%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M:%S']\n # ------------- SECURITY LOAN 相关列表 ---------------------\n # todo 加hait_xtpb; huat_matic参考其手册;\n # pluto 合约类型,合约状态里的1和huat里的1指代一个吗?\n # 这块 有不少问题!!!目前只关注short暂不会出错\n list_fields_shortqty = ['未还合约数量', 'real_compact_amount', '未还负债数量', '发生数量'] # 未还合约数量一般是开仓数量\n # 合约和委托没有关系了,但是用contract还是compact(券商版)?\n list_fields_contractqty = ['合约开仓数量', 'business_amount', '成交数量'] # 国外sell short约为“融券卖出”\n # list_fields_contracttype = ['合约类型', 'compact_type'] # 一定能分开 锁券与否\n # list_fields_contractstatus = ['合约状态', 'compact_status', '@负债现状'] # filled='完成'那不是委托?融资融券能用\n list_fields_opdate = ['合约开仓日期', 'open_date', '发生日期'] # FIX 合约: contract\n list_fields_sernum = ['成交编号', '合同编号', 'entrust_no', '委托序号', '合约编号', '合同号', 'instr_no', '成交序号',\n '订单号', '委托编号']\n # SerialNumber 券商不统一,目前方便区分是否传了两遍..然而entrust_no还是重复 (RZRQ里的business_no)可以\n list_fields_compositesrc = [] # todo CompositeSource\n\n # todo: 其它名字’开仓未归还‘,私用融券(专项券池)等得之后补上, 像上面做一个 ambigu区分\n # 遇到bug,pluto vs matic 2指代不一样的\n # Note3. contractstatus, contracttype 有些标准乱,以后有用处理\n # dict_contractstatus_fmt = {'部分归还': '部分归还', '未形成负债': None, '已归还': '已归还',\n # '0': '开仓未归还', '1': '部分归还', '5': None,\n # '2': '已归还/合约过期', '3': None,\n # '未归还': '开仓未归还', '自行了结': None} # 有bug了...pluto vs matic\n #\n # dict_contracttype_fmt = {'融券': 'rq', '融资': 'rz',\n # '1': 'rq', '0': 'rz',\n # '2': '其它负债/???'} # 一般没有融资, 其它负债(2)\n\n if sheet_type == 'fund': # cash\n list_dicts_fund = raw_list\n # print(list_dicts_fund)\n if list_dicts_fund is None:\n list_dicts_fund = []\n for dict_fund in list_dicts_fund:\n data_source = dict_fund['DataSourceType']\n cash = None\n avlfund = None # 'AvailableFund'\n ttasset = None # 'TotalAsset'\n mktvalue = None\n netasset = None\n kqzj = None # 可取资金\n total_liability = None\n\n # 分两种情况: 1. cash acct: 至少要有cash 2. margin acct: 至少要有ttasset\n\n flag_check_new_name = True # 用来弥补之前几个list的缺漏\n for field_af in list_fields_af:\n if field_af in dict_fund:\n avlfund = float(dict_fund[field_af])\n # todo patchdata fund 处理 有的券商负债的券不一样\n flag_check_new_name = False\n err = 'unknown available_fund name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_fund)\n logger_expo.debug((err, dict_fund))\n\n if accttype == 'm':\n flag_check_new_name = True\n for field_ttasset in list_fields_ttasset:\n if field_ttasset in dict_fund:\n ttasset = float(dict_fund[field_ttasset])\n flag_check_new_name = False\n err = 'unknown total asset name %s'%data_source\n if flag_check_new_name:\n if data_source not in ['gy_htpb', 'gs_htpb']:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_fund)\n logger_expo.debug((err, dict_fund))\n else:\n ttasset = float(dict_fund['产品总资产'])\n\n flag_check_new_name = True\n for field_mktv in list_fields_mktvalue:\n if field_mktv in dict_fund:\n mktvalue = float(dict_fund[field_mktv])\n flag_check_new_name = False\n err = 'unknown total market value name %s'%data_source\n if flag_check_new_name:\n if data_source not in ['gtja_pluto']:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_fund)\n logger_expo.debug((err, dict_fund))\n else:\n cash = ttasset - mktvalue\n\n # 读取净资产,总负债,或者两者之中推出另一个\n for field_na in list_fields_na:\n if field_na in dict_fund:\n netasset = float(dict_fund[field_na])\n\n for field_tl in list_fields_tl:\n if field_tl in dict_fund:\n total_liability = float(dict_fund[field_tl])\n\n if total_liability and netasset:\n delta = total_liability + netasset - ttasset\n if abs(delta) > 1:\n err = '券商%s数据错误:总资产 - 总负债 - 净资产 =%d'%(data_source, -delta)\n if err not in self.list_warn:\n self.list_warn.append(err)\n logger_expo.error((err, dict_fund))\n print(err, dict_fund)\n # 默认总资产正确:\n netasset = ttasset - total_liability\n else:\n if data_source in ['gy_htpb', 'gs_htpb', 'gj_htpb']:\n netasset = float(dict_fund['产品净值'])\n elif data_source in []: # 没有净资产等字段\n pass\n elif not(total_liability is None):\n netasset = ttasset - total_liability\n elif not(netasset is None):\n total_liability = ttasset - netasset\n else:\n err = 'unknown net asset or liability name %s'%data_source\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_fund)\n logger_expo.debug((err, dict_fund))\n\n else:\n flag_check_new_name = True\n for field_ttasset in list_fields_ttasset + list_fields_na:\n if field_ttasset in dict_fund:\n ttasset = float(dict_fund[field_ttasset])\n flag_check_new_name = False\n err = 'unknown total asset name %s'%data_source\n if flag_check_new_name:\n if data_source not in ['gy_htpb', 'gs_htpb', 'gj_htpb']:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_fund)\n logger_expo.debug((err, dict_fund))\n else:\n ttasset = float(dict_fund['产品总资产'])\n netasset = ttasset\n total_liability = 0\n cash = avlfund\n\n flag_check_new_name = True\n for field_kqzj in list_fields_kqzj:\n if field_kqzj in dict_fund:\n kqzj = float(dict_fund[field_kqzj])\n flag_check_new_name = False\n err = 'unknown 可取资金 name %s'%data_source\n if flag_check_new_name and data_source not in ['gf_tyt', 'zhaos_xtpb']: # 他们没有可取\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_fund)\n logger_expo.debug((err, dict_fund))\n # flt_cash = flt_ttasset - stock_longamt - etf_longamt - ce_longamt\n\n dict_fund_fmtted = {\n 'DataDate': self.str_day,\n 'UpdateTime': self.record_fmt_time,\n 'AcctIDByMXZ': acctidbymxz,\n 'DataSourceType': data_source,\n 'Cash': cash,\n 'NetAsset': netasset,\n 'AvailableFund': avlfund, # flt_approximate_na?\n 'TotalAsset': ttasset,\n 'TotalLiability': total_liability,\n 'KQZJ': kqzj # 总股本*每股价值 = 证券市值, 之后补上\n }\n list_dicts_fmtted.append(dict_fund_fmtted)\n elif sheet_type == 'holding': # holding\n # 2.整理holding\n # 2.1 rawdata(无融券合约账户)\n list_dicts_holding = raw_list\n\n for dict_holding in list_dicts_holding: # 不必 list_dicts_holding.keys()\n secid = None\n secidsrc = None\n symbol = None\n data_source = dict_holding['DataSourceType']\n longqty = 0\n # shortqty = 0\n flag_check_new_name = True\n for field_secid in list_fields_secid:\n if field_secid in dict_holding:\n secid = str(dict_holding[field_secid])\n flag_check_new_name = False\n err = 'unknown secid name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_holding)\n logger_expo.debug((err, dict_holding))\n\n flag_check_new_name = True\n for field_shareholder_acctid in list_fields_shareholder_acctid:\n if field_shareholder_acctid in dict_holding:\n shareholder_acctid = str(dict_holding[field_shareholder_acctid])\n if shareholder_acctid[0].isalpha():\n secidsrc = 'SSE'\n if shareholder_acctid[0].isdigit():\n secidsrc = 'SZSE'\n flag_check_new_name = False\n\n for field_exchange in list_fields_exchange:\n if field_exchange in dict_holding:\n try:\n if data_source in dict_ambigu_secidsrc:\n digit_exchange = str(dict_holding[field_exchange])\n secidsrc = dict_ambigu_secidsrc[data_source][digit_exchange]\n else:\n exchange = dict_holding[field_exchange]\n secidsrc = dict_exchange2secidsrc[exchange]\n except KeyError as err:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_holding)\n logger_expo.debug((err, dict_holding))\n flag_check_new_name = False\n break\n err = 'unknown security source name %s'%data_source\n if flag_check_new_name:\n secidsrc = self.id2source.find_exchange(secid)\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err)\n logger_expo.warning(err)\n\n flag_check_new_name = True\n for field_symbol in list_fields_symbol:\n if field_symbol in dict_holding:\n symbol = str(dict_holding[field_symbol])\n flag_check_new_name = False\n err = 'unknown symbol name %s'%data_source\n if flag_check_new_name:\n if data_source in ['hait_ehfz_api', 'yh_apama', 'gf_tyt']:\n symbol = '???' # 不管,需要可以用wind获取\n else:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_holding)\n logger_expo.debug((err, dict_holding))\n\n flag_check_new_name = True\n for field_longqty in list_fields_longqty:\n if field_longqty in dict_holding:\n longqty = float(dict_holding[field_longqty])\n flag_check_new_name = False\n err = 'unknown longqty name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_holding)\n logger_expo.debug((err, dict_holding))\n\n windcode_suffix = {'SZSE': '.SZ', 'SSE': '.SH'}[secidsrc]\n windcode = secid + windcode_suffix\n sectype = get_sectype_from_code(windcode)\n\n dict_holding_fmtted = {\n 'DataDate': self.str_day,\n 'UpdateTime': self.record_fmt_time,\n 'AcctIDByMXZ': acctidbymxz,\n 'DataSourceType': data_source,\n 'SecurityID': secid,\n 'SecurityType': sectype,\n 'Symbol': symbol,\n 'SecurityIDSource': secidsrc,\n 'LongQty': longqty,\n 'ShortQty': 0,\n 'LongAmt': None,\n 'ShortAmt': 0,\n 'NetAmt': None\n }\n list_dicts_fmtted.append(dict_holding_fmtted)\n\n elif sheet_type == 'order': # 3.order\n list_dicts_order = raw_list\n\n for dict_order in list_dicts_order:\n secid = None\n secidsrc = None\n symbol = None\n leavesqty = None\n cumqty = None\n side = None\n orderqty = None\n transtime = None\n avgpx = None\n sernum = None\n data_source = dict_order['DataSourceType']\n\n flag_check_new_name = True\n for field_secid in list_fields_secid:\n if field_secid in dict_order:\n secid = str(dict_order[field_secid])\n flag_check_new_name = False\n err = 'unknown secid name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n flag_check_new_name = True\n for field_shareholder_acctid in list_fields_shareholder_acctid:\n if field_shareholder_acctid in dict_order:\n shareholder_acctid = str(dict_order[field_shareholder_acctid])\n if shareholder_acctid[0].isalpha():\n secidsrc = 'SSE'\n if shareholder_acctid[0].isdigit():\n secidsrc = 'SZSE'\n flag_check_new_name = False\n\n for field_exchange in list_fields_exchange:\n if field_exchange in dict_order:\n try:\n if data_source in dict_ambigu_secidsrc:\n digit_exchange = dict_order[field_exchange]\n secidsrc = dict_ambigu_secidsrc[data_source][digit_exchange]\n else:\n exchange = dict_order[field_exchange]\n secidsrc = dict_exchange2secidsrc[exchange]\n except KeyError as err:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug(err, dict_order)\n flag_check_new_name = False\n err = 'unknown security source name %s'%data_source\n if flag_check_new_name:\n secidsrc = self.id2source.find_exchange(secid)\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err)\n logger_expo.warning(err)\n\n flag_check_new_name = True\n for field_symbol in list_fields_symbol:\n if field_symbol in dict_order:\n symbol = str(dict_order[field_symbol])\n flag_check_new_name = False\n err = 'unknown symbol name %s'%data_source\n if flag_check_new_name:\n if data_source in ['hait_ehfz_api', 'yh_apama', 'gf_tyt']:\n symbol = '???' # 不管,他们不给symbol需要可以用wind获取\n else:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n windcode_suffix = {'SZSE': '.SZ', 'SSE': '.SH'}[secidsrc]\n windcode = secid + windcode_suffix\n sectype = get_sectype_from_code(windcode)\n\n flag_check_new_name = True\n for field_cumqty in list_fields_cumqty:\n if field_cumqty in dict_order:\n cumqty = dict_order[field_cumqty]\n flag_check_new_name = False\n err = 'unknown cumqty name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n flag_check_new_name = True\n for field_leavesqty in list_fields_leavesqty:\n if field_leavesqty in dict_order:\n leavesqty = dict_order[field_leavesqty]\n flag_check_new_name = False\n err = 'unknown leavesqty name %s'%data_source\n if flag_check_new_name:\n if data_source in ['yh_apama']:\n pass\n else:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n if data_source == 'huat_matic_tsi':\n entrust_bs = int(dict_order['entrust_bs'])\n entrust_type = int(dict_order['entrust_type'])\n try: # entrust_type: 0普通委托, 2撤单, 6融资, 7融券, 9信用交易\n side = {(9, 1): 'buy', (9, 2): 'sell', (7, 2): 'sell short', # 6: 融资买入/卖券还款\n (7, 1): 'MQHQ', (6, 1): 'buy', (6, 2): 'sell',\n (0, 1): 'buy', (0, 2): 'sell'}[(entrust_type, entrust_bs)]\n except KeyError:\n side = 'cancel'\n else:\n flag_check_new_name = True\n for field_side in list_fields_side:\n if field_side in dict_order:\n if data_source in dict_ambigu_side_name:\n digit_side = dict_order[field_side]\n side = dict_ambigu_side_name[data_source][digit_side]\n else:\n str_side = dict_order[field_side]\n side = dict_fmtted_side_name[str_side]\n flag_check_new_name = False\n err = 'unknown side name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n flag_check_new_name = True\n for field_orderqty in list_fields_orderqty:\n if field_orderqty in dict_order:\n orderqty = dict_order[field_orderqty]\n flag_check_new_name = False\n err = 'unknown orderqty name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n flag_check_new_name = True\n for field_transtime in list_fields_ordertime:\n if field_transtime in dict_order:\n transtime = dict_order[field_transtime]\n # 转化成统一时间格式\n datetime_obj = None\n for time_format in list_time_format:\n try:\n datetime_obj = datetime.datetime.strptime(transtime, time_format)\n except ValueError:\n pass\n if datetime_obj:\n transtime = datetime_obj.strftime('%H%M%S')\n else:\n err = 'unknown transtime format %s'%data_source\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n flag_check_new_name = False\n err = 'unknown transaction time name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n flag_check_new_name = True\n for field_sernum in list_fields_sernum:\n if field_sernum in dict_order:\n sernum = str(dict_order[field_sernum])\n flag_check_new_name = False\n err = 'unknown serial number name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n flag_check_new_name = True\n for field_avgpx in list_fields_avgpx:\n if field_avgpx in dict_order:\n avgpx = float(dict_order[field_avgpx])\n flag_check_new_name = False\n err = 'unknown average price name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_order)\n logger_expo.debug((err, dict_order))\n\n dict_order_fmtted = {\n 'DataDate': self.str_day,\n 'UpdateTime': self.record_fmt_time,\n 'AcctIDByMXZ': acctidbymxz,\n 'DataSourceType': data_source,\n 'SecurityID': secid,\n 'SerialNumber': sernum,\n 'SecurityType': sectype,\n 'Symbol': symbol,\n 'SecurityIDSource': secidsrc,\n 'CumQty': cumqty,\n 'Side': side,\n 'OrdQty': orderqty,\n 'LeavesQty': leavesqty,\n 'TransactTime': transtime,\n 'AvgPx': avgpx\n }\n\n list_dicts_fmtted.append(dict_order_fmtted)\n elif sheet_type == 'secloan':\n list_dicts_secloan = raw_list\n for dict_secloan in list_dicts_secloan:\n secid = None\n secidsrc = None\n symbol = None\n # longqty = 0\n shortqty = 0\n contractstatus = None\n contracttype = None\n contractqty = None\n opdate = None\n sernum = None\n compositesrc = None\n data_source = dict_secloan['DataSourceType']\n\n flag_check_new_name = True\n for field_secid in list_fields_secid:\n if field_secid in dict_secloan:\n secid = str(dict_secloan[field_secid])\n flag_check_new_name = False\n err = 'unknown field_secid name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug((err, dict_secloan))\n\n flag_check_new_name = True\n for field_shareholder_acctid in list_fields_shareholder_acctid:\n if field_shareholder_acctid in dict_secloan:\n shareholder_acctid = str(dict_secloan[field_shareholder_acctid])\n if len(shareholder_acctid) == 0:\n continue\n if shareholder_acctid[0].isalpha():\n secidsrc = 'SSE'\n if shareholder_acctid[0].isdigit():\n secidsrc = 'SZSE'\n flag_check_new_name = False\n\n for field_exchange in list_fields_exchange:\n if field_exchange in dict_secloan:\n try:\n if data_source in dict_ambigu_secidsrc:\n digit_exchange = dict_secloan[field_exchange]\n secidsrc = dict_ambigu_secidsrc[data_source][digit_exchange]\n else:\n exchange = dict_secloan[field_exchange]\n secidsrc = dict_exchange2secidsrc[exchange]\n except KeyError as err:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug(err, dict_secloan)\n flag_check_new_name = False\n err = 'unknown security source name %s'%data_source\n if flag_check_new_name:\n secidsrc = self.id2source.find_exchange(secid)\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err)\n logger_expo.warning(err)\n\n flag_check_new_name = True\n for field_symbol in list_fields_symbol:\n if field_symbol in dict_secloan:\n symbol = str(dict_secloan[field_symbol])\n flag_check_new_name = False\n err = 'unknown field symbol name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug((err, dict_secloan))\n\n flag_check_new_name = True\n for field_shortqty in list_fields_shortqty:\n if field_shortqty in dict_secloan:\n shortqty = float(dict_secloan[field_shortqty])\n flag_check_new_name = False\n err = 'unknown field shortqty name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug((err, dict_secloan))\n\n flag_check_new_name = True\n for field_contractqty in list_fields_contractqty:\n if field_contractqty in dict_secloan:\n contractqty = str(dict_secloan[field_contractqty])\n flag_check_new_name = False\n err = 'unknown field contractqty name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug((err, dict_secloan))\n\n flag_check_new_name = True\n for field_sernum in list_fields_sernum:\n if field_sernum in dict_secloan:\n sernum = str(dict_secloan[field_sernum])\n flag_check_new_name = False\n err = 'unknown field serum name %s'%data_source\n if flag_check_new_name:\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug((err, dict_secloan))\n\n # flag_check_new_name = True\n # for field_contractstatus in list_fields_contractstatus:\n # if field_contractstatus in dict_secloan:\n # contractstatus = str(dict_secloan[field_contractstatus])\n # if contractstatus in dict_contractstatus_fmt:\n # contractstatus = dict_contractstatus_fmt[contractstatus]\n # else:\n # logger_expo.debug('Unknown contractstatus %s'%contractstatus)\n # # if contractstatus is None:\n # # raise Exception('During Clearing, we can not have ambiguous status in the compact')\n # flag_check_new_name = False\n #\n # if flag_check_new_name:\n # logger_expo.debug(('unknown field_contractstatus name', dict_secloan))\n\n # flag_check_new_name = True\n # for field_contracttype in list_fields_contracttype:\n # if field_contracttype in dict_secloan:\n # contracttype = str(dict_secloan[field_contracttype])\n # if contracttype in dict_contracttype_fmt:\n # contracttype = dict_contracttype_fmt[contracttype]\n # else:\n # logger_expo.debug('Unknown contractstatus %s'%contracttype)\n # flag_check_new_name = False\n # if flag_check_new_name:\n # if data_source != 'hait_ehfz_api':\n # logger_expo.debug(('unknown field_contracttype name', dict_secloan))\n\n flag_check_new_name = True\n for field_opdate in list_fields_opdate:\n if field_opdate in dict_secloan:\n opdate = str(dict_secloan[field_opdate])\n flag_check_new_name = False\n datetime_obj = None\n # 和order共用 date格式\n for date_format in list_date_format:\n try:\n datetime_obj = datetime.datetime.strptime(opdate, date_format)\n except ValueError:\n pass\n if datetime_obj:\n opdate = datetime_obj.strftime('%Y%m%d')\n else:\n err = 'Unrecognized trade date format %s'%data_source\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug((err, dict_secloan))\n\n if flag_check_new_name:\n err = 'unknown field opdate name %s'%data_source\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug((err, dict_secloan))\n\n flag_check_new_name = True\n for field_compositesrc in list_fields_compositesrc:\n if field_compositesrc in dict_secloan:\n compositesrc = str(dict_secloan[field_compositesrc])\n flag_check_new_name = False\n if flag_check_new_name and list_fields_compositesrc:\n err = 'unknown field_compositesrc name %s'%data_source\n if err not in self.list_warn:\n self.list_warn.append(err)\n print(err, dict_secloan)\n logger_expo.debug((err, dict_secloan))\n\n # print(secidsrc)\n windcode_suffix = {'SZSE': '.SZ', 'SSE': '.SH'}[secidsrc]\n windcode = secid + windcode_suffix\n sectype = get_sectype_from_code(windcode)\n\n dict_secloan_fmtted = {\n 'DataDate': self.str_day,\n 'AcctIDByMXZ': acctidbymxz,\n 'DataSourceType': data_source,\n 'UpdateTime': self.record_fmt_time,\n 'SecurityID': secid,\n 'SecurityType': sectype,\n 'Symbol': symbol,\n 'SecurityIDSource': secidsrc,\n 'SerialNumber': sernum,\n 'OpenPositionDate': opdate, # = tradeDate?loan是交易吗?感觉FIX里是\n 'ContractStatus': contractstatus,\n 'ContractType': contracttype,\n 'ContractQty': contractqty,\n 'CompositeSource': compositesrc,\n 'ShortQty': shortqty,\n 'ShortAmt': None\n }\n list_dicts_fmtted.append(dict_secloan_fmtted)\n else:\n raise ValueError('Unknown f_h_o_s_mark')\n elif accttype in ['f'] and patchpath is None:\n list_dicts_future_fund = raw_list\n for dict_fund_future in list_dicts_future_fund:\n avlfund = dict_fund_future['DYNAMICBALANCE']\n acctidbymxz = dict_fund_future['AcctIDByMXZ']\n kqzj = dict_fund_future['USABLECURRENT']\n dict_future_fund_fmtted = {\n 'DataDate': self.str_day,\n 'UpdateTime': self.record_fmt_time,\n 'AcctIDByMXZ': acctidbymxz,\n 'DataSourceType': 'trader_api',\n 'Cash': avlfund, # 期货户里不能拿券当担保品,全是现金\n 'NetAsset': avlfund,\n 'AvailableFund': avlfund,\n 'TotalAsset': None, # 总资产大致是LongAmt\n 'TotalLiability': None,\n 'KQZJ': kqzj # 总股本*每股价值 = 证券市值, 之后补上\n }\n list_dicts_fmtted.append(dict_future_fund_fmtted)\n # 期货holding直接放到 position里\n elif patchpath:\n if accttype == 'o':\n # todo patch 里场外暂时放放\n pass\n else:\n df = pd.read_excel(patchpath, dtype=str, sheet_name=sheet_type)\n df = df.where(df.notnull(), None)\n for i, row in df.iterrows():\n doc = dict(row)\n doc['UpdateTime'] = self.record_fmt_time\n doc['DataDate'] = self.str_day\n list_dicts_fmtted.append(doc)\n else:\n logger_expo.debug('Unknown account type in basic account info.')\n return list_dicts_fmtted\n\n @run_process\n def update_fmtdata(self):\n self.record_fmt_time = datetime.datetime.today().strftime('%H%M%S')\n self.record_update_raw_time = col_global_var.find_one({'DataDate': self.str_day})['RawUpdateTime']\n list_dicts_acctinfo = list(\n self.col_acctinfo.find({'DataDate': self.str_day, 'DataDownloadMark': '1'})) # {'_id': 0}隐藏\n list_dicts_patch = list(client_local_main['basic_info']['data_patch'].find({'DataDate': self.str_day}))\n dict_acct2patch = {}\n for _ in list_dicts_patch:\n acctid = _['AcctIDByMXZ']\n if acctid in dict_acct2patch:\n dict_acct2patch[acctid].append(_)\n else:\n dict_acct2patch[acctid] = [_]\n\n dict_raw_col = {}\n if self.is_trading_time:\n database = self.db_trddata\n dict_raw_col['future'] = {'fund': database['trade_future_api_fund']}\n dict_raw_col['stock'] = {'fund': database['trade_rawdata_fund'],\n 'holding': database['trade_rawdata_holding'],\n 'order': database['trade_rawdata_order'],\n 'secloan': database['trade_rawdata_secloan']}\n\n dict_fmt_col = {'fund': database['trade_fmtdata_fund'],\n 'holding': database['trade_fmtdata_holding'],\n 'order': database['trade_fmtdata_order'],\n 'secloan': database['trade_fmtdata_secloan']}\n dict_shtype2listFmtted = {'fund': [], 'holding': [], 'order': [], 'secloan': []}\n else:\n dict_raw_col['future'] = {}\n database = self.db_posttrddata\n dict_raw_col['stock'] = {'fund': database['post_trade_rawdata_fund'],\n 'holding': database['post_trade_rawdata_holding'],\n 'secloan': database['post_trade_rawdata_secloan']}\n dict_fmt_col = {'fund': database['post_trade_fmtdata_fund'],\n 'holding': database['post_trade_fmtdata_holding'],\n 'secloan': database['post_trade_fmtdata_secloan']}\n dict_shtype2listFmtted = {'fund': [], 'holding': [], 'secloan': []}\n\n # Note3 只下载一遍, 根据future; stock分成不同词典, 通过dict_raw_col, 对每一种sheet type(fund....),都只下载一边,存成\n # 关于acctidbymxz的字典: 三层: {stock:{fund:{acctid: [准备format的list]}}}\n dict3d_acctid2rawList = {'future': {}, 'stock': {}}\n for general_type in dict_raw_col:\n for sheet_type in dict_raw_col[general_type]:\n col = dict_raw_col[general_type][sheet_type]\n dict_acctid2rawList = {}\n for _ in col.find({'DataDate': self.str_day}):\n acctid = _[\"AcctIDByMXZ\"]\n if acctid in dict_acctid2rawList:\n dict_acctid2rawList[acctid].append(_)\n else:\n dict_acctid2rawList[acctid] = [_]\n dict3d_acctid2rawList[general_type].update({sheet_type: dict_acctid2rawList})\n\n # dict_mark2listFmtted = {'future': {}, 'stock': {}}\n # dict_shtype2listFmtted = {'fund': [], 'holding': [], 'order': [], 'secloan': []}\n for dict_acctinfo in list_dicts_acctinfo:\n acctidbymxz = dict_acctinfo['AcctIDByMXZ']\n accttype = dict_acctinfo['AcctType']\n general_type = {'f': 'future', 'c': 'stock', 'm': 'stock', 'o': 'stock'}[accttype]\n patchpaths = {}\n if dict_acctinfo['PatchMark'] == '1':\n for _ in dict_acct2patch[acctidbymxz]:\n patchpaths[_['SheetName']] = _['DataFilePath']\n # time_cycle1 = time.time()\n for sheet_type in dict3d_acctid2rawList[general_type].keys():\n if sheet_type in patchpaths:\n patchpath = patchpaths[sheet_type]\n else:\n patchpath = None\n # 有patch就不从数据库里取\n if acctidbymxz in dict3d_acctid2rawList[general_type][sheet_type] and patchpath is None:\n raw_list = dict3d_acctid2rawList[general_type][sheet_type][acctidbymxz]\n elif patchpath:\n raw_list = None\n else:\n continue\n # Note3. raw_list {stock:{fund:{acctid: [准备format的list]}}}里的 ‘准备format的list’\n list_dicts_fmtted = self.formulate_raw_data(acctidbymxz, accttype, patchpath, sheet_type, raw_list)\n dict_shtype2listFmtted[sheet_type] += list_dicts_fmtted\n\n # time_cycle2 = time.time()\n # print(acctidbymxz, time_cycle2 - time_cycle1)\n for sheet_type in dict_shtype2listFmtted:\n list_dicts_fmtted = dict_shtype2listFmtted[sheet_type]\n target_collection = dict_fmt_col[sheet_type]\n if list_dicts_fmtted and self.is_trading_time:\n # target_collection.delete_many({'DataDate': self.str_day, 'UpdateTime': self.record_fmt_time})\n # 默认record_fmt_time是新时间\n target_collection.insert_many(list_dicts_fmtted)\n\n if list_dicts_fmtted and not self.is_trading_time:\n target_collection.delete_many({'DataDate': self.str_day}) # post 只上传一次\n target_collection.insert_many(list_dicts_fmtted)\n # print('1', time.time() - tim2, '2', tim2-tim1)\n col_global_var.update_one({'DataDate': self.str_day}, {'$set': {\n 'RawFinished': False, 'FmtFinished': True, 'FmtUpdateTime': self.record_fmt_time}})\n return\n\n def run(self):\n fmt_threading = threading.Thread(target=self.update_fmtdata)\n fmt_threading.start()\n\n\nclass Position:\n def __init__(self):\n # w.start()\n self.dt_day, self.str_day, self.is_trading_day, self.is_trading_time = ini_time_records()\n self.record_fmt_time = None\n self.record_position_time = None\n self.id2source = ID2Source(client_local_main['basic_info'], 'data/security_id.xlsx')\n\n self.col_acctinfo = client_local_main['basic_info']['acctinfo']\n self.db_trddata = client_local_main['trade_data']\n self.db_posttrddata = client_local_main['post_trade_data']\n self.dict_future2multiplier = {'IC': 200, 'IH': 300, 'IF': 300}\n self.gl_var_last = client_local_main['global_var']['last']\n\n self.warn_list = []\n # REDIS_HOST = '47.103.187.110'\n # REDIS_PORT = 6379\n # REDIS_PASS = 'Ms123456'\n # self.rds = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASS)\n\n self.event = threading.Event()\n self.lock = threading.Lock()\n return\n #\n # def get_order_last_from_wind(self, list_secid_query):\n # # we do query only for securities in our account, secid should be type of wind\n # # w.wsq(\"600000.SH\", \"rt_last,rt_latest\", func=DemoWSQCallback)\n # if list_secid_query:\n # docs = []\n # dict_wcode2last = {}\n # last_from_wind = w.wsq(list_secid_query, \"rt_last\") # 实时快照现价\n # if last_from_wind.ErrorCode == 0:\n # dict_wcode2last = dict(zip(last_from_wind.Codes, last_from_wind.Data[0]))\n # for key in dict_wcode2last:\n # dt = last_from_wind.Times[0]\n # doc = {'TransactTime': dt.strftime(\"%H%M%S\"), 'DataDate': dt.strftime(\"%Y%m%d\"),\n # 'LastPx': dict_wcode2last[key], 'WindCode': key}\n # docs.append(doc)\n # elif last_from_wind.ErrorCode == -40520010:\n # pass\n # else:\n # raise Exception(last_from_wind.Data[0][0]) # Error Msg here\n # if docs:\n # self.db_trddata['wind_last'].insert_many(docs)\n # return dict_wcode2last\n # else:\n # return {}\n #\n # def get_order_last_from_redis(self, list_windcode):\n # list_rediskey = []\n # length = len(list_windcode)\n # for i in range(length):\n # list_rediskey.append('market_'+list_windcode[i])\n # list_byte_rds = self.rds.mget(list_rediskey)\n # dict_patch = {'511990.SH': 100, '000016': 1.17, }\n # dict_windcode2last = {}\n # for i in range(length):\n # if list_byte_rds[i] is None:\n # dict_windcode2last.update({list_windcode[i]: None})\n # print(list_windcode[i])\n # #\n # else:\n # doc = orjson.loads(list_byte_rds[i])\n # dict_windcode2last.update({list_windcode[i]: doc['LastPx'] / 10000}) # 放大了10000倍\n #\n # return dict_windcode2last\n\n @run_process\n def update_position(self):\n self.record_fmt_time = col_global_var.find_one({'DataDate': self.str_day})['FmtUpdateTime']\n # print(yesterday)\n list_dicts_position = [] # 取名改改...\n set_windcode_to_search = set() # 防止重复\n dict_id2info = {}\n dict_pair2allcol = {} # 为了只遍历一遍各个表格,不然特别慢!\n dict_learn_secid2src = {} # 有的post里面没有source,得用fmt里的“学”\n\n list_dicts_acctinfo = list(self.col_acctinfo.find({'DataDate': self.str_day, 'DataDownloadMark': '1'}))\n for dict_acctinfo in list_dicts_acctinfo:\n acctidbymxz = dict_acctinfo['AcctIDByMXZ']\n # print('acctidbymxz', acctidbymxz)\n accttype = dict_acctinfo['AcctType']\n patchmark = dict_acctinfo['PatchMark']\n data_source = dict_acctinfo['DataSourceType']\n dict_id2info.update({acctidbymxz: [accttype, patchmark, data_source]})\n\n # Note4. pair作用: 相同的acctid, 证券对应唯一的position,但是holding,合约,order可能不止一个\n # 存成字典dict_pair2allcol: {pair: {holding:[...], order:[...], secloan: []},之后遍历每一个key\n # Note4. 有时候计算错误(实际持仓和计算的持仓不一样)的原因是市场错了 idsrc分错导致应该当成一个票子的没合并\n # Note4. 上面的dict_id2info作用在于把acctinfo拍扁成dict,pair -> acctid -> 账户信息\n for col_name in ['trade_fmtdata_order', 'trade_fmtdata_holding', 'trade_fmtdata_secloan']:\n list_to_add = list(self.db_trddata[col_name].find(\n {'DataDate': self.str_day, 'UpdateTime': self.record_fmt_time}))\n # {'$gte':},不用万一readfmt两遍(position还没结束),太多太超前会超级加倍\n for _ in list_to_add:\n sid = _['SecurityID']\n idsrc = _['SecurityIDSource']\n pair = (_['AcctIDByMXZ'], sid, idsrc, _['SecurityType'])\n if sid in dict_learn_secid2src:\n if dict_learn_secid2src[sid] != idsrc:\n dict_learn_secid2src[sid] = None # 感觉得改改\n else:\n dict_learn_secid2src.update({sid: idsrc})\n\n # set_pair_secid = set_pair_secid | {pair} # 并集\n all_doc = _.copy()\n if pair in dict_pair2allcol:\n if col_name in dict_pair2allcol[pair]:\n dict_pair2allcol[pair][col_name].append(all_doc)\n else:\n dict_pair2allcol[pair].update({col_name: [all_doc]})\n else:\n dict_pair2allcol.update({pair: {col_name: [all_doc]}})\n # post_col_name = ['fmtdata_holding', 'fmtdata_secloan']\n for col_name in ['post_trade_fmtdata_holding', 'post_trade_fmtdata_secloan']:\n list_to_add = list(self.db_posttrddata[col_name].find({'DataDate': self.str_day})) # postdata同一天9:00算\n for _ in list_to_add:\n if not ('SecurityType' in _): # 老版post里无IDSource...\n if not ('SecurityIDSource' in _):\n sid = _['SecurityID']\n if sid in dict_learn_secid2src:\n _['SecurityIDSource'] = dict_learn_secid2src[sid]\n else:\n _['SecurityIDSource'] = self.id2source.find_exchange(sid) # 因为可能要回答问题所以尽量不做\n windcode_suffix = {'SZSE': '.SZ', 'SSE': '.SH'}[_['SecurityIDSource']]\n _['SecurityType'] = get_sectype_from_code(_['SecurityID'] + windcode_suffix)\n pair = (_['AcctIDByMXZ'], _['SecurityID'], _['SecurityIDSource'], _['SecurityType'])\n # set_pair_secid = set_pair_secid | {pair} # 并集\n all_doc = _.copy()\n if pair in dict_pair2allcol:\n if col_name in dict_pair2allcol[pair]:\n dict_pair2allcol[pair][col_name].append(all_doc)\n else:\n dict_pair2allcol[pair].update({col_name: [all_doc]})\n else:\n dict_pair2allcol.update({pair: {col_name: [all_doc]}})\n for col_name in ['trade_future_api_holding']:\n list_to_add = list(self.db_trddata[col_name].find({'DataDate': self.str_day}))\n for _ in list_to_add:\n pair = (_['AcctIDByMXZ'], _['instrument_id'], _['exchange'])\n all_doc = _.copy()\n if pair in dict_pair2allcol:\n if col_name in dict_pair2allcol[pair]:\n dict_pair2allcol[pair][col_name].append(all_doc)\n else:\n dict_pair2allcol[pair].update({col_name: [all_doc]})\n else:\n dict_pair2allcol.update({pair: {col_name: [all_doc]}})\n\n for pair in dict_pair2allcol: # or pair in dict_pair2allcol.keys()\n acctidbymxz = pair[0]\n secid = pair[1]\n # if acctidbymxz == '3033_m_yh_5930' and secid == '510500':\n # print(end='')\n secidsrc = pair[2]\n sectype = None\n\n try:\n accttype, patchmark, data_source = dict_id2info[acctidbymxz]\n except KeyError:\n continue\n try:\n list_dicts_holding = dict_pair2allcol[pair]['trade_fmtdata_holding']\n except KeyError: # pair may not has 'fmtdata_holding' etc key\n list_dicts_holding = []\n try:\n list_dicts_post_holding = dict_pair2allcol[pair]['post_trade_fmtdata_holding']\n except KeyError: # pair may not has 'fmtdata_holding' etc key\n list_dicts_post_holding = []\n try:\n list_dicts_secloan = dict_pair2allcol[pair]['trade_fmtdata_secloan']\n except KeyError: # pair may not has 'fmtdata_holding' etc key\n list_dicts_secloan = []\n try:\n list_dicts_post_secloan = dict_pair2allcol[pair]['post_trade_fmtdata_secloan']\n except KeyError: # pair may not has 'fmtdata_holding' etc key\n list_dicts_post_secloan = []\n try:\n list_dicts_order = dict_pair2allcol[pair]['trade_fmtdata_order']\n except KeyError: # pair may not has 'fmtdata_holding' etc key\n list_dicts_order = []\n try:\n list_dicts_holding_future = dict_pair2allcol[pair]['trade_future_api_holding']\n except KeyError: # pair may not has 'fmtdata_holding' etc key\n list_dicts_holding_future = []\n\n if accttype in ['c', 'm', 'o'] and self.is_trading_time:\n if len(pair) == 4:\n sectype = pair[3]\n\n windcode_suffix = {'SZSE': '.SZ', 'SSE': '.SH'}[secidsrc]\n windcode = secid + windcode_suffix\n\n longqty = 0 # longqty可能准\n longqty_ref = 0\n shortqty = 0\n shortqty_ref = 0 # 实在没有postdata就用它\n dict_holding_id = 'no reference'\n dict_post_holding_id = 'no reference'\n\n if len(list_dicts_post_holding) == 1:\n longqty = float(list_dicts_post_holding[0]['LongQty'])\n dict_post_holding_id = list_dicts_post_holding[0]['_id']\n elif len(list_dicts_post_holding) == 0:\n pass\n else:\n tmax = time.strptime('0:0:0', '%H:%M:%S')\n post_holding_id = list_dicts_post_holding[0]['_id']\n for d in list_dicts_post_holding:\n t = time.strptime(d['UpdateTime'], '%H%M%S')\n if tmax < t:\n longqty = int(d['LongQty'])\n tmax = t\n post_holding_id = d['_id']\n print('The postholding has too many information', post_holding_id)\n\n if len(list_dicts_holding) == 1:\n longqty_ref = float(list_dicts_holding[0]['LongQty'])\n dict_holding_id = list_dicts_holding[0]['_id']\n elif len(list_dicts_holding) == 0:\n pass\n else:\n tmax = time.strptime('0:0:0', '%H:%M:%S')\n for d in list_dicts_holding:\n t = time.strptime(d['UpdateTime'], '%H%M%S')\n if tmax < t:\n longqty_ref = float(d['LongQty'])\n dict_holding_id = d['_id']\n tmax = t\n\n if len(list_dicts_post_secloan) > 0:\n for d in list_dicts_post_secloan:\n shortqty += float(d['ShortQty']) # 可能多个合约\n\n if len(list_dicts_secloan) > 0:\n for d in list_dicts_secloan:\n shortqty_ref += float(d['ShortQty']) # 可能多个合约\n\n for dict_order in list_dicts_order:\n # if self.str_day == dict_order['TradeDate']:\n side = dict_order['Side']\n cumqty = int(dict_order['CumQty'])\n avgpx = dict_order['AvgPx']\n if 'yh' in dict_order['AcctIDByMXZ']:\n valid_cum = True\n elif data_source == 'huat_matic_tsi' and avgpx == 0:\n # 华泰有0元成交0元委托(不算撤单,成交量不为0的奇怪情况)\n valid_cum = False\n else:\n leavesqty = int(dict_order['LeavesQty'])\n orderqty = int(dict_order['OrdQty'])\n valid_cum = (cumqty + leavesqty == orderqty)\n if valid_cum: # 交易最终态的cumqty才可以用\n if side == 'buy':\n longqty += cumqty\n elif side == 'sell':\n longqty -= cumqty\n elif side == 'sell short':\n shortqty += cumqty\n elif side == 'XQHQ':\n longqty -= cumqty\n shortqty -= cumqty\n elif side == 'MQHQ': # 导致资金变动而不是券的变动\n shortqty -= cumqty\n else: # 判断撤单\n continue\n\n # if longqty < 0: # 有的券商没有sell short说法, long就是net..\n # warnings.warn(\"LongQty is Negative: short: %f, long: %f because \"\n # \"postdata is not clean, id %s\" % (shortqty, longqty, dict_secloan_id))\n # longqty = 0\n # todo long小于0各种情况讨论。。c用户; m时有short, 无short\n\n # check\n if patchmark == '1': # 照抄\n longqty = longqty_ref\n shortqty = shortqty_ref\n elif accttype == 'c' and (data_source in broker_c_without_postdata): # Note1. 可以去掉,只作为验算\n longqty = longqty_ref\n elif data_source in broker_m_without_postdata and accttype == 'm': # 数据升级等问题导致只能抄\n longqty = longqty_ref\n shortqty = shortqty_ref\n else:\n # todo 如果有问题界面里只显示一次\n if abs(longqty - longqty_ref) > 0.01: # hait, huat, gtja OK\n err = \"\\n Please check fmtdata_holding: %s and the one in posttrade %s and order: %s \\n\" \\\n \"The alogrithm to calculate longqty of account: %s is somehow wrong! \\n\" \\\n \"longqty: %d; shortqty: %d; longqty_ref: %d\"\\\n % (dict_holding_id, dict_post_holding_id, secid, acctidbymxz, longqty, shortqty, longqty_ref)\n\n if acctidbymxz not in self.warn_list:\n print(self.record_fmt_time, ':', err)\n self.warn_list.append(acctidbymxz)\n logger_expo.error(err)\n\n longqty = longqty_ref\n shortqty = shortqty_ref\n\n # 只监控有票子的\n if longqty != 0 or shortqty != 0 or longqty_ref != 0:\n set_windcode_to_search = set_windcode_to_search | {windcode}\n dict_position = {\n 'DataDate': self.str_day,\n 'UpdateTime': None,\n 'AcctIDByMXZ': acctidbymxz,\n 'SecurityID': secid,\n 'SecurityType': sectype,\n # 'Symbol': symbol, # 有的券商没有,可加可不加\n 'SecurityIDSource': secidsrc,\n 'LongQty': longqty,\n # 'LongQty_ref': longqty_ref,\n 'ShortQty': shortqty,\n 'NetQty': longqty - shortqty,\n 'LongAmt': None,\n 'ShortAmt': None,\n 'NetAmt': None,\n 'WindCode': windcode\n }\n list_dicts_position.append(dict_position)\n\n elif accttype in ['f'] and self.is_trading_time:\n # list_dicts_holding_future_exposure_draft = []\n future_longqty = 0\n future_shortqty = 0\n secid_first_part = secid[:-4]\n dict_future2spot_windcode = {'IC': '000905.SH', 'IH': '000016.SH', 'IF': '000300.SH'}\n try: # SHFE - 'ssXXXX'格式等先不管,它们对应CTA策略\n windcode = dict_future2spot_windcode[secid_first_part]\n except:\n continue\n for dict_holding_future in list_dicts_holding_future:\n qty = dict_holding_future['position']\n direction = dict_holding_future['direction']\n\n if direction == 'buy':\n future_longqty = qty\n # future_longamt = close * future_longqty * self.dict_future2multiplier[secid_first_part]\n elif direction == 'sell':\n future_shortqty = qty\n # future_shortamt = close * future_shortqty * self.dict_future2multiplier[secid_first_part]\n else:\n raise ValueError('Unknown direction in future respond.')\n\n if future_longqty != 0 or future_shortqty != 0:\n set_windcode_to_search = set_windcode_to_search | {windcode}\n dict_position = {\n 'DataDate': self.str_day,\n 'UpdateTime': None,\n 'AcctIDByMXZ': acctidbymxz,\n 'SecurityID': secid,\n 'SecurityType': 'Index Future',\n 'Symbol': None,\n 'SecurityIDSource': secidsrc,\n 'LongQty': future_longqty,\n 'ShortQty': future_shortqty,\n 'NetQty': future_longqty - future_shortqty,\n 'LongAmt': None,\n 'ShortAmt': None,\n 'NetAmt': None,\n 'WindCode': windcode\n }\n list_dicts_position.append(dict_position)\n\n # 统一一次询问现价,节约时间,市价更加精确\n self.record_position_time = datetime.datetime.today().strftime(\"%H%M%S\")\n # self.record_wind_query_time = (datetime.datetime.today() - datetime.timedelta(hours=1, seconds=10)).strftime(\"%H%M%S\")\n\n list_windcode_to_search = list(set_windcode_to_search)\n self.gl_var_last.update_one({'Key': 'SecidQuery'}, {'$set': {'Value': list_windcode_to_search}})\n print('Getting last price from wind...')\n time.sleep(2) # wait wind_last.py\n dict_windcode2last = self.gl_var_last.find_one({'Key': 'Wcode2Last'})['Value']\n if dict_windcode2last is None:\n dict_windcode2last = {}\n iter_last = self.db_trddata['wind_last'].find({'WindCode': {'$in': list_windcode_to_search}})\n for _d in iter_last:\n dict_windcode2last.update({_d['WindCode']: _d['LastPx']})\n elif set(dict_windcode2last) != set_windcode_to_search:\n list_windcode_to_add = list(set_windcode_to_search - set(dict_windcode2last))\n iter_last = self.db_trddata['wind_last'].find({'WindCode': {'$in': list_windcode_to_add}})\n for _d in iter_last:\n dict_windcode2last.update({_d['WindCode']: _d['LastPx']})\n\n # self.gl_var_last.update_one({'Key': 'Wcode2Last'}, {'$set': {'Value': None}})\n for dict_position in list_dicts_position:\n windcode = dict_position['WindCode']\n if dict_position['SecurityType'] == 'Index Future':\n secid_first_part = dict_position['SecurityID'][:-4]\n point = self.dict_future2multiplier[secid_first_part]\n dict_position['LongAmt'] = dict_position['LongQty'] * dict_windcode2last[windcode] * point\n dict_position['ShortAmt'] = dict_position['ShortQty'] * dict_windcode2last[windcode] * point\n else:\n dict_position['LongAmt'] = dict_position['LongQty']*dict_windcode2last[windcode]\n dict_position['ShortAmt'] = dict_position['ShortQty'] * dict_windcode2last[windcode]\n dict_position['NetAmt'] = dict_position['LongAmt'] - dict_position['ShortAmt']\n dict_position['UpdateTime'] = self.record_position_time\n # print('2246', dict_position)\n # del dict_position['WindCode'] # 可删可不删\n\n # print(list_dicts_position)\n if list_dicts_position:\n self.db_trddata['trade_position'].delete_many(\n {'DataDate': self.str_day, 'UpdateTime': self.record_position_time})\n self.db_trddata['trade_position'].insert_many(list_dicts_position)\n\n col_global_var.update_one({'DataDate': self.str_day}, {'$set': {\n 'FmtFinished': False, 'PosFinished': True, 'PositionUpdateTime': self.record_position_time}})\n # print(\"Update Position finished\")\n return\n\n def run(self):\n position_thread = threading.Thread(target=self.update_position)\n position_thread.start()\n\n\nclass Exposure:\n def __init__(self):\n \"\"\"\n Incorporated inputs: (可以全局化...)\n 1.MongoClient('host:port username@admin:pwd')\n 2.path of basic_info\n 3.database names and collection names : trddata, basicinfo\n 4.date\n \"\"\"\n\n # 时间判定:交易时间;清算时间;发呆时间讨论\n\n self.dt_day, self.str_day, self.is_trading_day, self.is_trading_time = ini_time_records()\n self.record_position_time = None\n self.record_fmt_time = None\n\n self.db_trddata = client_local_main['trade_data']\n self.col_acctinfo = client_local_main['basic_info']['acctinfo']\n\n self.event = threading.Event()\n self.lock = threading.Lock()\n\n @run_process\n def exposure_analysis(self):\n self.record_position_time = col_global_var.find_one({'DataDate': self.str_day})['PositionUpdateTime']\n list_dicts_acctinfo = list(self.col_acctinfo.find({'DataDate': self.str_day, 'DataDownloadMark': '1'}))\n list_dicts_position = list(self.db_trddata['trade_position'].find({'DataDate': self.str_day, 'UpdateTime': self.record_position_time}))\n dict_acctid2list_position = {}\n # Note5. 只调用mongodb.find()一次\n # 原本:for 遍历acctid, 每次查找collection.find(acctidbymxz, datadate, updatetime),\n # 改进: 只查找一次collection.find( datadate, updatetime), 然后存成词典: {acctid: [position]}\n # 也方便汇总成一个账户的exposure\n for _ in list_dicts_position:\n acctidbymxz = _['AcctIDByMXZ']\n if acctidbymxz in dict_acctid2list_position:\n dict_acctid2list_position[acctidbymxz].append(_)\n else:\n dict_acctid2list_position[acctidbymxz] = [_]\n list_dict_acct_exposure = []\n dict_prdcode2exposure = {}\n for dict_acctinfo in list_dicts_acctinfo:\n acctidbymxz = dict_acctinfo['AcctIDByMXZ']\n accttype = dict_acctinfo['AcctType']\n prdcode = dict_acctinfo['PrdCode']\n mdm = dict_acctinfo['MonitorDisplayMark']\n if dict_acctinfo['MonitorExposureAnalysisMark'] != '0':\n acct_exposure_dict = {'AcctIDByMXZ': acctidbymxz, 'PrdCode': prdcode, 'MonitorDisplayMark': mdm,\n 'UpdateTime': self.record_position_time, 'DataDate': self.str_day,\n 'LongQty': 0, 'ShortQty': 0, 'NetQty': 0,\n 'LongAmt': 0, 'ShortAmt': 0, 'NetAmt': 0}\n if acctidbymxz in dict_acctid2list_position:\n for dict_position in dict_acctid2list_position[acctidbymxz]:\n if dict_position['SecurityType'] == 'IrrelevantItem' or dict_position['SecurityType'] == 'CE':\n continue\n else:\n for key in ['LongQty', 'ShortQty', 'NetQty', 'LongAmt', 'ShortAmt', 'NetAmt']:\n acct_exposure_dict[key] += dict_position[key]\n\n if not (prdcode in dict_prdcode2exposure):\n prdcode_exposure_dict = acct_exposure_dict.copy()\n del prdcode_exposure_dict['AcctIDByMXZ']\n dict_prdcode2exposure[prdcode] = prdcode_exposure_dict\n if accttype != 'f':\n dict_prdcode2exposure[prdcode]['StkLongAmt'] = acct_exposure_dict['LongAmt']\n dict_prdcode2exposure[prdcode]['StkShortAmt'] = acct_exposure_dict['ShortAmt']\n dict_prdcode2exposure[prdcode]['StkNetAmt'] = acct_exposure_dict['NetAmt']\n else:\n dict_prdcode2exposure[prdcode]['StkLongAmt'] = 0\n dict_prdcode2exposure[prdcode]['StkShortAmt'] = 0\n dict_prdcode2exposure[prdcode]['StkNetAmt'] = 0\n elif dict_prdcode2exposure[prdcode]['LongQty'] is None:\n pass\n else:\n # 4舍5入保留两位小数, todo 在flask展示里而不是在数据库里保留2位\n for key in ['LongQty', 'ShortQty', 'NetQty', 'LongAmt', 'ShortAmt', 'NetAmt']:\n dict_prdcode2exposure[prdcode][key] += acct_exposure_dict[key]\n acct_exposure_dict[key] = round(acct_exposure_dict[key], 2)\n if accttype != 'f':\n dict_prdcode2exposure[prdcode]['StkLongAmt'] += acct_exposure_dict['LongAmt']\n dict_prdcode2exposure[prdcode]['StkShortAmt'] += acct_exposure_dict['ShortAmt']\n dict_prdcode2exposure[prdcode]['StkNetAmt'] += acct_exposure_dict['NetAmt']\n list_dict_acct_exposure.append(acct_exposure_dict)\n\n for prdcode in dict_prdcode2exposure:\n for key in ['LongQty', 'ShortQty', 'NetQty', 'LongAmt', 'ShortAmt', 'NetAmt']:\n if dict_prdcode2exposure[prdcode][key]:\n dict_prdcode2exposure[prdcode][key] = round(dict_prdcode2exposure[prdcode][key], 2)\n\n list_dict_prdcode_exposure = list(dict_prdcode2exposure.values())\n\n # print(pd.DataFrame(list_dict_acct_exposure))\n # logger_expo.info(pd.DataFrame(list_dict_prdcode_exposure))\n if list_dict_acct_exposure:\n self.db_trddata['trade_exposure_by_acctid'].delete_many({'DataDate': self.str_day, 'UpdateTime': self.record_position_time})\n self.db_trddata['trade_exposure_by_acctid'].insert_many(list_dict_acct_exposure)\n self.db_trddata['trade_exposure_by_prdcode'].insert_many(list_dict_prdcode_exposure)\n return\n\n def run(self):\n exposure_monitoring_thread = threading.Thread(target=self.exposure_analysis)\n exposure_monitoring_thread.start()\n\n\nif __name__ == '__main__':\n read_raw = ReadRaw()\n fmt_data = FmtData()\n\n read_raw.run()\n fmt_data.run()\n if read_raw.is_trading_time:\n position = Position()\n exposure = Exposure()\n position.run()\n exposure.run()\n elif not update_postdata_manually:\n # 如果在 run_threading里的话每个都会跑3遍(run_pending把所有schedule里的都跑一边)\n while True:\n print(datetime.datetime.today().strftime(\"%d %H:%M:%S\"))\n schedule.run_pending()\n time.sleep(schedule_interval) # 7200 睡2小时\n","sub_path":"exposure_monitoring_copy.py","file_name":"exposure_monitoring_copy.py","file_ext":"py","file_size_in_byte":160613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"166636923","text":"\n\n#calss header\nclass _NIP():\n\tdef __init__(self,): \n\t\tself.name = \"NIP\"\n\t\tself.definitions = [u'If there is a nip in the air, the air outside is quite cold: ', u'an occasion when something nips a person or thing: ', u'a small amount of strong alcoholic drink: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_nip.py","file_name":"_nip.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"47755873","text":"# モデルの定義\nmodel = SLPNet(300, 4)\n\n# 損失関数の定義\ncriterion = nn.CrossEntropyLoss()\n\n# オプティマイザの定義\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-1)\n\n# 学習\nnum_epochs = 10\nlog_train = []\nlog_valid = []\nfor epoch in range(num_epochs):\n # 訓練モードに設定\n model.train()\n for inputs, labels in dataloader_train:\n # 勾配をゼロで初期化\n optimizer.zero_grad()\n\n # 順伝播 + 誤差逆伝播 + 重み更新\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # 損失と正解率の算出\n loss_train, acc_train = calculate_loss_and_accuracy(model, criterion, dataloader_train)\n loss_valid, acc_valid = calculate_loss_and_accuracy(model, criterion, dataloader_valid)\n log_train.append([loss_train, acc_train])\n log_valid.append([loss_valid, acc_valid])\n\n # チェックポイントの保存\n torch.save({'epoch': epoch, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict()}, f'checkpoint{epoch + 1}.pt')\n\n # ログを出力\n print(f'epoch: {epoch + 1}, loss_train: {loss_train:.4f}, accuracy_train: {acc_train:.4f}, loss_valid: {loss_valid:.4f}, accuracy_valid: {acc_valid:.4f}') \n\n","sub_path":"tsunoda/chapter08/76.py","file_name":"76.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"487527337","text":"# coding=utf8\n\"\"\" StrHelper Module\n\nSeveral useful helper methods for use with strings\n\"\"\"\n\n__author__ = \"Chris Nasr\"\n__copyright__ = \"Ouroboros Coding Inc.\"\n__version__ = \"1.0.0\"\n__email__ = \"chris@ouroboroscoding.com\"\n__created__ = \"2018-11-11\"\n\n# Python imports\nfrom base64 import b64encode, b64decode\nfrom random import randint\nimport sys\n\n# The sets available for the random function\n_mdRandomSets = {\n\t\"0x\":\t\"0123456789abcdef\",\n\t\"0\":\t\"01234567\",\n\t\"10\":\t\"0123456789\",\n\t\"10*\": \"123456789\",\n\t\"az\":\t\"abcdefghijklmnopqrstuvwxyz\",\n\t\"az*\":\t\"abcdefghijkmnopqrstuvwxyz\",\n\t\"AZ\":\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n\t\"AZ*\":\t\"ABCDEFGHJKLMNPQRSTUVWXYZ\",\n\t\"aZ\":\t\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n\t\"aZ*\":\t\"abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\",\n\t\"!\":\t\"!@#$%^&*-_+.?\",\n\t\"!*\":\t\"!@$^*-_.\"\n}\n\ndef bytes_human(num, suffix='B'):\n\t\"\"\"Bytes Human\n\n\tReturns the size of bytes in the closest binary prefix so that they are\n\tclearly understood by humans\n\n\tArguments:\n\t\tnum (uint): The bytes to convert to human readable\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\n\tfor unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:\n\n\t\tif abs(num) < 1024.0:\n\t\t\treturn \"%3.1f%sB\" % (num, unit)\n\n\t\tnum /= 1024.0\n\n\treturn \"%.1fYiB\" % num\n\ndef decrypt(key, val):\n\t\"\"\"Decrypt\n\n\tDecrypts a string using the key and returns it. Key must be in multiples of\n\t16 bytes\n\n\tArguments:\n\t\tkey (str): A key that was used to encrypt the original value\n\t\tval (str): The value to decrypt\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\n\t# Load PyCrypto\n\ttry:\n\t\tfrom Cryptodome.Cipher import AES\n\texcept Exception as e:\n\t\tprint('%s\\n' % str(e))\n\t\treturn None\n\n\t# base64 decode the value; this can explode because of padding errors\n\ttry: val = b64decode(val)\n\texcept TypeError: return None\n\n\t# Recreate the IV\n\tsIV = val[:16]\n\n\t# Strip out the IV from the encrypted value\n\tval = val[16:]\n\n\t# Create the cipher and store the decrypted value\n\toC = AES.new(key, AES.MODE_CFB, sIV, segment_size=128)\n\n\t# Return the decrypted value\n\treturn oC.decrypt(val)\n\ndef digits(val):\n\t\"\"\"Digits\n\n\tReturns only the digits in the string\n\n\tArguments:\n\t\tval (str): The string to strip all non-digit characters from\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\n\t# Init list of valid characters\n\tlRet = []\n\n\t# Go through each character in the string and only keep it if it's a digit\n\tfor c in val:\n\t\tif c.isdigit():\n\t\t\tlRet.append(c)\n\n\t# Return the new string\n\treturn ''.join(lRet)\n\ndef encrypt(key, val):\n\t\"\"\"Encrypt\n\n\tEncrypts a string using the passed key and returns it. Key must be in\n\tmultiples of 16 bytes\n\n\tArguments:\n\t\tkey (str): The key used to encrypt the value\n\t\tval (str): The value to encrypt and return\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\n\t# Try to load PyCrypto\n\ttry:\n\t\tfrom Crypto import Random\n\t\tfrom Cryptodome.Cipher import AES\n\texcept Exception as e:\n\t\tprint('%s\\n' % str(e))\n\t\treturn None\n\n\t# Generate an IV\n\tsIV = Random.new().read(AES.block_size)\n\n\t# Create a new cipher using the key and the IV\n\toC = AES.new(key, AES.MODE_CFB, sIV, segment_size=128)\n\n\t# Encrypt the value\n\tval = oC.encrypt(val)\n\n\t# Add the IV\n\tval = '%s%s' % (sIV, val)\n\n\t# Return the entire thing as a base 64 encoded string\n\treturn b64encode(val)\n\ndef normalize(val):\n\t\"\"\"Normalize\n\n\tReplaces all special alpha characters with their ascii equivalent\n\n\tArgs:\n\t\tval (str): The text to normalize\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\treturn strtr(val, {\n\t\t'Ъ': \"'\", 'ъ': \"'\", 'Ь': \"'\", 'ь': \"'\",\n\n\t\t'Á': 'A', 'Ă': 'A', 'Ắ': 'A', 'Ặ': 'A', 'Ằ': 'A', 'Ẳ': 'A', 'Ẵ': 'A',\n\t\t'Ǎ': 'A', 'Â': 'A', 'Ấ': 'A', 'Ậ': 'A', 'Ầ': 'A', 'Ẩ': 'A', 'Ẫ': 'A',\n\t\t'Ä': 'A', 'Ǟ': 'A', 'Ȧ': 'A', 'Ǡ': 'A', 'Ạ': 'A', 'Ȁ': 'A', 'À': 'A',\n\t\t'Ả': 'A', 'Ȃ': 'A', 'Ā': 'A', 'Ą': 'A', 'Å': 'A', 'Ǻ': 'A', 'Ḁ': 'A',\n\t\t'Ⱥ': 'A', 'Ã': 'A', 'Ɐ': 'A', 'ᴀ': 'A',\n\t\t 'á': 'a', 'ă': 'a', 'ắ': 'a', 'ặ': 'a', 'ằ': 'a', 'ẳ': 'a', 'ẵ': 'a',\n\t\t 'ǎ': 'a', 'â': 'a', 'ấ': 'a', 'ậ': 'a', 'ầ': 'a', 'ẩ': 'a', 'ẫ': 'a',\n\t\t 'ä': 'a', 'ǟ': 'a', 'ȧ': 'a', 'ǡ': 'a', 'ạ': 'a', 'ȁ': 'a', 'à': 'a',\n\t\t 'ả': 'a', 'ȃ': 'a', 'ā': 'a', 'ą': 'a', 'ᶏ': 'a', 'ẚ': 'a', 'å': 'a',\n\t\t 'ǻ': 'a', 'ḁ': 'a', 'ⱥ': 'a', 'ã': 'a', 'ɐ': 'a', 'ₐ': 'a', 'А': 'a',\n\t\t 'а': 'a',\n\n\t\t'Ꜳ': 'AA', 'Æ': 'AE', 'Ǽ': 'AE', 'Ǣ': 'AE', 'ᴁ': 'AE', 'Ꜵ': 'AO',\n\t\t'Ꜷ': 'AU', 'Ꜹ': 'AV', 'Ꜻ': 'AV', 'Ꜽ': 'AY',\n\t\t'ꜳ': 'aa', 'æ': 'ae', 'ǽ': 'ae', 'ǣ': 'ae', 'ᴂ': 'ae', 'ꜵ': 'ao',\n\t\t'ꜷ': 'au', 'ꜹ': 'av', 'ꜻ': 'av', 'ꜽ': 'ay',\n\n\t\t'Ḃ': 'B', 'Ḅ': 'B', 'Ɓ': 'B', 'Ḇ': 'B', 'Ƀ': 'B', 'Ƃ': 'B', 'ʙ': 'B',\n\t\t'ᴃ': 'B', 'Б': 'B',\n\t\t'ḃ': 'b', 'ḅ': 'b', 'ɓ': 'b', 'ḇ': 'b', 'ᵬ': 'b', 'ᶀ': 'b', 'ƀ': 'b',\n\t\t'ƃ': 'b', 'б': 'b',\n\n\t\t'Ć': 'C', 'Č': 'C', 'Ç': 'C', 'Ḉ': 'C', 'Ĉ': 'C', 'Ċ': 'C', 'Ƈ': 'C',\n\t\t'Ȼ': 'C', 'Ꜿ': 'C', 'ᴄ': 'C',\n\t\t'ć': 'c', 'č': 'c', 'ç': 'c', 'ḉ': 'c', 'ĉ': 'c', 'ɕ': 'c', 'ċ': 'c',\n\t\t'ƈ': 'c', 'ȼ': 'c', 'ↄ': 'c', 'ꜿ': 'c',\n\n\t\t'Ч': 'CH',\n\t\t'ч': 'ch',\n\n\t\t'Ď': 'D', 'Ḑ': 'D', 'Ḓ': 'D', 'Ḋ': 'D', 'Ḍ': 'D', 'Ɗ': 'D', 'Ḏ': 'D',\n\t\t'Dz': 'D', 'Dž': 'D', 'Đ': 'D', 'Ƌ': 'D', 'Ꝺ': 'D', 'ᴅ': 'D', 'Д': 'D',\n\t\t'ď': 'd', 'ḑ': 'd', 'ḓ': 'd', 'ȡ': 'd', 'ḋ': 'd', 'ḍ': 'd', 'ɗ': 'd',\n\t\t'ᶑ': 'd', 'ḏ': 'd', 'ᵭ': 'd', 'ᶁ': 'd', 'đ': 'd', 'ɖ': 'd', 'ƌ': 'd',\n\t\t'ꝺ': 'd', 'д': 'd',\n\n\t\t'DZ': 'DZ', 'DŽ': 'DZ',\n\t\t'dz': 'dz', 'dž': 'dz',\n\n\t\t'É': 'E', 'Ĕ': 'E', 'Ě': 'E', 'Ȩ': 'E', 'Ḝ': 'E', 'Ê': 'E', 'Ế': 'E',\n\t\t'Ệ': 'E', 'Ề': 'E', 'Ể': 'E', 'Ễ': 'E', 'Ḙ': 'E', 'Ë': 'E', 'Ė': 'E',\n\t\t'Ẹ': 'E', 'Ȅ': 'E', 'È': 'E', 'Ẻ': 'E', 'Ȇ': 'E', 'Ē': 'E', 'Ḗ': 'E',\n\t\t'Ḕ': 'E', 'Ę': 'E', 'Ɇ': 'E', 'Ẽ': 'E', 'Ḛ': 'E', 'Ɛ': 'E', 'Ǝ': 'E',\n\t\t'ᴇ': 'E', 'ⱻ': 'E', 'Е': 'E', 'Э': 'E',\n\t\t'é': 'e', 'ĕ': 'e', 'ě': 'e', 'ȩ': 'e', 'ḝ': 'e', 'ê': 'e', 'ế': 'e',\n\t\t'ệ': 'e', 'ề': 'e', 'ể': 'e', 'ễ': 'e', 'ḙ': 'e', 'ë': 'e', 'ė': 'e',\n\t\t'ẹ': 'e', 'ȅ': 'e', 'è': 'e', 'ẻ': 'e', 'ȇ': 'e', 'ē': 'e', 'ḗ': 'e',\n\t\t'ḕ': 'e', 'ⱸ': 'e', 'ę': 'e', 'ᶒ': 'e', 'ɇ': 'e', 'ẽ': 'e', 'ḛ': 'e',\n\t\t'ɛ': 'e', 'ᶓ': 'e', 'ɘ': 'e', 'ǝ': 'e', 'ₑ': 'e', 'е': 'e', 'э': 'e',\n\n\t\t'Ꝫ': 'ET',\n\t\t'ꝫ': 'et',\n\n\t\t'Ḟ': 'F', 'Ƒ': 'F', 'Ꝼ': 'F', 'ꜰ': 'F', 'Ф': 'F',\n\t\t'ḟ': 'f', 'ƒ': 'f', 'ᵮ': 'f', 'ᶂ': 'f', 'ꝼ': 'f', 'ф': 'f',\n\n\t\t'ff': 'ff', 'ffi': 'ffi', 'ffl': 'ffl', 'fi': 'fi', 'fl': 'fl',\n\n\t\t'Ǵ': 'G', 'Ğ': 'G', 'Ǧ': 'G', 'Ģ': 'G', 'Ĝ': 'G', 'Ġ': 'G', 'Ɠ': 'G',\n\t\t'Ḡ': 'G', 'Ǥ': 'G', 'Ᵹ': 'G', 'ɢ': 'G', 'ʛ': 'G', 'Г': 'G',\n\t\t'ǵ': 'g', 'ğ': 'g', 'ǧ': 'g', 'ģ': 'g', 'ĝ': 'g', 'ġ': 'g', 'ɠ': 'g',\n\t\t'ḡ': 'g', 'ᶃ': 'g', 'ǥ': 'g', 'ᵹ': 'g', 'ɡ': 'g', 'ᵷ': 'g', 'г': 'g',\n\n\t\t'Ḫ': 'H', 'Ȟ': 'H', 'Ḩ': 'H', 'Ĥ': 'H', 'Ⱨ': 'H', 'Ḧ': 'H', 'Ḣ': 'H',\n\t\t'Ḥ': 'H', 'Ħ': 'H', 'ʜ': 'H', 'Х': 'H',\n\t\t'ḫ': 'h', 'ȟ': 'h', 'ḩ': 'h', 'ĥ': 'h', 'ⱨ': 'h', 'ḧ': 'h', 'ḣ': 'h',\n\t\t'ḥ': 'h', 'ɦ': 'h', 'ẖ': 'h', 'ħ': 'h', 'ɥ': 'h', 'ʮ': 'h', 'ʯ': 'h',\n\t\t'х': 'h',\n\n\t\t'ƕ': 'hv',\n\n\t\t'Í': 'I', 'Ĭ': 'I', 'Ǐ': 'I', 'Î': 'I', 'Ï': 'I', 'Ḯ': 'I', 'İ': 'I',\n\t\t'Ị': 'I', 'Ȉ': 'I', 'Ì': 'I', 'Ỉ': 'I', 'Ȋ': 'I', 'Ī': 'I', 'Į': 'I',\n\t\t'Ɨ': 'I', 'Ĩ': 'I', 'Ḭ': 'I', 'ɪ': 'I', 'Й': 'I', 'Ы': 'I', 'И': 'I',\n\t\t'ı': 'i', 'í': 'i', 'ĭ': 'i', 'ǐ': 'i', 'î': 'i', 'ï': 'i', 'ḯ': 'i',\n\t\t'ị': 'i', 'ȉ': 'i', 'ì': 'i', 'ỉ': 'i', 'ȋ': 'i', 'ī': 'i', 'į': 'i',\n\t\t'ᶖ': 'i', 'ɨ': 'i', 'ĩ': 'i', 'ḭ': 'i', 'ᴉ': 'i', 'ᵢ': 'i', 'й': 'i',\n\t\t'ы': 'i', 'и': 'i',\n\n\t\t'IJ': 'IJ', 'Ꝭ': 'IS',\n\t\t'ij': 'ij', 'ꝭ': 'is',\n\n\t\t'Ĵ': 'J', 'Ɉ': 'J', 'ᴊ': 'J',\n\t\t'ȷ': 'j', 'ɟ': 'j', 'ʄ': 'j', 'ǰ': 'j', 'ĵ': 'j', 'ʝ': 'j', 'ɉ': 'j',\n\t\t'ⱼ': 'j',\n\n\t\t'Ḱ': 'K', 'Ǩ': 'K', 'Ķ': 'K', 'Ⱪ': 'K', 'Ꝃ': 'K', 'Ḳ': 'K', 'Ƙ': 'K',\n\t\t'Ḵ': 'K', 'Ꝁ': 'K', 'Ꝅ': 'K', 'ᴋ': 'K', 'К': 'K',\n\t\t'ḱ': 'k', 'ǩ': 'k', 'ķ': 'k', 'ⱪ': 'k', 'ꝃ': 'k', 'ḳ': 'k', 'ƙ': 'k',\n\t\t'ḵ': 'k', 'ᶄ': 'k', 'ꝁ': 'k', 'ꝅ': 'k', 'ʞ': 'k', 'к': 'k',\n\n\t\t'Ĺ': 'L', 'Ƚ': 'L', 'Ľ': 'L', 'Ļ': 'L', 'Ḽ': 'L', 'Ḷ': 'L', 'Ḹ': 'L',\n\t\t'Ⱡ': 'L', 'Ꝉ': 'L', 'Ḻ': 'L', 'Ŀ': 'L', 'Ɫ': 'L', 'Lj': 'L', 'Ł': 'L',\n\t\t'Ꞁ': 'L', 'ʟ': 'L', 'ᴌ': 'L', 'Л': 'L',\n\t\t'ĺ': 'l', 'ƚ': 'l', 'ɬ': 'l', 'ľ': 'l', 'ļ': 'l', 'ḽ': 'l', 'ȴ': 'l',\n\t\t'ḷ': 'l', 'ḹ': 'l', 'ⱡ': 'l', 'ꝉ': 'l', 'ḻ': 'l', 'ŀ': 'l', 'ɫ': 'l',\n\t\t'ᶅ': 'l', 'ɭ': 'l', 'ł': 'l', 'ꞁ': 'l', 'л': 'l',\n\n\t\t'LJ': 'LJ',\n\t\t'lj': 'lj',\n\n\t\t'Ḿ': 'M', 'Ṁ': 'M', 'Ṃ': 'M', 'Ɱ': 'M', 'Ɯ': 'M', 'ᴍ': 'M', 'М': 'M',\n\t\t'ḿ': 'm', 'ṁ': 'm', 'ṃ': 'm', 'ɱ': 'm', 'ᵯ': 'm', 'ᶆ': 'm', 'ɯ': 'm',\n\t\t'ɰ': 'm', 'м': 'm',\n\n\t\t'Ń': 'N', 'Ň': 'N', 'Ņ': 'N', 'Ṋ': 'N', 'Ṅ': 'N', 'Ṇ': 'N', 'Ǹ': 'N',\n\t\t'Ɲ': 'N', 'Ṉ': 'N', 'Ƞ': 'N', 'Nj': 'N', 'Ñ': 'N', 'ɴ': 'N', 'ᴎ': 'N',\n\t\t'Н': 'N',\n\t\t'ń': 'n', 'ň': 'n', 'ņ': 'n', 'ṋ': 'n', 'ȵ': 'n', 'ṅ': 'n', 'ṇ': 'n',\n\t\t'ǹ': 'n', 'ɲ': 'n', 'ṉ': 'n', 'ƞ': 'n', 'ᵰ': 'n', 'ᶇ': 'n', 'ɳ': 'n',\n\t\t'ñ': 'n', 'н': 'n',\n\n\t\t'NJ': 'NJ',\n\t\t'nj': 'nj',\n\n\t\t'Ó': 'O', 'Ŏ': 'O', 'Ǒ': 'O', 'Ô': 'O', 'Ố': 'O', 'Ộ': 'O', 'Ồ': 'O',\n\t\t'Ổ': 'O', 'Ỗ': 'O', 'Ö': 'O', 'Ȫ': 'O', 'Ȯ': 'O', 'Ȱ': 'O', 'Ọ': 'O',\n\t\t'Ő': 'O', 'Ȍ': 'O', 'Ò': 'O', 'Ỏ': 'O', 'Ơ': 'O', 'Ớ': 'O', 'Ợ': 'O',\n\t\t'Ờ': 'O', 'Ở': 'O', 'Ỡ': 'O', 'Ȏ': 'O', 'Ꝋ': 'O', 'Ꝍ': 'O', 'Ō': 'O',\n\t\t'Ṓ': 'O', 'Ṑ': 'O', 'Ɵ': 'O', 'Ǫ': 'O', 'Ǭ': 'O', 'Ø': 'O', 'Ǿ': 'O',\n\t\t'Õ': 'O', 'Ṍ': 'O', 'Ṏ': 'O', 'Ȭ': 'O', 'Ɔ': 'O', 'ᴏ': 'O', 'ᴐ': 'O',\n\t\t'О': 'O',\n\t\t'ɵ': 'o', 'ó': 'o', 'ŏ': 'o', 'ǒ': 'o', 'ô': 'o', 'ố': 'o', 'ộ': 'o',\n\t\t'ồ': 'o', 'ổ': 'o', 'ỗ': 'o', 'ö': 'o', 'ȫ': 'o', 'ȯ': 'o', 'ȱ': 'o',\n\t\t'ọ': 'o', 'ő': 'o', 'ȍ': 'o', 'ò': 'o', 'ỏ': 'o', 'ơ': 'o', 'ớ': 'o',\n\t\t'ợ': 'o', 'ờ': 'o', 'ở': 'o', 'ỡ': 'o', 'ȏ': 'o', 'ꝋ': 'o', 'ꝍ': 'o',\n\t\t'ⱺ': 'o', 'ō': 'o', 'ṓ': 'o', 'ṑ': 'o', 'ǫ': 'o', 'ǭ': 'o', 'ø': 'o',\n\t\t'ǿ': 'o', 'õ': 'o', 'ṍ': 'o', 'ṏ': 'o', 'ȭ': 'o', 'ɔ': 'o', 'ᶗ': 'o',\n\t\t'ᴑ': 'o', 'ᴓ': 'o', 'ₒ': 'o', 'о': 'o',\n\n\t\t'Œ': 'OE', 'ɶ': 'OE', 'Ƣ': 'OI', 'Ꝏ': 'OO', 'Ȣ': 'OU', 'ᴕ': 'OU',\n\t\t'ᴔ': 'oe', 'œ': 'oe', 'ƣ': 'oi', 'ꝏ': 'oo', 'ȣ': 'ou',\n\n\t\t'Ṕ': 'P', 'Ṗ': 'P', 'Ꝓ': 'P', 'Ƥ': 'P', 'Ꝕ': 'P', 'Ᵽ': 'P', 'Ꝑ': 'P',\n\t\t'ᴘ': 'P', 'П': 'P',\n\t\t'ṕ': 'p', 'ṗ': 'p', 'ꝓ': 'p', 'ƥ': 'p', 'ᵱ': 'p', 'ᶈ': 'p', 'ꝕ': 'p',\n\t\t'ᵽ': 'p', 'ꝑ': 'p', 'п': 'p',\n\n\t\t'Ꝙ': 'Q', 'Ꝗ': 'Q',\n\t\t'ꝙ': 'q', 'ʠ': 'q', 'ɋ': 'q', 'ꝗ': 'q',\n\n\t\t'Ꞃ': 'R', 'Ŕ': 'R', 'Ř': 'R', 'Ŗ': 'R', 'Ṙ': 'R', 'Ṛ': 'R', 'Ṝ': 'R',\n\t\t'Ȑ': 'R', 'Ȓ': 'R', 'Ṟ': 'R', 'Ɍ': 'R', 'Ɽ': 'R', 'ʁ': 'R', 'ʀ': 'R',\n\t\t'ᴙ': 'R', 'ᴚ': 'R', 'Р': 'R',\n\t\t'ꞃ': 'r', 'ŕ': 'r', 'ř': 'r', 'ŗ': 'r', 'ṙ': 'r', 'ṛ': 'r', 'ṝ': 'r',\n\t\t'ȑ': 'r', 'ɾ': 'r', 'ᵳ': 'r', 'ȓ': 'r', 'ṟ': 'r', 'ɼ': 'r', 'ᵲ': 'r',\n\t\t'ᶉ': 'r', 'ɍ': 'r', 'ɽ': 'r', 'ɿ': 'r', 'ɹ': 'r', 'ɻ': 'r', 'ɺ': 'r',\n\t\t'ⱹ': 'r', 'ᵣ': 'r', 'р': 'r',\n\n\t\t'Ꞅ': 'S', 'Ś': 'S', 'Ṥ': 'S', 'Š': 'S', 'Ṧ': 'S', 'Ş': 'S', 'Ŝ': 'S',\n\t\t'Ș': 'S', 'Ṡ': 'S', 'Ṣ': 'S', 'Ṩ': 'S', 'ꜱ': 'S', 'С': 'S',\n\t\t'ꞅ': 's', 'ſ': 's', 'ẜ': 's', 'ẛ': 's', 'ẝ': 's', 'ś': 's', 'ṥ': 's',\n\t\t'š': 's', 'ṧ': 's', 'ş': 's', 'ŝ': 's', 'ș': 's', 'ṡ': 's', 'ṣ': 's',\n\t\t'ṩ': 's', 'ʂ': 's', 'ᵴ': 's', 'ᶊ': 's', 'ȿ': 's', 'с': 's',\n\n\t\t'Щ': 'SCH', 'Ш': 'SH',\n\t\t'щ': 'sch', 'ш': 'sh', 'ß': 'ss', 'st': 'st',\n\n\t\t'Ꞇ': 'T', 'Ť': 'T', 'Ţ': 'T', 'Ṱ': 'T', 'Ț': 'T', 'Ⱦ': 'T', 'Ṫ': 'T',\n\t\t'Ṭ': 'T', 'Ƭ': 'T', 'Ṯ': 'T', 'Ʈ': 'T', 'Ŧ': 'T', 'ᴛ': 'T', 'Т': 'T',\n\t\t'ꞇ': 't', 'ť': 't', 'ţ': 't', 'ṱ': 't', 'ț': 't', 'ȶ': 't', 'ẗ': 't',\n\t\t'ⱦ': 't', 'ṫ': 't', 'ṭ': 't', 'ƭ': 't', 'ṯ': 't', 'ᵵ': 't', 'ƫ': 't',\n\t\t'ʈ': 't', 'ŧ': 't', 'ʇ': 't', 'т': 't',\n\n\t\t'Ц': 'TS', 'Ꜩ': 'TZ',\n\t\t'ᵺ': 'th', 'ц': 'ts', 'ꜩ': 'tz',\n\n\t\t'Ú': 'U', 'Ŭ': 'U', 'Ǔ': 'U', 'Û': 'U', 'Ṷ': 'U', 'Ü': 'U', 'Ǘ': 'U',\n\t\t'Ǚ': 'U', 'Ǜ': 'U', 'Ǖ': 'U', 'Ṳ': 'U', 'Ụ': 'U', 'Ű': 'U', 'Ȕ': 'U',\n\t\t'Ù': 'U', 'Ủ': 'U', 'Ư': 'U', 'Ứ': 'U', 'Ự': 'U', 'Ừ': 'U', 'Ử': 'U',\n\t\t'Ữ': 'U', 'Ȗ': 'U', 'Ū': 'U', 'Ṻ': 'U', 'Ų': 'U', 'Ů': 'U', 'Ũ': 'U',\n\t\t'Ṹ': 'U', 'Ṵ': 'U', 'ᴜ': 'U', 'У': 'U',\n\t\t'ᴝ': 'u', 'ú': 'u', 'ŭ': 'u', 'ǔ': 'u', 'û': 'u', 'ṷ': 'u', 'ü': 'u',\n\t\t'ǘ': 'u', 'ǚ': 'u', 'ǜ': 'u', 'ǖ': 'u', 'ṳ': 'u', 'ụ': 'u', 'ű': 'u',\n\t\t'ȕ': 'u', 'ù': 'u', 'ủ': 'u', 'ư': 'u', 'ứ': 'u', 'ự': 'u', 'ừ': 'u',\n\t\t'ử': 'u', 'ữ': 'u', 'ȗ': 'u', 'ū': 'u', 'ṻ': 'u', 'ų': 'u', 'ᶙ': 'u',\n\t\t'ů': 'u', 'ũ': 'u', 'ṹ': 'u', 'ṵ': 'u', 'ᵤ': 'u', 'у': 'u',\n\n\t\t'ᵫ': 'ue', 'ꝸ': 'um',\n\n\t\t'Ʌ': 'V', 'Ꝟ': 'V', 'Ṿ': 'V', 'Ʋ': 'V', 'Ṽ': 'V', 'ᴠ': 'V', 'В': 'V',\n\t\t'ʌ': 'v', 'ⱴ': 'v', 'ꝟ': 'v', 'ṿ': 'v', 'ʋ': 'v', 'ᶌ': 'v', 'ⱱ': 'v',\n\t\t'ṽ': 'v', 'ᵥ': 'v', 'в': 'v',\n\n\t\t'Ꝡ': 'VY',\n\t\t'ꝡ': 'vy',\n\n\t\t'Ẃ': 'W', 'Ŵ': 'W', 'Ẅ': 'W', 'Ẇ': 'W', 'Ẉ': 'W', 'Ẁ': 'W', 'Ⱳ': 'W',\n\t\t'ᴡ': 'W',\n\t\t'ʍ': 'w', 'ẃ': 'w', 'ŵ': 'w', 'ẅ': 'w', 'ẇ': 'w', 'ẉ': 'w', 'ẁ': 'w',\n\t\t'ⱳ': 'w', 'ẘ': 'w',\n\n\t\t'Ẍ': 'X', 'Ẋ': 'X',\n\t\t'ẍ': 'x', 'ẋ': 'x', 'ᶍ': 'x', 'ₓ': 'x',\n\n\t\t'Ý': 'Y', 'Ŷ': 'Y', 'Ÿ': 'Y', 'Ẏ': 'Y', 'Ỵ': 'Y', 'Ỳ': 'Y', 'Ƴ': 'Y',\n\t\t'Ỷ': 'Y', 'Ỿ': 'Y', 'Ȳ': 'Y', 'Ɏ': 'Y', 'Ỹ': 'Y', 'ʏ': 'Y',\n\t\t'ʎ': 'y', 'ý': 'y', 'ŷ': 'y', 'ÿ': 'y', 'ẏ': 'y', 'ỵ': 'y', 'ỳ': 'y',\n\t\t'ƴ': 'y', 'ỷ': 'y', 'ỿ': 'y', 'ȳ': 'y', 'ẙ': 'y', 'ɏ': 'y', 'ỹ': 'y',\n\n\t\t'Ё': 'YO', 'Ю': 'YU', 'Я': 'Ya',\n\t\t'я': 'ya', 'ё': 'yo', 'ю': 'yu',\n\n\t\t'Ź': 'Z', 'Ž': 'Z', 'Ẑ': 'Z', 'Ⱬ': 'Z', 'Ż': 'Z', 'Ẓ': 'Z', 'Ȥ': 'Z',\n\t\t'Ẕ': 'Z', 'Ƶ': 'Z', 'ᴢ': 'Z', 'З': 'Z',\n\t\t'ź': 'z', 'ž': 'z', 'ẑ': 'z', 'ʑ': 'z', 'ⱬ': 'z', 'ż': 'z', 'ẓ': 'z',\n\t\t'ȥ': 'z', 'ẕ': 'z', 'ᵶ': 'z', 'ᶎ': 'z', 'ʐ': 'z', 'ƶ': 'z', 'ɀ': 'z',\n\t\t'з': 'z',\n\n\t\t'Ж': 'ZH',\n\t\t'ж': 'zh'\n\t})\n\ndef random(length = 8, sets='_aZ', duplicates=True):\n\t\"\"\"Random\n\n\tGenerates a random string. By default this function will generate an 8\n\tcharacter string using lowercase letters with possible repeating characters\n\n\tArguments:\n\t\tlength (int): Requested length of the string\n\t\tsets (str|str[]): A list of names from the standard sets, a string\n\t\t\tstarting with an underscore representing one named set, or any other\n\t\t\tstring to be used as an array of characters to chose from. If you\n\t\t\twant certain characters to have a greater chance of appearing, use\n\t\t\tthem more times, e.g. twice the 'A's, \"AABC\", or three times the\n\t\t\t'B's, \"ABBBC\". Make sure not to turn off duplicates for this to be\n\t\t\teffective\n\t\tduplicates (bool): Defaults to True, allowing characters to be used\n\t\t\tmore than once\n\n\tSets:\n\t\t0x:\t\t0123456789abcdef\n\t\t0:\t\t01234567\n\t\t10:\t\t0123456789\n\t\taz:\t\tabcdefghijklmnopqrstuvwxyz\n\t\taz*:\tabcdefghijkmnopqrstuvwxyz\n\t\tAZ:\t\tABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t\tAZ*:\tABCDEFGHJKLMNPQRSTUVWXYZ\n\t\taZ:\t\tabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t\taZ*:\tabcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\n\t\t!:\t\t!@#$%^&*-_+.?\n\t\t!*:\t\t!@$%^*-_.\n\n\tExamples:\n\t\t> random(8, '_0x')\n\t\t\"baadbeef\"\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\n\t# If the sets are a list\n\tif isinstance(sets, list):\n\n\t\t# If there is no count\n\t\tif not sets:\n\t\t\traise ValueError('sets must contain at least one set name')\n\n\t\t# Init the string to be used as the allowed characters\n\t\tsChars = ''\n\n\t\t# Go through the list\n\t\tfor s in sets:\n\n\t\t\t# If the set doesn't exist\n\t\t\tif s not in _mdRandomSets:\n\t\t\t\traise ValueError('%s is not a valid set' % s)\n\n\t\t\t# Else, add it to the allowed characters\n\t\t\tsChars += _mdRandomSets[s]\n\n\t# Else if we have a string\n\telif isinstance(sets, str):\n\n\t\t# If it starts with an underscore\n\t\tif sets[0] == '_':\n\n\t\t\t# If the set doesn't exist\n\t\t\tif sets[1:] not in _mdRandomSets:\n\t\t\t\traise ValueError('%s is not a valid set for %s' % (sets[1:], sys._getframe().f_code.co_name))\n\n\t\t\t# Else, set it to the allowed characters\n\t\t\tsChars = _mdRandomSets[sets[1:]]\n\n\t\t# Else, use the string as is\n\t\telse:\n\t\t\tsChars = sets\n\n\telse:\n\t\traise ValueError('%s is not a valid value for sets argument of %s' % (str(sets), sys._getframe().f_code.co_name))\n\n\t# Init the return variable\n\tsText = '';\n\n\t# Count the number of characters we can use\n\tiCount = len(sChars)\n\n\t# Create a [length] of random character\n\ti = 0\n\twhile i < length:\n\t\tsFound = sChars[randint(0, iCount - 1)]\n\t\tbDup = sText.find(sFound)\n\n\t\tif duplicates or bDup == -1:\n\t\t\tsText += sFound\n\t\t\ti += 1\n\n\t# Return the generated string\n\treturn sText\n\ndef strtr(text, table):\n\t\"\"\"String Translate\n\n\tPort of PHP strtr (string translate)\n\n\tArgs:\n\t\ttext (str): The string to translate\n\t\ttable (dict): The translation table\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\ttext = str(text)\n\tbuff = []\n\ti = 0\n\tn = len(text)\n\twhile i < n:\n\t\tfor s, r in table.items():\n\t\t\tif text[i:len(s)+i] == s:\n\t\t\t\tbuff.append(r)\n\t\t\t\ti += len(s)\n\t\t\t\tbreak\n\t\telse:\n\t\t\tbuff.append(text[i])\n\t\t\ti += 1\n\n\treturn ''.join(buff)\n\ndef to_bool(t):\n\t\"\"\"To Bool\n\n\tConverts a string to a boolean value\n\n\tArguments:\n\t\tt (str): The text to attempt to convert\n\n\tRaises\n\t\tValueError\n\n\tReturns:\n\t\tbool\n\t\"\"\"\n\n\t# If we didn't get a string\n\tif not isinstance(t, str):\n\t\treturn ValueError('t is not a string: %s', str(type(t)))\n\n\t# First, convert the string to lowercase\n\tt = t.lower()\n\n\t# If it's any true type value\n\tif t in ['1', 'on', 't', 'true', 'y', 'yes']:\n\t\treturn True\n\n\t# Else, if it's any false type value\n\telif t in ['0', 'f', 'false', 'n', 'no', 'off']:\n\t\treturn False\n\n\t# Raise an exception\n\traise ValueError('t is not a boolean representation: \"%s\"' % t)\n\ndef uuid_add_dashes(uuid):\n\t\"\"\"UUID Add Dashes\n\n\tAdds dashes back to a UUID that had them removed\n\n\tArguments:\n\t\tuuid (str): The UUID to transform\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\treturn '%s-%s-%s-%s-%s' % (\n\t\tuuid[0:8],\n\t\tuuid[8:12],\n\t\tuuid[12:16],\n\t\tuuid[16:20],\n\t\tuuid[20:32]\n\t)\n\ndef uuid_strip_dashes(uuid):\n\t\"\"\"UUID Strip Dashes\n\n\tRemoves the dashes from a UUID\n\n\tArguments:\n\t\tuuid (str): The UUID to transform\n\n\tReturns:\n\t\tstr\n\t\"\"\"\n\treturn '%s%s%s%s%s' % (\n\t\tuuid[0:8],\n\t\tuuid[9:13],\n\t\tuuid[14:18],\n\t\tuuid[19:23],\n\t\tuuid[24:36]\n\t)\n","sub_path":"RestOC/StrHelper.py","file_name":"StrHelper.py","file_ext":"py","file_size_in_byte":18147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"368971274","text":"from django.db import models\nfrom .store import Store\nfrom .user import User\n\n\n# Create your models here.\nclass Product(models.Model):\n class Meta:\n db_table = '\"mk_product\"'\n\n # pk\n seq = models.AutoField(primary_key=True)\n # product title\n title = models.CharField(max_length=250)\n # product number\n count = models.IntegerField()\n\n price = models.IntegerField()\n\n info = models.TextField()\n # sold yn\n is_sold = models.BooleanField()\n store = models.ForeignKey(Store, on_delete=models.CASCADE)\n create_at = models.DateTimeField(auto_now_add=True)\n\n\nclass Order(models.Model):\n class Meta:\n db_table = '\"mk_order\"'\n\n seq = models.AutoField(primary_key=True)\n user = models.ForeignKey(User, on_delete=models.DO_NOTHING)\n product = models.ForeignKey(Product, on_delete=models.DO_NOTHING)\n cnt = models.IntegerField()\n create_at = models.DateTimeField(auto_now_add=True)\n\n\n\n","sub_path":"venv/bin/App/Apps/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"21420268","text":"import cv2\nimport os\nimport glob\nimport numpy\n\nfor file in glob.glob('data/dataset/test_original/*.png'):\n#for file in glob.glob('data/dataset/train_original/*.png'):\n img = cv2.imread(file)\n height = img.shape[0]\n width = img.shape[1]\n\n if height > 416 and width > 416:\n\n for y in range(0, img.shape[0], 416):\n for x in range(0, img.shape[1], 416):\n #croppedImage = img[startRow:endRow, startCol:endCol]\n crop_img = img[y:y + 416, x:x + 416]\n name, extension = os.path.splitext(os.path.basename(file))\n new_extension = '.jpg'\n\n name1 = name + \"_\" + str(y)\n name2 = name1 + \"_\" + str(x)\n print(str(y))\n print(str(x))\n filename = name2 + new_extension\n print(filename)\n\n if os.path.isfile(filename):\n print(\"File exist\")\n break\n else:\n print(\"File not exist\")\n output_directory = 'data/dataset/train_segmented'\n if crop_img.shape[0] < 416 or crop_img.shape[1] < 416:\n break\n else:\n cv2.imwrite(os.path.join(output_directory, filename), crop_img)\n print('Successfully saved')\n\n else:\n print(\"No 416 image\") \n print(\"Keep calm! Image not deleted in home\") \n\n\n\n","sub_path":"image_segmentation.py","file_name":"image_segmentation.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"450313793","text":"import os\nimport itertools\n\nfrom enum import Enum, auto\n\nfrom .option_file_data import (\n OF_BYTE_LENGTH,\n OF_BLOCK,\n OF_BLOCK_SIZE,\n OF_KEY,\n OF_KEY_PC,\n)\n\nfrom .club import Club\nfrom .player import Player\n\nfrom .utils.common_functions import bytes_to_int, zero_fill_right_shift\n\n\nclass OptionFile:\n of_byte_length = OF_BYTE_LENGTH\n of_block = OF_BLOCK\n of_block_size = OF_BLOCK_SIZE\n of_key = OF_KEY\n of_key_pc = OF_KEY_PC\n\n def __init__(self, file_location):\n self.file_location = file_location\n\n self.data = bytearray()\n self.file_name = \"\"\n self.game_type = None\n\n self.read_option_file()\n\n self.set_clubs()\n self.set_players()\n\n def get_game_type(self, file_name):\n \"\"\"\n Return game type from supplied filename string.\n \"\"\"\n game_type_map = {\n \"KONAMI-WIN32PES5OPT\": GameType.pc_pes,\n \"KONAMI-WIN32WE9KOPT\": GameType.pc_pwe,\n }\n return game_type_map.get(file_name)\n\n def read_option_file(self):\n \"\"\"\n Decrypt supplied file and set OF data.\n \"\"\"\n of_file = open(self.file_location, \"rb\")\n file_name = os.path.basename(of_file.name)\n self.file_name = file_name\n self.game_type = self.get_game_type(file_name)\n\n file_contents = of_file.read()\n of_file.close()\n\n self.data = bytearray(file_contents)\n self.convert_data()\n self.decrypt()\n\n return True\n\n def save_option_file(self, file_location=None):\n \"\"\"\n Save OF data to supplied file.\n \"\"\"\n file_location = self.file_location = file_location or self.file_location\n\n self.data[45] = 1\n self.data[46] = 1\n self.data[5958] = 1\n self.data[5959] = 1\n\n self.encrypt()\n self.checksums()\n self.convert_data()\n\n of_file = open(file_location, \"wb\")\n of_file.write(self.data)\n of_file.close()\n\n self.convert_data()\n self.decrypt()\n\n return True\n\n def convert_data(self):\n \"\"\"\n Converts OF data based on PC key.\n \"\"\"\n key = 0\n\n for i in range(self.of_byte_length):\n self.data[i] = self.data[i] ^ self.of_key_pc[key]\n\n if key < 255:\n key += 1\n else:\n key = 0\n\n def decrypt(self):\n \"\"\"\n Decrypt OF.\n \"\"\"\n for i in range(1, 10):\n k = 0\n a = self.of_block[i]\n while True:\n if a + 4 > self.of_block[i] + self.of_block_size[i]:\n break\n\n c = bytes_to_int(self.data, a)\n p = ((c - self.of_key[k]) + 0x6C371625) ^ 0x6C371625\n\n self.data[a] = p & 0x000000FF\n self.data[a + 1] = zero_fill_right_shift(p, 8) & 0x000000FF\n self.data[a + 2] = zero_fill_right_shift(p, 16) & 0x000000FF\n self.data[a + 3] = zero_fill_right_shift(p, 24) & 0x000000FF\n\n k += 1\n if k == 367:\n k = 0\n\n a += 4\n\n def encrypt(self):\n \"\"\"\n Encrypt OF.\n \"\"\"\n for i in range(1, 10):\n k = 0\n a = self.of_block[i]\n while True:\n if a + 4 > self.of_block[i] + self.of_block_size[i]:\n break\n\n p = bytes_to_int(self.data, a)\n c = self.of_key[k] + ((p ^ 0x6C371625) - 0x6C371625)\n\n self.data[a] = c & 0x000000FF\n self.data[a + 1] = zero_fill_right_shift(c, 8) & 0x000000FF\n self.data[a + 2] = zero_fill_right_shift(c, 16) & 0x000000FF\n self.data[a + 3] = zero_fill_right_shift(c, 24) & 0x000000FF\n\n k += 1\n if k == 367:\n k = 0\n\n a += 4\n\n def checksums(self):\n \"\"\"\n Set checksums.\n \"\"\"\n for i in range(0, 10):\n checksum = 0\n\n for a in range(\n self.of_block[i], self.of_block[i] + self.of_block_size[i], 4\n ):\n checksum += bytes_to_int(self.data, a)\n\n self.data[self.of_block[i] - 8] = checksum & 0x000000FF\n self.data[self.of_block[i] - 7] = (\n zero_fill_right_shift(checksum, 8) & 0x000000FF\n )\n self.data[self.of_block[i] - 6] = (\n zero_fill_right_shift(checksum, 16) & 0x000000FF\n )\n self.data[self.of_block[i] - 5] = (\n zero_fill_right_shift(checksum, 24) & 0x000000FF\n )\n\n def set_clubs(self):\n \"\"\"\n Load all clubs from OF data and add to clubs list.\n \"\"\"\n self.clubs = []\n for i in range(Club.total):\n club = Club(self, i)\n self.clubs.append(club)\n\n def set_players(self):\n \"\"\"\n Load all players from OF data and add to players list.\n \"\"\"\n self.players = []\n for i in itertools.chain(\n range(1, Player.total + 1),\n range(Player.first_edit, Player.last_edit),\n ):\n player = Player(self, i)\n self.players.append(player)\n\n\nclass GameType(Enum):\n pc_pes = auto()\n pc_pwe = auto()\n","sub_path":"editor/option_file.py","file_name":"option_file.py","file_ext":"py","file_size_in_byte":5315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565356126","text":"import numpy as np\nimport math\n\n\ndef normalize_feature(feature):\n if len(feature.shape) != 1:\n raise ValueError('not valid shape, feature: {}'.format(feature.shape))\n return feature / math.sqrt(np.sum(feature*feature))\n\n\ndef face_feature_match(probe_feature, gallery_feature, normalize=True):\n \"\"\"\n :param probe_feature: numpy.ndarray [512,]\n :param gallery_feature: numpy.ndarray [bbox index][512]\n :param normalize:\n :return:\n \"\"\"\n if probe_feature.shape[0] != gallery_feature.shape[1] or len(probe_feature.shape) != 1\\\n or len(gallery_feature.shape) != 2:\n raise ValueError('not valid shape, probe_feature: {} gallery_feature: {}'\n .format(probe_feature.shape, gallery_feature))\n if normalize:\n for i in range(gallery_feature.shape[0]):\n gallery_feature[i, :] = normalize_feature(gallery_feature[i])\n\n probe_feature = normalize_feature(probe_feature)\n probe_feature = np.reshape(probe_feature, (1, probe_feature.shape[0]))\n score_matrix = np.matmul(probe_feature, gallery_feature.transpose())\n index = np.argmax(score_matrix[0])\n score = score_matrix[0][index]\n return index, score\n","sub_path":"face/face_identification.py","file_name":"face_identification.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50413874","text":"from random import randrange, uniform\n\nclass Node():\n def __init__(self,data):\n self.data = data\n self.parent = None\n self.leftChild = None\n self.rightChild = None\n self.height = -1;\n\n def setLeftChild(self,leftChild):\n self.leftChild=leftChild\n\n def setRightChild(self,rightChild):\n self.rightChild=rightChild\n\n def setParent(self,parent):\n self.parent=parent\n\n def setData(self,data): # update data\n self.data=data\n\n def setHeight(self,height):\n self.height=height\n\n def getData(self):\n return self.data\n\n def getLeftChild(self):\n return self.leftChild\n\n def getRightChild(self):\n return self.rightChild\n\n def getParent(self):\n return self.parent\n\n\n\n\nclass BinarySearchTree():\n\n def __init__(self):\n self.root = None\n self.size = 0\n\n def getRoot(self):\n return self.root\n\n def insertNode(self, data):\n tempNode = self.root\n\n newNode = Node(data)\n if(tempNode == None):\n self.root = newNode\n\n else:\n while(True):\n if(data < tempNode.getData()):\n if(tempNode.getLeftChild() == None):\n tempNode.setLeftChild(newNode)\n tempNode.getLeftChild().setParent(tempNode)\n break\n else:\n tempNode = tempNode.getLeftChild()\n else:\n if (tempNode.getRightChild() == None):\n tempNode.setRightChild(newNode)\n tempNode.getRightChild().setParent(tempNode)\n\n break\n else:\n tempNode = tempNode.getRightChild()\n self.size+=1\n\n def findNode(self,data):\n tempNode = self.root\n iteration =0\n while(True):\n if(tempNode.getData()==data):\n\n return iteration\n elif(tempNode.getData()>data): tempNode=tempNode.getLeftChild()\n else: tempNode=tempNode.getRightChild()\n iteration+=1\n\n def printTreeInOrder(self, node):\n if(node == None): return\n self.printTreeInOrder(node.getLeftChild())\n print(node.getData(),end=' ')\n self.printTreeInOrder(node.getRightChild())\n\n\n def printTreePostOrder(self, node):\n if(node == None): return\n self.printTreeInOrder(node.getRightChild())\n print(node.getData(),end=' ')\n self.printTreeInOrder(node.getLeftChild())\n\n\n def printTreePreOrder(self, node):\n if(node == None): return\n print(node.getData(),end=' ')\n self.printTreePreOrder(node.getLeftChild())\n self.printTreePreOrder(node.getRightChild())\n\n def deleteNode(self,data):\n tempNode = self.findNode(data)\n # print(tempNode.getData())\n # print(tempNode.getParent().getData())\n # if(tempNode.getLeftChild()): print(tempNode.getLeftChild().getData())\n # if(tempNode.getRightChild()): print(tempNode.getRightChild().getData())\n if(tempNode.getLeftChild()==None and tempNode.getRightChild()==None):\n if(tempNode.getParent().getData()>tempNode.getData()):\n tempNode.getParent().setLeftChild(None)\n else:\n tempNode.getParent().setRightChild(None)\n\n elif(tempNode.getLeftChild() == None and tempNode.getRightChild() != None):\n child = tempNode.getRightChild()\n parent = tempNode.getParent()\n\n parent.setRightChild(child)\n\n elif (tempNode.getLeftChild() != None and tempNode.getRightChild() == None):\n child = tempNode.getLeftChild()\n parent = tempNode.getParent()\n\n parent.setLeftChild(child)\n else:\n child = tempNode.getRightChild()\n\n while(child.getLeftChild()!=None):\n child = child.getLeftChild()\n tempNode.setData(child.getData())\n child.getParent().setLeftChild(None)\n # tempNode.setData(child.getData())\n\n self.size-=1\n\n def getHeight(self,node):\n\n if(node == None): return -1\n\n # if(node and node.getLeftChild()): print('Calling node= ', node.getData(),\"left Child= \",node.getLeftChild().getData())\n leftHeight = self.getHeight(node.getLeftChild())\n\n # if(node and node.getRightChild()): print('Calling node = ', node.getData(),\"right Child= \",node.getRightChild().getData())\n RightHeight = self.getHeight(node.getRightChild())\n\n\n # print(maxH)\n return max(leftHeight,RightHeight)+1\n\n\n\n\n\nbinary = BinarySearchTree()\n\nbinary.insertNode(12)\nbinary.insertNode(20)\nbinary.insertNode(6)\nbinary.insertNode(4)\nbinary.insertNode(5)\nbinary.insertNode(25)\nbinary.insertNode(21)\nbinary.insertNode(29)\nbinary.insertNode(19)\nbinary.insertNode(27)\nbinary.insertNode(26)\nbinary.insertNode(28)\n\n\n\n\n\n# list = input().strip().split(' ')\n# l = input()\n# arr = input()\n# list=list(map(int,arr.split(' ')))\n# for i in range(len(list)):\n# binary.insertNode(list[i])\nbinary.printTreeInOrder(binary.getRoot())\nprint()\nprint(binary.findNode(4))\n# binary.printTreePostOrder(binary.getRoot())\n# binary.printTreePreOrder(binary.getRoot())","sub_path":"media/chinmoy/private-project/binarSearchTree.py","file_name":"binarSearchTree.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"420538753","text":"from turtle import *\nimport math\n\n# Name your Turtle.\nt = Turtle()\n\n# Set Up your screen and starting position.\nsetup(500,600)\nsides = input(\"enter a number\")\nangle = 360/sides\npencolor(\"red\")\npendown()\nfor i in range(sides):\n forward(100)\n left(angle)\npenup()\nexitonclick()\n","sub_path":"Unit1_Foundations/shapes2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"338300796","text":"#why we use dictionaries?\n# because of list limitation, list are not enough to represent real data\n\n#what are dictionaries?\n#unordered collection of data in key:value pair\n\n#how to create dictionaries?\nuser = {'name':'shlok','age': 2}\nprint(user)\n\n#second method \nuser1 = dict(name = 'shlok', age = 3)\nprint(user1)\n\n#how add data in empty dictionaries\nuser_info2 = {}\nuser_info2['name'] = 'Shlok'\nprint(user_info2)\n\n\n# looping and in keyword\n#for i in user_info:\n# print(i)\n\n#only values\n#for i in user_info.values():\n# print(i)\n\n\n# how to add,delete data in dictionaries\n\nuser_info = {\n 'name':'Shlok',\n 'age': 2,\n 'fav_movie':['kk','bb','aa'],\n 'fav_tunes':['tt','yy'],\n}\n\n#how to add data\nuser_info['fav_song'] = ['song1','song2']\nprint(user_info)\n#pop method\n#user_info.pop('fav_tunes')\npopped_item = user_info.pop('fav_tunes')\nprint(user_info)\n\n#popitem method : when you want to remove random item\n","sub_path":"dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"30047998","text":"from flask import Flask\nfrom itertools import permutations\nimport os.path\nimport json\nimport pdb\nimport time\n\n \nwords = []\nwith open('/usr/share/dict/words') as f:\n for line in f.readlines():\n words.append(line.strip('\\n'))\n\nword_dict = {}\n\nfor word in words:\n if len(word) > 1 or word in 'ai':\n sig = ''.join(sorted(word))\n word_dict.setdefault(sig.decode('ascii').encode('utf-8'), []).append(word)\n\n#We now have a dictionary that has a sorted 'signature' based list of all words that are in the words dict\n\napp = Flask(__name__)\n\n#Fetch all substrings of a given string\n#this is used to grab all the permutations of a string passed into the wordfinder\n#route\n\n@timeit\ndef get_all_substrings(string):\n length = len(string)\n for i in xrange(length):\n for j in xrange(i + 1, length + 1):\n yield(string[i:j])\n\n@app.route('/ping')\ndef pong():\n return ('', 200)\n\n@app.route('/wordfinder/<string:letters>')\ndef findwords(letters):\n #Get all the substrings of the letters passed in\n matches = []\n for k in word_dict.keys():\n matches.extend([x for x in word_dict[k] if k in letters]) \n return json.dumps(matches)\n\nif __name__ == \"__main__\":\n app.run(port=8080, debug=True)\n","sub_path":"attempts/attempt2.py","file_name":"attempt2.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"108233687","text":"import csv\n\nwith open('content_db.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter = ',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n print(f'Column names are {\",\".join(row)}')\n line_count += 1\n else:\n print(f'{row[0]} {row[1]} lives in {row[3]} {row[4]}, mobile number\\\n{row[5]} email {row[6]} birthday {row[7]}')\n line_count += 1\n print(f'Processed {line_count} lines.')\n\n#unit 3 lesson 27 Udemy on basics input/output (I/O)\n","sub_path":"Code using csv database/Test_csv_read.py","file_name":"Test_csv_read.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"39969836","text":"\"\"\"First_Django URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', 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: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\n#Links all of the urls.py from each app to the main urls\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('log_in/', include('log_in.urls')),\n path('', include('Home_Page.urls')),\n path('about/', include('about.urls')),\n path('FAQ/', include('FAQ.urls')),\n path('guide/', include('guide.urls')),\n path('signup/', include('signup.urls')),\n path('topMemes/', include('topMemes.urls')),\n path('upload/', include('upload.urls')),\n path('log_out/', include('logout.urls')),\n path('your_memes/', include('Your_Memes.urls')),\n] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)\n","sub_path":"First_Django/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177740511","text":"import cbmpy\nimport numpy as np\nimport os\nimport sys\nimport pandas as pd\n\nmodelLoc = sys.argv[1]\ngrowthMediumLoc = sys.argv[2]\nscriptLoc = sys.argv[3]\nproteomicsLoc = sys.argv[4]\nresultsFolder = sys.argv[5]\n\nmodel = cbmpy.CBRead.readSBML3FBC(modelLoc, scan_notes_gpr = False)\ngrowthData = pd.read_csv(growthMediumLoc)\nproteomicsData = pd.read_csv(proteomicsLoc)\nresultsPath = '%s/%s' %(scriptLoc, resultsFolder)\nif not (os.path.isdir(resultsPath)): os.mkdir(resultsPath)\nos.chdir(resultsPath)\n\n\"\"\"\nMetabolic constraints\t\t\t\n\"\"\"\nfor i in growthData['Reaction ID']:\n\tmodel.setReactionLowerBound(i, growthData['Lower Bound'].loc[growthData['Reaction ID']==i].values[0])\n\n\"\"\"\nProteomic constraints\nShould be commented out for the \"w/o proteomic constraints\" condition.\n\"\"\"\nfor i in proteomicsData['Entry']:\n\tif (proteomicsData['conc_mmolgDW'].loc[proteomicsData['Entry']==i].values[0] == ('#VALUE!')): continue\n\telif np.isnan(float(proteomicsData['conc_mmolgDW'].loc[proteomicsData['Entry']==i].values[0])): continue\n\telif (proteomicsData['conc_mmolgDW'].loc[proteomicsData['Entry']==i].values[0] == 0.0): continue\n\telse: model.setReactionBounds('P_%s_synthesis' %(i), float(proteomicsData['0.9conc'].loc[proteomicsData['Entry']==i].values[0]), 1000.0)\n\n\"\"\"\nTotal protein volume constraint for E. coli\nSee the supplementary material of the paper for the derivation of the constraint\n\"\"\"\nprotSum=float(0.62/0.34)\npID = 'UP000000625'\nconstraint = []\nUniProtIDs = pd.read_csv('proteinMasses.txt', sep = '\\t')\n\nfor entry in UniProtIDs.index: constraint.append([(7.3*pow(10,-4)*float(UniProtIDs['Mass'][entry].replace(',', ''))), 'P_%s_synthesis' %(UniProtIDs['Entry'][entry])])\n\nmodel.addUserConstraint(pid = None, fluxes = constraint, operator = '<=', rhs = protSum)\n\nfbaResult = cbmpy.CBCPLEX.cplx_analyzeModel(model)\nif np.isnan(float(fbaResult)): sys.exit(0) #terminate if infeasible\n\nfva = cbmpy.CBCPLEX.cplx_FluxVariabilityAnalysis(model, pre_opt=True)\ncbmpy.CBWrite.writeFVAdata(fva[0], fva[1], os.path.split(growthMediumLoc)[1])\n","sub_path":"publicationData/paperResultsScripts/Fig3.py","file_name":"Fig3.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631574106","text":"from veryeasymdt import *\nfrom holoeye import slmdisplaysdk\nimport pyvisa\nimport numpy as np\nfrom utils import ascii_list_to_ndarray, extract_effi_ct, extract_ave_effi\nimport time\n\n\nclass AutoAlignment:\n def __init__(self, mdt_serial0, mdt_serial1, slm_datafiles, ks_mppm_addr, powermeter_ports, **kwargs):\n # connect the Thorlabs piezo controllers\n self.mdt0 = MDT(mdt_serial0)\n self.mdt1 = MDT(mdt_serial1)\n self.mdt0.SetAllVoltage(20)\n self.mdt1.SetAllVoltage(20)\n self.__current_set_voltages = [20] * 6\n self.limit_voltages = self.get_limit_voltages()\n\n # connect Holoeye SLM\n self.slm = slmdisplaysdk.SLMDisplay()\n self.slm.utilsSLMPreviewShow()\n self.slm_datafiles = slm_datafiles\n self.slm_data_handles = self.slm_preload_data_from_file()\n self.slmErrorCode = slmdisplaysdk.SLMDisplay.ErrorCode\n self.slmShowFlags = slmdisplaysdk.SLMDisplay.ShowFlags\n\n # connect the Keysight multiport powermeter\n visa_rm = pyvisa.ResourceManager()\n self.ks_mppm = visa_rm.open_resource(ks_mppm_addr)\n self.ks_mppm.query('*IDN?')\n self.ks_mppm.write('*RST')\n self.ks_mppm.query('*TST?')\n self.ports_pyindices = np.array(powermeter_ports) - 1\n self.nport = len(powermeter_ports)\n\n # other parameters\n self.best_ave_effi = 0\n self.best_voltages = [0] * 6\n\n time.sleep(1)\n\n def get_current_set_voltages(self):\n return self.__current_set_voltages\n\n def slm_preload_data_from_file(self):\n handles = []\n for df in slm_datafiles:\n error, hd = self.slm.loadDataFromFile(df)\n assert error == self.slmErrorCode.NoError, self.slm.errorString(error)\n handles.append(hd)\n return handles\n\n def get_power(self):\n power_ascii = self.ks_mppm.query('fetch:power:all:csv?')\n power = np.fromstring(power_ascii, count=8, sep=',')\n return power\n\n def get_transfer_matrix(self):\n tm = np.zeros((self.nport, self.nport))\n for i, handle in self.slm_data_handles:\n self.slm.showDatahandle(handle)\n tm[i, :] = self.get_power()\n return tm\n\n def step_optimize_xp0(self, step):\n current = self.mdt0.GetXYZAxisVoltage()\n self.mdt0.SetXAxisVoltage(current + step)\n\n def step_optimize(self, step):\n\n # to get the current transfer matrix, average efficiency and set voltages\n transfer_matrix = self.get_transfer_matrix()\n ave_effi = extract_ave_effi(transfer_matrix)\n previous_set_voltages = self.__current_set_voltages.copy()\n current_set_voltages = self.__current_set_voltages\n\n # to move forward and backward along every axis and compare the average efficiency\n operations = [self.mdt0.SetXAxisVoltage,\n self.mdt0.SetYAxisVoltage,\n self.mdt0.SetZAxisVoltage,\n self.mdt1.SetXAxisVoltage,\n self.mdt1.SetYAxisVoltage,\n self.mdt1.SetZAxisVoltage]\n dev_ax = [0, 1, 2, 3, 4, 5]\n for op, dev_ax in zip(operations, dev_ax):\n new_voltage_f = current_set_voltages[dev_ax] + step\n op(new_voltage_f)\n new_transfer_matrix_f = self.get_transfer_matrix()\n new_ave_effi_f = extract_ave_effi(new_transfer_matrix_f)\n\n new_voltage_b = current_set_voltages[dev_ax] - step\n op(new_voltage_b)\n new_transfer_matrix_b = self.get_transfer_matrix()\n new_ave_effi_b = extract_ave_effi(new_transfer_matrix_b)\n\n effi_argmax = np.argmax([new_ave_effi_f, new_ave_effi_b, ave_effi])\n if effi_argmax == 0:\n current_set_voltages[dev_ax] = new_voltage_f\n elif effi_argmax == 1:\n current_set_voltages[dev_ax] = new_voltage_b\n op(current_set_voltages[dev_ax])\n\n # to check whether the current efficiency is better than the previous best\n new_transfer_matrix = self.get_transfer_matrix()\n new_ave_effi = extract_ave_effi(new_transfer_matrix)\n if new_ave_effi > self.best_ave_effi:\n self.best_ave_effi = new_ave_effi\n self.best_voltages = self.__current_set_voltages\n\n if current_set_voltages == previous_set_voltages:\n return False\n else:\n return True\n\n def get_limit_voltages(self):\n m0 = self.mdt0\n m1 = self.mdt1\n limit_voltages = np.array([[m0.GetXAxisMinVoltage(), m0.GetXAxisMaxVoltage()],\n [m0.GetYAxisMinVoltage(), m0.GetYAxisMaxVoltage()],\n [m0.GetZAxisMinVoltage(), m0.GetZAxisMaxVoltage()],\n [m1.GetXAxisMinVoltage(), m1.GetXAxisMaxVoltage()],\n [m1.GetYAxisMinVoltage(), m1.GetYAxisMaxVoltage()],\n [m1.GetZAxisMinVoltage(), m1.GetZAxisMaxVoltage()]])\n return limit_voltages\n\n def update_limit_voltages(self):\n self.limit_voltages = self.get_limit_voltages\n\n def randomize(self):\n m0 = self.mdt0\n m1 = self.mdt1\n lv = self.limit_voltages\n\n x0 = np.random.uniform(lv[0, 0], lv[0, 1])\n m0.SetXAxisVoltage(x0)\n y0 = np.random.uniform(lv[1, 0], lv[1, 1])\n m0.SetYAxisVoltage(y0)\n z0 = np.random.uniform(lv[2, 0], lv[2, 1])\n m0.SetYAxisVoltage(z0)\n x1 = np.random.uniform(lv[3, 0], lv[3, 1])\n m1.SetXAxisVoltage(x1)\n y1 = np.random.uniform(lv[4, 0], lv[4, 1])\n m1.SetYAxisVoltage(y1)\n z1 = np.random.uniform(lv[5, 0], lv[5, 1])\n m1.SetYAxisVoltage(z1)\n\n self.__current_set_voltages = [x0, y0, z0, x1, y1, z1]\n\n\nif __name__ == '__main__':\n mdt_serial0 = ''\n mdt_serial1 = ''\n ks_mppm_addr = ''\n slm_datafiles = []\n powermeter_ports = [1, 2, 3, 4, 5, 6, 7]\n step = 0.2\n epoch = 5\n\n aa = AutoAlignment(mdt_serial0, mdt_serial1, slm_datafiles, ks_mppm_addr, powermeter_ports)\n for ep in range(epoch):\n if aa.step_optimize(step):\n aa.randomize()\n","sub_path":"auto_alignment.py","file_name":"auto_alignment.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584762372","text":"#! /usr/bin/env python\n\nimport json\n\nimport requests\n\nfrom currency_converter.currency_symbols import get_currency_code\n\n\ndef validate_amount(amount):\n try:\n return float(amount)\n except:\n raise ValueError('Amount could not be converted to float.')\n\n\ndef get_currency_rates():\n r = requests.get('http://api.fixer.io/latest?base=USD')\n if r.status_code == 200:\n rates = json.loads(r.text)['rates']\n rates['USD'] = 1.0\n return rates\n else:\n raise ConnectionError('Connection error when downloading conversion rates.')\n\n\ndef generate_output(amount, input_code, output):\n return {\n \"input\": {\n \"amount\": round(amount, 2),\n \"currency\": input_code\n },\n \"output\": output\n }\n\n\ndef convert(amount, input_currency, output_currency=None):\n amount = validate_amount(amount)\n input_code = get_currency_code(input_currency)\n rates = get_currency_rates()\n\n if input_code not in rates:\n raise ValueError('Input currency unknown.')\n\n if output_currency is None:\n output = {}\n for currency_code in rates:\n rate = rates[currency_code] / rates[input_code]\n output[currency_code] = round(amount * rate, 2)\n else:\n output_code = get_currency_code(output_currency)\n if output_code in rates:\n rate = rates[output_code] / rates[input_code]\n output = {output_code: round(amount * rate, 2)}\n else:\n raise ValueError('Output currency unknown.')\n\n return generate_output(amount, input_code, output)\n\n","sub_path":"currency_converter/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177304989","text":"\"\"\"\r\n参数说明:graph为传入的带权图(有weight,如果没有请在建图时设置为1);\r\nrep_size是生成向量的维度,默认128;batch_size默认1000;\r\nepoch默认100,选择loss最小的结果保存;\r\nnegtive_ratio为负样本数目,默认为5,一般无需修改;\r\norder=1一阶相似度(first-order),=2二阶相似度(second-order),默认为3(first-order+second-order);\r\n\"\"\"\r\n\r\n\r\nimport random\r\nimport math\r\nimport numpy as np\r\nimport pandas as pd\r\nimport tensorflow as tf\r\nimport networkx as nx\r\n\r\n\r\n\r\nclass _LINE(object):\r\n\r\n def __init__(self, graph, rep_size=128, batch_size=1000, negative_ratio=5, order=3):\r\n self.cur_epoch = 0\r\n self.order = order\r\n self.g = graph\r\n self.node_size = graph.G.number_of_nodes()\r\n self.rep_size = rep_size\r\n self.batch_size = batch_size\r\n self.negative_ratio = negative_ratio\r\n\r\n self.gen_sampling_table()\r\n self.sess = tf.Session()\r\n cur_seed = random.getrandbits(32)\r\n #tf.reset_default_graph()\r\n initializer = tf.contrib.layers.xavier_initializer(\r\n uniform=False, seed=cur_seed)\r\n with tf.variable_scope(\"model\", reuse=None, initializer=initializer):\r\n self.build_graph()\r\n self.sess.run(tf.global_variables_initializer())\r\n\r\n\r\n def build_graph(self):\r\n self.h = tf.placeholder(tf.int32, [None])\r\n self.t = tf.placeholder(tf.int32, [None])\r\n self.sign = tf.placeholder(tf.float32, [None])\r\n\r\n cur_seed = random.getrandbits(32)\r\n self.embeddings = tf.get_variable(name=\"embeddings\"+str(self.order), shape=[\r\n self.node_size, self.rep_size], initializer=tf.contrib.layers.xavier_initializer(uniform=False, seed=cur_seed))\r\n self.context_embeddings = tf.get_variable(name=\"context_embeddings\"+str(self.order), shape=[\r\n self.node_size, self.rep_size], initializer=tf.contrib.layers.xavier_initializer(uniform=False, seed=cur_seed))\r\n # self.h_e = tf.nn.l2_normalize(tf.nn.embedding_lookup(self.embeddings, self.h), 1)\r\n # self.t_e = tf.nn.l2_normalize(tf.nn.embedding_lookup(self.embeddings, self.t), 1)\r\n # self.t_e_context = tf.nn.l2_normalize(tf.nn.embedding_lookup(self.context_embeddings, self.t), 1)\r\n self.h_e = tf.nn.embedding_lookup(self.embeddings, self.h)\r\n self.t_e = tf.nn.embedding_lookup(self.embeddings, self.t)\r\n self.t_e_context = tf.nn.embedding_lookup(\r\n self.context_embeddings, self.t)\r\n self.second_loss = -tf.reduce_mean(tf.log_sigmoid(\r\n self.sign*tf.reduce_sum(tf.multiply(self.h_e, self.t_e_context), axis=1)))\r\n self.first_loss = -tf.reduce_mean(tf.log_sigmoid(\r\n self.sign*tf.reduce_sum(tf.multiply(self.h_e, self.t_e), axis=1)))\r\n if self.order == 1:\r\n self.loss = self.first_loss\r\n else:\r\n self.loss = self.second_loss\r\n optimizer = tf.train.AdamOptimizer(0.001)\r\n self.train_op = optimizer.minimize(self.loss)\r\n\r\n def train_one_epoch(self):\r\n sum_loss = 0.0\r\n batches = self.batch_iter()\r\n batch_id = 0\r\n for batch in batches:\r\n h, t, sign = batch\r\n feed_dict = {\r\n self.h: h,\r\n self.t: t,\r\n self.sign: sign,\r\n }\r\n _, cur_loss = self.sess.run([self.train_op, self.loss], feed_dict)\r\n sum_loss += cur_loss\r\n batch_id += 1\r\n #print('epoch:{} sum of loss:{!s}'.format(self.cur_epoch, sum_loss))\r\n self.cur_epoch += 1\r\n return sum_loss\r\n\r\n def batch_iter(self):\r\n look_up = self.g.look_up_dict\r\n\r\n table_size = 1e7\r\n numNodes = self.node_size\r\n\r\n edges = [(look_up[x[0]], look_up[x[1]]) for x in self.g.G.edges()]\r\n\r\n data_size = self.g.G.number_of_edges()\r\n edge_set = set([x[0]*numNodes+x[1] for x in edges])\r\n shuffle_indices = np.random.permutation(np.arange(data_size))\r\n\r\n # positive or negative mod\r\n mod = 0\r\n mod_size = 1 + self.negative_ratio\r\n h = []\r\n t = []\r\n sign = 0\r\n\r\n start_index = 0\r\n end_index = min(start_index+self.batch_size, data_size)\r\n while start_index < data_size:\r\n if mod == 0:\r\n sign = 1.\r\n h = []\r\n t = []\r\n for i in range(start_index, end_index):\r\n if not random.random() < self.edge_prob[shuffle_indices[i]]:\r\n shuffle_indices[i] = self.edge_alias[shuffle_indices[i]]\r\n cur_h = edges[shuffle_indices[i]][0]\r\n cur_t = edges[shuffle_indices[i]][1]\r\n h.append(cur_h)\r\n t.append(cur_t)\r\n else:\r\n sign = -1.\r\n t = []\r\n for i in range(len(h)):\r\n t.append(\r\n self.sampling_table[random.randint(0, table_size-1)])\r\n\r\n yield h, t, [sign]\r\n mod += 1\r\n mod %= mod_size\r\n if mod == 0:\r\n start_index = end_index\r\n end_index = min(start_index+self.batch_size, data_size)\r\n\r\n def gen_sampling_table(self):\r\n table_size = 1e7\r\n power = 0.75\r\n numNodes = self.node_size\r\n\r\n #print(\"Pre-procesing for non-uniform negative sampling!\")\r\n node_degree = np.zeros(numNodes) # out degree\r\n\r\n look_up = self.g.look_up_dict\r\n for edge in self.g.G.edges():\r\n node_degree[look_up[edge[0]]\r\n ] += self.g.G[edge[0]][edge[1]][\"weight\"]\r\n\r\n norm = sum([math.pow(node_degree[i], power) for i in range(numNodes)])\r\n\r\n self.sampling_table = np.zeros(int(table_size), dtype=np.uint32)\r\n\r\n p = 0\r\n i = 0\r\n for j in range(numNodes):\r\n p += float(math.pow(node_degree[j], power)) / norm\r\n while i < table_size and float(i) / table_size < p:\r\n if i % 100000 == 0:\r\n print(i, table_size, float(i) / table_size, p, j, numNodes)\r\n self.sampling_table[i] = j\r\n i += 1\r\n\r\n data_size = self.g.G.number_of_edges()\r\n self.edge_alias = np.zeros(data_size, dtype=np.int32)\r\n self.edge_prob = np.zeros(data_size, dtype=np.float32)\r\n large_block = np.zeros(data_size, dtype=np.int32)\r\n small_block = np.zeros(data_size, dtype=np.int32)\r\n\r\n total_sum = sum([self.g.G[edge[0]][edge[1]][\"weight\"]\r\n for edge in self.g.G.edges()])\r\n norm_prob = [self.g.G[edge[0]][edge[1]][\"weight\"] *\r\n data_size/total_sum for edge in self.g.G.edges()]\r\n num_small_block = 0\r\n num_large_block = 0\r\n cur_small_block = 0\r\n cur_large_block = 0\r\n for k in range(data_size-1, -1, -1):\r\n if norm_prob[k] < 1:\r\n small_block[num_small_block] = k\r\n num_small_block += 1\r\n else:\r\n large_block[num_large_block] = k\r\n num_large_block += 1\r\n while num_small_block and num_large_block:\r\n num_small_block -= 1\r\n cur_small_block = small_block[num_small_block]\r\n num_large_block -= 1\r\n cur_large_block = large_block[num_large_block]\r\n self.edge_prob[cur_small_block] = norm_prob[cur_small_block]\r\n self.edge_alias[cur_small_block] = cur_large_block\r\n norm_prob[cur_large_block] = norm_prob[cur_large_block] + norm_prob[cur_small_block] - 1\r\n if norm_prob[cur_large_block] < 1:\r\n small_block[num_small_block] = cur_large_block\r\n num_small_block += 1\r\n else:\r\n large_block[num_large_block] = cur_large_block\r\n num_large_block += 1\r\n\r\n while num_large_block:\r\n num_large_block -= 1\r\n self.edge_prob[large_block[num_large_block]] = 1\r\n while num_small_block:\r\n num_small_block -= 1\r\n self.edge_prob[small_block[num_small_block]] = 1\r\n\r\n def get_embeddings(self):\r\n vectors = {}\r\n embeddings = self.embeddings.eval(session=self.sess)\r\n # embeddings = self.sess.run(tf.nn.l2_normalize(self.embeddings.eval(session=self.sess), 1))\r\n look_back = self.g.look_back_list\r\n for i, embedding in enumerate(embeddings):\r\n vectors[look_back[i]] = embedding\r\n return vectors\r\n\r\n\r\nclass LINE(object):\r\n def __init__(self, graph, rep_size=128, batch_size=1000, epoch=100, negative_ratio=5, order=3, auto_save=True):\r\n self.rep_size = rep_size\r\n self.order = order\r\n self.best_result = 1e9\r\n self.best_ite=0\r\n self.vectors = {}\r\n if order == 3:\r\n self.model1 = _LINE(graph, int(rep_size/2), batch_size,\r\n negative_ratio, order=1)\r\n self.model2 = _LINE(graph,int(rep_size/2), batch_size,\r\n negative_ratio, order=2)\r\n for i in range(epoch):\r\n loss1=self.model1.train_one_epoch()\r\n loss2=self.model2.train_one_epoch()\r\n loss=loss1+loss2\r\n self.get_embeddings()\r\n # pos_test=gen_pos(df_test, self.vectors)\r\n # neg_test=gen_neg(pos_test,df_train,df_GD,df_MD,is_test_GD,self.vectors)\r\n # test_data=gen_test(pos_test, neg_test)\r\n # result=auc_score(test_data)\r\n if loss < self.best_result:\r\n self.best_result = loss\r\n self.best_ite=i\r\n if auto_save:\r\n self.best_vector = self.vectors\r\n self.model1.sess.close()\r\n self.model2.sess.close()\r\n\r\n else:\r\n self.model = _LINE(graph, rep_size, batch_size,\r\n negative_ratio, order=self.order)\r\n for i in range(epoch):\r\n loss=self.model.train_one_epoch()\r\n self.get_embeddings()\r\n if loss<self.best_result:\r\n self.best_result=loss\r\n self.best_ite = i\r\n if auto_save:\r\n self.best_vector=self.vectors\r\n self.model.sess.close()\r\n\r\n if auto_save:\r\n self.vectors = self.best_vector\r\n\r\n\r\n def get_embeddings(self):\r\n self.last_vectors = self.vectors\r\n self.vectors = {}\r\n if self.order == 3:\r\n vectors1 = self.model1.get_embeddings()\r\n vectors2 = self.model2.get_embeddings()\r\n for node in vectors1.keys():\r\n self.vectors[node] = np.append(vectors1[node], vectors2[node])\r\n else:\r\n self.vectors = self.model.get_embeddings()\r\n\r\n def save_embeddings(self, filename):\r\n df=pd.DataFrame(columns=['node','vector'])\r\n for node, vec in self.vectors.items():\r\n df=df.append({'node': node, 'vector': vec}, ignore_index=True)\r\n df.to_csv(filename,index=False)\r\n\r\n\r\nclass Graph(object):\r\n def __init__(self):\r\n self.G = None\r\n self.look_up_dict = {}\r\n self.look_back_list = []\r\n self.node_size = 0\r\n\r\n def encode_node(self):\r\n look_up = self.look_up_dict\r\n look_back = self.look_back_list\r\n for node in self.G.nodes():\r\n look_up[node] = self.node_size\r\n look_back.append(node)\r\n self.node_size += 1\r\n # self.G.nodes[node]['status'] = ''\r\n\r\n def read_g(self, g):\r\n self.G = g\r\n self.encode_node()\r\n\r\n def read_graph(self,df):\r\n G = nx.Graph()\r\n def load_single_entry(x):\r\n G.add_node(x['node1'], type=x['node1_type'])\r\n G.add_node(x['node2'], type=x['node2_type'])\r\n G.add_edge(x['node1'], x['node2'], weight=float(x['weight']))\r\n df.apply(load_single_entry, axis=1)\r\n self.G=G\r\n self.encode_node()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n input_csv=\"~/project/visual-analysis-platform/data/GD_human.csv\"#文件路径名称\r\n graph_df = pd.read_csv(input_csv, names=['node1', 'node1_type', 'node2', 'node2_type', 'weight'],\r\n dtype={'node1': str, 'node2': str, 'weight': float})\r\n g = Graph()\r\n g.read_graph(graph_df)\r\n model = LINE(g,epoch=1,rep_size=128, order=3)\r\n model.save_embeddings(\"./test.csv\") #filename为要写入的文件名及路径\r\n","sub_path":"algorithm/graph/graph_nn/_line.py","file_name":"_line.py","file_ext":"py","file_size_in_byte":12701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197532545","text":"#encoding: utf-8\nfrom hashlib import sha1\nimport pycabinet\nimport os\n\nPROJ_PATH = '/data0/ntfs'\nDATA_PATH = os.path.join(PROJ_PATH,'data/')\n\ndef safetch(dbname,dbpath=PROJ_PATH):\n dbname = os.path.join(dbpath,dbname)\n try:\n os.stat(dbname)\n except:\n pycabinet.create(dbname)\n return dbname\n\ndef ntsha1(k):\n \"\"\"\n >>> ntsha1(\"IDC|西单网通|port1|d\")\n '7ab0512e54099ce5be8819eabc41be2dc46fa106'\n \"\"\"\n return sha1(k).hexdigest()\n\ndef autodir(s,dirpath=DATA_PATH):\n \"\"\"\n >>> autodir(\"IDC|西单网通|port1|d\")\n '267a011c682b67839e358faf6ba016ac7fed1d4c'\n \"\"\"\n p = os.path.join(dirpath,ntsha1(s.split(\"|\")[0]))\n try:\n os.stat(p)\n except:\n os.makedirs(p)\n return p\n\ndef genkey(s):\n hashdb = safetch('hashkey.tch')\n key = pycabinet.get(hashdb,s)\n if key==None:\n key=ntsha1(s)\n pycabinet.put(hashdb,s,key)\n fname = safetch( \"%s.tch\" % key, autodir(s) )\n return key\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"64958286","text":"import json\n\n\nMAX_CUBE = 0\nMAX_THERMOSTAT = 1\nMAX_THERMOSTAT_PLUS = 2\nMAX_WALL_THERMOSTAT = 3\nMAX_WINDOW_SHUTTER = 4\nMAX_PUSH_BUTTON = 5\n\nMAX_DEVICE_MODE_AUTOMATIC = 0\nMAX_DEVICE_MODE_MANUAL = 1\nMAX_DEVICE_MODE_VACATION = 2\nMAX_DEVICE_MODE_BOOST = 3\n\nMAX_DEVICE_BATTERY_OK = 0\nMAX_DEVICE_BATTERY_LOW = 1\n\n\nclass MaxDevice(object):\n def __init__(self):\n self.rf_address = None\n self.type = None\n self.room_id = None\n self.firmware = None\n self.serial = None\n self.name = None\n self.initialized = None\n self.battery = None\n\n def is_thermostat(self):\n return self.type in (MAX_THERMOSTAT, MAX_THERMOSTAT_PLUS)\n\n def is_wallthermostat(self):\n return self.type == MAX_WALL_THERMOSTAT\n\n def is_windowshutter(self):\n return self.type == MAX_WINDOW_SHUTTER\n\n def is_room(self):\n return False\n\n def to_dict(self):\n data = {}\n \n keys = ['rf_address', 'type', 'room_id', 'firmware', 'serial', 'name', 'initialized',\n 'battery', 'comfort_temperature', 'eco_temperature', 'max_temperature',\n 'min_temperature', 'target_temperature', 'actual_temperature',\n 'locked', 'mode', 'vacation_until', 'temperature_offset', 'window_open_temperature',\n 'window_open_duration', 'boost_duration', 'boost_valve_position', 'decalcification', \n 'max_valve_setting', 'valve_offset', 'valve_position', 'programme']\n for key in keys:\n data[key] = getattr(self, key, None)\n data['rf_address'] = self.rf_address\n return data\n","sub_path":"maxcube/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91771153","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport math\nimport time\nimport json\nimport shlex\nimport signal\nimport socket\nimport psutil\nimport atexit\nimport logging\nimport requests\nimport subprocess\nfrom datetime import datetime\nfrom threading import Timer, Thread\nfrom multiprocessing import Process\nfrom logging.handlers import TimedRotatingFileHandler\n\ntry:\n import asyncio\nexcept ImportError:\n pass\n\n\n# Disk\nmix_ratio = 90\nbs_dict = {\"ssd\": \"4k\", \"hdd\": \"256k\"}\ndisk_umount = \"umount /dev/%s\"\ndmsetup_disk = \"dmsetup ls | grep -v 'No devices found' | awk '{if($1!~\\\"^centos\\\")print$1}' | while read n;do dmsetup remove ${n};done\"\nwipefs_disk = \"wipefs -a /dev/%s\"\nformat_disk = \"mkfs.xfs /dev/%s\"\nmount_disk = \"mount -t xfs /dev/%s %s\"\nlsblk_disk = \"lsblk -d -o name | grep -v NAME\"\nmount_point_template = \"/fio_test/%s\"\n# disk_usage_command = \"df -BM /dev/%s | grep -v 'Filesystem'\"\n# system_disk = \"df -h | grep -E '/$' | awk '{print $1}'\"\n# removable = \"cat /sys/block/%s/removable\"\n# usb_device = \"ls -l /dev/disk/by-path | grep usb | grep -v part | grep %s | wc -l\"\n# check_disk_type = \"lsblk -d -o name,rota,type /dev/%s | grep -v NAME | awk '{print $1\\\" \\\"$2\\\" \\\"$3 }'\" # rota: hdd - 1; ssd - 0\nfio_command = \"fio -filename=%s -direct=1 -iodepth 1 -thread -rw=randrw -rwmixread=%s -ioengine=psync -bs=%s -size=5G -numjobs=64 -runtime=60 -group_reporting -name=file 2>&1 | grep read:\"\ndisk_usage = \"df -h /dev/%s | tail -n +2 | awk '{print $5}' | cut -d '%%' -f1\"\ndisk_total = \"df -h /dev/%s | tail -n +2 | awk '{print $2}'\"\n\n# memory\nmemory_tool_command = \"dmidecode --type memory | grep \\\"Speed:\\\" | grep -v \\\"Configured Memory\\\"\"\n\n# network\nbandwidth_test_command = \"nohup timeout 180s /usr/bin/painull client --count %s > /home/pi-miner/painull/painul.log 2>&1 &\"\nps_painull = \"ps -ef | grep \\\"painull client --count\\\" | grep -v timeout | grep -v grep | awk '{print $2}'\"\nbandwidth_quality_command = \"nohup /usr/bin/painull client-new --taskid=%s --ratioupper=%s %s > /tmp/painull.log 2>&1 &\"\nbandwidth_mix_command = \"nohup /usr/bin/painull client-mix --taskid=%s --ratioupper=%s %s > /tmp/painull.log 2>&1 &\"\nline_quality_command = \"nohup /usr/bin/painull client-quality %s > /tmp/painull.log 2>&1 &\"\nnetwork_quality_sock = \"/tmp/painull_result.sock\"\n# 查询没有内网 IP 的物理网卡;\n# ls /sys/class/net/ | grep -v \"`ls /sys/devices/virtual/net/`\" -- 在所有网卡中,去除虚拟网卡\n# grep \"`ip -br link | grep LOWER_UP | grep -v @ | awk '{print $1}' | awk -F '@' '{print $1}' | sort | uniq`\" -- 列出所有 LOWER_UP 网卡\n# grep -v \"$(ip -br -f inet a | grep 192 | awk '{print $1}' | awk -F '@' '{ print $2 }' | grep -v \\\"^$\\\")\" -- 去除 IP 为 192.xxx 的网卡\nall_net_card = \"ls /sys/class/net/ | grep -v \\\"`ls /sys/devices/virtual/net/`\\\" | grep \\\"`ip -br link | grep LOWER_UP | grep -v @ | awk '{print $1}' | sort | uniq`\\\"\"\nnet_card_bandwidth_data_path = \"/sys/class/net/%s/statistics/tx_bytes\"\nping_cmd = \"ping -c 100 -i 0.01 %s -I %s 2>&1 | grep -E \\\"packets|rtt\\\"\"\nping_addr = \"baidu.com\"\n\n# 获取 painull port\npainull_port = \"netstat -anlpt | grep painull | awk -F ' ' '{print $4}' | awk -F ':' '{print $2}' | sort | uniq\"\n\n# report IP\nsimple_URL = \"\"\nip_inet_addr = \"ip -br -f inet addr | awk '{print $1, $3}' | grep -v 'lo\\|ppy\\|docker\\|mgt\\|br-'\"\n# net_card_IP = \"ip -br a | grep %s | awk '{print $3}' | awk -F '/' '{print $1}'\"\ncurl_command = \"curl -s %s --interface %s | awk -F ':' '{print $1}'\"\nnet_config_path = \"/etc/sysconfig/network-scripts/\"\n\n# API url\nbase_url = \"\"\nbase_url_debug = \"\"\nreport_ip_url = \"\"\nfetch_ip_url = \"\"\nfetch_all_ip_url = \"\"\nbandwidth_quality_report_url = \"\"\nbandwidth_mix_report_url = \"\"\niops_report_url = \"\"\ndisk_track_detection_report_url = \"\"\ncpu_indicator_report_url = \"\"\nmemory_info_report_url = \"\"\nmulti_info_report_url = \"\"\ntoken = \"\"\ntoken_debug = \"\"\n\n# local info\nmachine_id_file = \"/etc/machine-id\"\n\n\nclass ConnectionLostError(Exception):\n \"\"\" Raised when connection is lost \"\"\"\n pass\n\n\nclass NetworkTest(object):\n \"\"\" \"\"\"\n def __init__(self, ip_pool_url, max_conn_num, report_url, debug):\n \"\"\" Init\n 带宽压测两个协程:1. 根据给定连接数,向 IP 池发包; 2. 测试各个网卡的丢包和延时,动态调整 协程1 的连接数,并计算整机带宽值\n self.conn_num_queue: 协程间, 压测连接数通讯队列, maxsize=1, -1: 压测协程停止压测流程,并退出\n self.status_queue: 记录压测状态, maxsize=1(0: 初始化状态;\n 1: 压测流程正常执行;\n 2: IP池无法提供足够数量IP, 用于带宽压测;\n ?3: 计划连接数与当前连接数相同, 记录数据, 退出压测流程)\n \"\"\"\n self.conn_num_queue = asyncio.Queue(maxsize=1)\n self.status_queue = asyncio.Queue(maxsize=1)\n self.servers_ip_queue = asyncio.Queue() # 从 IP 池获取到压测服务端 IP\n self.conn_num_lock = asyncio.Lock()\n self.status_lock = asyncio.Lock()\n self.servers_ip_lock = asyncio.Lock()\n self.stop_client = False\n self.ip_pool_url = ip_pool_url # IP 池地址\n self.max_conn_num = max_conn_num # 最大连接数 约等于 上报带宽(Mb)/8(Mb)\n self.network_cards = list()\n\n # 根据当前所有线路平均丢包率,动态调节压测连接数 {丢包率: 连接数系数}(lpr = loss packet rate)\n self.conn_num_gradient = {0: 0.5, 1: 0.5, 2: 0.5, 3: 0.5, 4: 0.5, 5: 0.5}\n self.lpr_value_point = 0.8 # 压测带宽达到上报带宽 80% 时,记录各条线路丢包率\n self.max_lpr = 5 # 各线路平均丢包率 = 5%时,作为带宽压测值\n\n # 测试结果报告\n self.average_value = 0\n self.max_value = 0\n self.line_quality_record = dict()\n self.report_url = report_url\n self.debug = debug\n\n def fetch_server_ip(self):\n \"\"\" Fetch other machine public network ip \"\"\"\n params = dict()\n ips = HttpRequest().fetch_data(self.ip_pool_url, params).get(\"data\", list())\n if len(ips) < self.max_conn_num * 2:\n ips = HttpRequest().fetch_data(fetch_all_ip_url, params).get(\"data\", list())\n for ip in ips:\n self.servers_ip_queue.put_nowait(ip)\n g_logger.debug(\"Fetched server IP: %s\" % self.servers_ip_queue)\n\n def fetch_network_cards(self):\n \"\"\" \"\"\"\n public_net_card_list, private_net_card_list = ReportLocalPublicIP.get_net_card()\n self.network_cards = public_net_card_list\n if len(self.network_cards) == 0:\n self.network_cards += private_net_card_list\n g_logger.info(\"Local network cards: %s\" % self.network_cards)\n\n def report_bandwidth_data(self, test_time, task_id):\n \"\"\" Report bandwidth pressure test data to server \"\"\"\n body_dict = {\"testTime\": test_time}\n body_dict.update({\"version\": \"v2\"})\n body_dict.update({\"commandID\": task_id})\n body_dict.update({\"avgUpbandwidth\": self.average_value})\n body_dict.update({\"maxUpbandwidth\": self.max_value})\n body_dict.update({\"lineQuality\": self.line_quality_record})\n HttpRequest(self.debug).report_data(self.report_url, body_dict)\n\n @staticmethod\n async def clean_queue(data_queue, lock):\n \"\"\" Clean data queue \"\"\"\n async with lock:\n size = data_queue.qsize()\n g_logger.debug(\"Start clean queue: %s, size: %s\" % (repr(data_queue), size))\n for i in range(size):\n if not data_queue.empty():\n data_queue.get_nowait()\n g_logger.debug(\"End clean queue: %s, size: %s\" % (repr(data_queue), data_queue.qsize()))\n\n async def set_conn_num(self, num):\n \"\"\" Set tcp conn num for network test coroutines \"\"\"\n await self.clean_queue(self.conn_num_queue, self.conn_num_lock)\n async with self.conn_num_lock:\n self.conn_num_queue.put_nowait(num)\n g_logger.debug(\"Set conn num: %s\" % num)\n\n @staticmethod\n async def subprocess_shell(cmd):\n \"\"\" asynchronous execute shell \"\"\"\n stdout = str()\n stderr = str()\n try:\n # g_logger.debug(\"Async execute shell: %s\" % cmd)\n proc = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE)\n # g_logger.debug(\"Async ping cmd: %s wait for result\" % cmd)\n stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=600)\n stdout = stdout.decode('utf-8')\n stderr = stderr.decode('utf-8')\n except Exception as e:\n g_logger.exception(\"Async execute shell error: %s\" % e)\n return stdout, stderr\n\n async def async_ping(self, interface):\n \"\"\" asynchronous ping for all net card \"\"\"\n lpr = 100\n avg_delay = 30\n try:\n interface_ip = interface\n cmd = \"%s | grep %s\" % (ip_inet_addr, interface)\n g_logger.debug(\"Fetch interface IP command: %s\" % cmd)\n stdout, stderr = await self.subprocess_shell(cmd)\n if stdout:\n interface_ip = stdout.split()[1].split(\"/\")[0]\n g_logger.debug(\"Interface:%s; IP: %s\" % (interface, interface_ip))\n if stderr:\n g_logger.error(\"Fetch interface IP error(%s), try ues interface(%s) ping\" % (stderr, interface_ip))\n\n cmd = ping_cmd % (ping_addr, interface_ip)\n g_logger.debug(\"Async ping cmd: %s\" % cmd)\n stdout, stderr = await self.subprocess_shell(cmd)\n if stdout:\n lpr = round(float(stdout.split(\",\")[2].strip().split(\" \")[0].split(\"%\")[0]), 2)\n avg_delay = round(float(stdout.split(\"=\")[1].strip().split(\"/\")[1]), 2)\n g_logger.info(\"Async ping: %s, result: %s\" % (cmd, stdout))\n if stderr:\n g_logger.error(\"Async ping: %s, error: %s\" % (cmd, stderr))\n except Exception as e:\n g_logger.exception(\"Async ping error: %s\" % e)\n return lpr, avg_delay\n\n async def network_quality_data(self):\n \"\"\" \"\"\"\n avg_lpr = 0\n result_dict = dict()\n for card in self.network_cards:\n lpr, delay = await self.async_ping(card)\n g_logger.debug(\"Network quality: network card: %s, delay: %s, loss packet rate: %s\" % (card, delay, lpr))\n avg_lpr += lpr\n result_dict.update({card: {\"networkDelay\": delay, \"packetLossRate\": lpr}})\n avg_lpr = int(avg_lpr / len(self.network_cards))\n g_logger.debug(\"Network quality: loss packet rate average value: %s\" % avg_lpr)\n return avg_lpr, result_dict\n\n async def read_bandwidth_data(self):\n \"\"\" \"\"\"\n bandwidth_data_list = list()\n pre_bandwidth_data = 0\n for i in range(120):\n now_bandwidth_data = 0\n for card in self.network_cards:\n if not card:\n continue\n file_path = net_card_bandwidth_data_path % card\n if os.path.exists(file_path):\n try:\n with open(file_path) as f:\n tmp_data = int(f.read())\n now_bandwidth_data += tmp_data\n g_logger.debug(\"net card %s,/sys/class/net/%s/statistics/tx_bytes:%s\" % (card, card, tmp_data))\n except OSError as e:\n g_logger.exception(\"Can not read file %s, reason: %s\" % (file_path, e))\n else:\n g_logger.error(\"net card %s, /sys/class/net/%s/statistics/tx_bytes can not be read\" % (card, card))\n\n bandwidth_data_list.append(now_bandwidth_data - pre_bandwidth_data) if i != 0 else \"\"\n g_logger.info(\"bandwidth data: %s\" % bandwidth_data_list)\n pre_bandwidth_data = now_bandwidth_data\n await asyncio.sleep(1)\n return bandwidth_data_list\n\n async def calc_bandwidth_value(self):\n \"\"\" \"\"\"\n average_value = 0\n max_value = 0\n data_list = await self.read_bandwidth_data()\n if data_list:\n summary = 0\n data_list.sort(reverse=True)\n max_value = data_list[0] * 8\n for value in data_list:\n summary += value\n average_value = (summary / len(data_list)) * 8\n g_logger.info(\"Max bandwidth: %s; avg bandwidth: %s\" % (max_value, average_value))\n return average_value, max_value\n\n async def client_controller(self):\n \"\"\" Network test flow controller\n 控制协程: 根据压测协程的状态,决定压测流程\n \"\"\"\n avg_lpr, self.line_quality_record = await self.network_quality_data() # 未压测时,丢包率过高,停止压测,带宽压测值 = 0\n if avg_lpr > 5:\n self.stop_client = True\n g_logger.debug(\"When does not doing network test, loss packet rate average value: %s,stop test\" % avg_lpr)\n return 0, 0, self.line_quality_record\n\n avg_bw = 0\n max_bw = 0\n line_quality_record = dict()\n # test_status = 0\n plan_conn_num = int(self.conn_num_gradient[0] * self.max_conn_num) # 开始压测时连接数\n value_conn_num = math.ceil(self.lpr_value_point * self.max_conn_num) # 上报带宽 80%,压测带宽取值点\n await self.set_conn_num(plan_conn_num) # 初始化连接数\n g_logger.debug(\"Controller: Start network test, init conn num:%s\" % plan_conn_num)\n g_logger.debug(\"Controller: Bandwidth sampling conn num: %s\" % value_conn_num)\n g_logger.debug(\"Controller: Max conn num: %s\" % self.max_conn_num)\n\n while plan_conn_num <= self.max_conn_num:\n await asyncio.sleep(0.1)\n if not self.status_queue.empty():\n test_status = self.status_queue.get_nowait() # 获取压测协程的状态\n await asyncio.sleep(60) # 维持连接数一分钟, 用于压测带宽\n g_logger.debug(\"Controller: Get client running status: %s\" % test_status)\n else:\n continue\n\n if test_status == 1:\n try:\n avg_lpr, line_quality_dict = await self.network_quality_data()\n if plan_conn_num >= value_conn_num and len(line_quality_record) == 0:\n line_quality_record = line_quality_dict\n txt = \"Controller: Plan conn num:%s is equal to 80%% max conn num, statistic line info:%s\"\n g_logger.debug(txt % (plan_conn_num, line_quality_record))\n diff_value = int(self.max_lpr - avg_lpr)\n g_logger.debug(\"Controller: loss packet rate diff value: %s\" % diff_value)\n if diff_value <= 0:\n if avg_bw == 0 and max_bw == 0:\n avg_bw, max_bw = await self.calc_bandwidth_value()\n g_logger.debug(\"Controller:Lpr average:%s,bw avg:%s,bw max:%s\" % (avg_lpr, avg_bw, max_bw))\n if plan_conn_num >= value_conn_num:\n txt = \"Controller: Plan conn num %s is equal to 80%% max conn num %s, statistic data\"\n g_logger.info(txt % (plan_conn_num, self.max_conn_num))\n break\n else:\n if plan_conn_num >= self.max_conn_num:\n txt = \"Controller: Plan conn num %s is equal to max conn num %s, statistic data\"\n g_logger.info(txt % (plan_conn_num, self.max_conn_num))\n break\n coefficient = self.conn_num_gradient.get(int(avg_lpr), 0.5)\n plan_conn_num = math.ceil((self.max_conn_num - plan_conn_num) * coefficient + plan_conn_num)\n g_logger.debug(\"Controller:Coefficient:%s,modify plan conn num:%s\" % (coefficient, plan_conn_num))\n await self.set_conn_num(plan_conn_num)\n except Exception as e:\n g_logger.exception(\"%s\" % e)\n elif test_status == 2:\n g_logger.error(\"Controller: Client running status error, stop client\")\n break\n else:\n txt = \"Controller: Plan conn num %s is greater than max conn num %s, statistic data\"\n g_logger.info(txt % (plan_conn_num, self.max_conn_num))\n\n if len(line_quality_record) == 0:\n avg_lpr, line_quality_record = await self.network_quality_data()\n g_logger.debug(\"Controller: Plan conn num:%s, line info:%s\" % (plan_conn_num, line_quality_record))\n if avg_bw == 0 and max_bw == 0:\n avg_bw, max_bw = await self.calc_bandwidth_value()\n g_logger.debug(\"Controller: bw avg:%s, bw max:%s\" % (avg_bw, max_bw))\n self.stop_client = True\n g_logger.info(\"Controller: Test result bw avg: %s\" % avg_bw)\n g_logger.info(\"Controller: Test result bw max: %s\" % max_bw)\n g_logger.info(\"Controller: Test result line quality: %s\" % line_quality_record)\n self.average_value = int(avg_bw)\n self.max_value = int(max_bw)\n self.line_quality_record = line_quality_record\n g_logger.info(\"Controller: Controller Stopped !\")\n\n async def run_client(self, cid):\n \"\"\" Start client, send tcp packet to painull servers \"\"\"\n # data = bytes(b\"0\") * 131072\n data = bytes(b'0') * 1024 * 1024\n # g_logger.debug(\"Client %s: Client will send %s byte packet to servers\" % (cid, len(data)))\n\n sock = \"\"\n writer = None\n while True:\n try:\n sock = self.servers_ip_queue.get_nowait()\n ip = sock.split(\":\")[0]\n port = sock.split(\":\")[1]\n reader, writer = await asyncio.open_connection(ip, port, limit=len(data) + 1)\n g_logger.debug(\"Client %s: New connection be created: ip: %s, port: %s\" % (cid, ip, port))\n break\n except asyncio.QueueEmpty as e:\n g_logger.exception(\"Client %s: Servers ip queue empty, reason %s\" % (cid, e))\n raise asyncio.QueueEmpty(\"Servers ip queue empty\")\n except Exception as e:\n g_logger.exception(\"Client %s: Failed to connect server(%s), reason %s\" % (cid, sock, e))\n continue\n\n while True:\n if self.stop_client:\n try:\n writer.close()\n await writer.wait_closed()\n g_logger.debug(\"Client %s: AsyncIO stream writer %s be closed. Client Stopped !\" % (cid, writer))\n break\n except Exception as e:\n g_logger.exception(\"Client %s: AsyncIO stream writer %s close error %s\" % (cid, writer, e))\n raise RuntimeError(e)\n else:\n last_time = time.time_ns()\n try:\n if not writer.transport._conn_lost:\n writer.write(data)\n await writer.drain()\n await asyncio.sleep(0)\n duration = (last_time + 0.5 * 1.0e+9 - time.time_ns()) * 1.0e-9\n if duration > 1.0e-16:\n # g_logger.debug(\"Send packet stop duration: %s\" % duration)\n await asyncio.sleep(duration)\n # g_logger.debug(\"Client %s: send packet\" % cid)\n else:\n g_logger.error(\"Client %s: Connection is lost\" % cid)\n raise ConnectionLostError()\n except Exception as e:\n g_logger.exception(\"Client %s: AsyncIO stream writer %s, send packet error: %s\" % (cid, writer, e))\n writer.close()\n await writer.wait_closed()\n raise ConnectionLostError()\n\n async def start_client(self, plan_conn_num, current_conn_num, cid, event_loop=None, report_controller=True):\n \"\"\" \"\"\"\n while plan_conn_num > current_conn_num:\n if self.servers_ip_queue.qsize() == 0 & report_controller:\n try:\n self.status_queue.put_nowait(2)\n except asyncio.QueueFull as e:\n g_logger.exception(\"Creator: status queue full, reason: %s\" % e)\n txt = \"Creator: Current IP total num: %s, plan conn num: %s, need more servers IP\"\n g_logger.debug(txt % (self.servers_ip_queue.qsize(), plan_conn_num))\n break\n\n txt = \"Creator: Plan conn num: %s, current conn num: %s, need to create %s new connection\"\n g_logger.debug(txt % (plan_conn_num, current_conn_num, int(plan_conn_num - current_conn_num)))\n asyncio.run_coroutine_threadsafe(self.run_client(cid), event_loop)\n cid += 1\n current_conn_num += 1\n await asyncio.sleep(0.1)\n if plan_conn_num == current_conn_num and report_controller:\n g_logger.debug(\"Creator: current conn num: %s, connection created completion\" % current_conn_num)\n await self.status_queue.put(1)\n return current_conn_num, cid\n\n async def create_coroutine(self, event_loop=None):\n \"\"\" \"\"\"\n coroutine_index = 0\n plan_conn_num = 0\n current_conn_num = 0\n while True:\n await asyncio.sleep(0.1)\n tasks_set_len = len(asyncio.all_tasks(event_loop))\n if self.stop_client:\n while tasks_set_len > 0:\n tasks_set_len = len(asyncio.all_tasks(event_loop))\n await asyncio.sleep(1)\n g_logger.debug(\"Creator: Creator Stopped !\")\n break\n # g_logger.debug(\"Creator: Current running task num: %s\" % tasks_set_len)\n if tasks_set_len < current_conn_num:\n txt = \"Creator: Current conn num: %s, created conn num: %s, need create %s connection again\"\n g_logger.debug(txt % (tasks_set_len, current_conn_num, current_conn_num - tasks_set_len))\n current_conn_num = tasks_set_len\n current_conn_num, coroutine_index = await self.start_client(plan_conn_num, current_conn_num,\n coroutine_index, event_loop, False)\n\n if not self.conn_num_queue.empty():\n async with self.conn_num_lock:\n plan_conn_num = self.conn_num_queue.get_nowait()\n txt = \"Creator: Newest plan conn num: %s, current conn num: %s\"\n g_logger.debug(txt % (plan_conn_num, current_conn_num))\n\n current_conn_num, coroutine_index = await self.start_client(plan_conn_num, current_conn_num,\n coroutine_index, event_loop, True)\n\n @staticmethod\n def start_loop(event_loop):\n \"\"\" \"\"\"\n asyncio.set_event_loop(event_loop)\n event_loop.run_forever()\n\n def async_run(self):\n \"\"\" \"\"\"\n # start send packet event loop\n thread_loop = asyncio.new_event_loop()\n run_loop_thread = Thread(target=self.start_loop, args=(thread_loop,))\n run_loop_thread.setDaemon(True)\n run_loop_thread.start()\n\n # run main event loop\n main_loop = asyncio.get_event_loop()\n # g_logger.debug(\"thread_loop: %s; running_loop: %s\" % (id(thread_loop), id(main_loop)))\n tasks = [self.create_coroutine(thread_loop), self.client_controller()]\n main_loop.run_until_complete(asyncio.wait(tasks, timeout=3000))\n\n\ndef set_logger(path=\"\", category=\"log\", name=\"painull_tool\", clear_handler=False):\n \"\"\" Set logger system \"\"\"\n logger_name = name\n logger = logging.getLogger(logger_name)\n logger.setLevel(logging.DEBUG) # 必须设置 level,否则是否 root logger level,默认是 warming,将导致其他句柄无输出\n if clear_handler:\n for handler in logger.handlers:\n logger.removeHandler(handler)\n\n dir_name = \"painull_tool\"\n if path:\n log_path = os.path.abspath(os.path.join(path, dir_name, category, \"%s.log\" % logger_name))\n else:\n log_path = os.path.abspath(os.path.join(os.getcwd(), dir_name, category, \"%s.log\" % logger_name))\n\n if not os.path.exists(os.path.dirname(log_path)):\n os.makedirs(os.path.dirname(log_path))\n\n file_handler = TimedRotatingFileHandler(log_path, when='W6', interval=1, backupCount=20, encoding=\"utf-8\")\n file_handler.setLevel(logging.DEBUG)\n log_format = \"%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s\"\n data_format = \"%a %d %b %Y %H:%M:%S\"\n formatter = logging.Formatter(log_format, data_format)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n return logger\n\n\ng_logger = set_logger(path=\"/var/log\", category=\"disk\", clear_handler=True)\n\n\ndef set_logger_callback(path=\"\", category=\"log\", name=\"painull_tool\", clear_handler=True):\n \"\"\" set logger config callback \"\"\"\n global g_logger\n g_logger = set_logger(path=path, category=category, name=name, clear_handler=clear_handler)\n\n\nclass HttpRequest(object):\n \"\"\" Upload pressure test result \"\"\"\n def __init__(self, debug=False):\n \"\"\" init \"\"\"\n if debug:\n self.token = token_debug\n else:\n self.token = token\n if debug:\n self.base_url = base_url_debug\n else:\n self.base_url = base_url\n self.headers = {'Authorization': self.token, 'Content-Type': 'application/json'}\n machine_id = \"\"\n try:\n with open(machine_id_file) as f:\n machine_id = f.read()\n except OSError as e:\n g_logger.exception(\"Can not open file %s, reason: %s\" % (machine_id_file, e))\n self.machine_id = machine_id.strip()\n\n def report_data(self, url, report_data):\n \"\"\" Report test data to server \"\"\"\n try:\n url = self.base_url + url\n g_logger.debug(\"url: %s, header: %s\" % (url, self.headers))\n report_data.update({\"deviceUUID\": self.machine_id})\n body = json.dumps(report_data)\n g_logger.info(\"Report body: %s\" % body)\n for i in range(5):\n response = requests.post(url=url, data=body, headers=self.headers, verify=False)\n if response.status_code == 200:\n g_logger.debug(\"Report data successfully, data: %s\" % report_data)\n break\n else:\n txt = \"Report data failed, report times: %s, status code: %s, reason: %s\"\n g_logger.error(txt % (i, response.status_code, response.json()))\n except Exception as e:\n g_logger.exception(\"Http report data error: %s\" % e)\n\n def fetch_data(self, url, query):\n \"\"\" Fetch data from server \"\"\"\n info = dict()\n try:\n url = self.base_url + url\n query.update({\"deviceUUID\": self.machine_id})\n response = requests.get(url=url, params=query, headers=self.headers, verify=False)\n if response.status_code == 200:\n info = response.json()\n else:\n g_logger.error(\"Fetch data failed, reason: %s\" % response.reason)\n except Exception as e:\n g_logger.exception(\"Http fetch data error: %s\" % e)\n return info\n\n\nclass ReportLocalPublicIP(object):\n \"\"\" Report the machine all public IP\n \"\"\"\n def __init__(self, sever_port, report_url, debug=False):\n \"\"\" init \"\"\"\n self.server_port = sever_port\n self.report_url = report_url\n self.public_ips = list()\n self.debug = debug\n\n @staticmethod\n def get_net_card():\n \"\"\" Fetch all net card name \"\"\"\n public_net_card_list = list()\n private_net_card_list = list()\n output = exec_shell(ip_inet_addr).strip().split(\"\\n\")\n for line in output:\n if not line:\n continue\n try:\n net_card_name = line.split(\" \")[0].strip()\n if \"@\" in net_card_name:\n net_card_name = net_card_name.split(\"@\")[0]\n\n if \"ppp\" in net_card_name or \"wan\" in net_card_name:\n public_net_card_list.append(net_card_name)\n else:\n ip = line.split(\" \")[1].strip()\n ip1 = int(ip.split(\".\")[0])\n ip2 = int(ip.split(\".\")[1])\n if ip1 == 192 and ip2 == 168:\n is_public_ip = 0\n elif ip1 == 10:\n is_public_ip = 0\n elif ip1 == 172 and 32 < ip2 >= 16:\n is_public_ip = 0\n else:\n is_public_ip = 1\n\n if is_public_ip == 1:\n public_net_card_list.append(net_card_name)\n else:\n private_net_card_list.append(net_card_name)\n except IndexError as e:\n g_logger.exception(\"Net card info(%s) format error: %s\" % (line, e))\n except ValueError as e:\n g_logger.exception(\"Net card info(%s) format error: %s\" % (line, e))\n g_logger.debug(\"Public net card: %s; Private net card: %s\" % (public_net_card_list, private_net_card_list))\n return public_net_card_list, private_net_card_list\n\n def get_public_ips(self):\n \"\"\" Fetch all net card public ips \"\"\"\n ppp_ifcfg = list()\n wan_ifcfg = list()\n if os.path.exists(net_config_path):\n for root, dirs, filenames in os.walk(net_config_path):\n if root != net_config_path:\n continue\n for name in filenames:\n if \"ifcfg-ppp\" in name:\n ppp_ifcfg.append(name.split(\"-\")[1])\n elif \"ifcfg-wan\" in name:\n wan_ifcfg.append(name.split(\"-\")[1])\n if ppp_ifcfg:\n for ifcfg in ppp_ifcfg:\n output = exec_shell(curl_command % (simple_URL, ifcfg)).strip()\n self.public_ips.append(output) if output and output not in self.public_ips else \"\"\n elif wan_ifcfg:\n for ifcfg in wan_ifcfg:\n output = exec_shell(curl_command % (simple_URL, ifcfg)).strip()\n self.public_ips.append(output) if output and output not in self.public_ips else \"\"\n else:\n public_net_card_list, private_net_card_list = self.get_net_card()\n for card in public_net_card_list:\n output = exec_shell(curl_command % (simple_URL, card)).strip()\n self.public_ips.append(output) if output and output not in self.public_ips else \"\"\n for card in private_net_card_list:\n for i in range(100):\n output = exec_shell(curl_command % (simple_URL, card)).strip()\n self.public_ips.append(output) if output and output not in self.public_ips else \"\"\n\n def report_public_ips(self):\n \"\"\" Report machine all public ips to server \"\"\"\n body_dict = {\"reportTime\": int(time.mktime(datetime.now().timetuple()))}\n body_dict.update({\"listenPort\": int(self.server_port)})\n body_dict.update({\"ipList\": self.public_ips})\n HttpRequest(self.debug).report_data(self.report_url, body_dict)\n\n\ndef restore_signals():\n signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')\n for sig in signals:\n if hasattr(signal, sig):\n signal.signal(getattr(signal, sig), signal.SIG_DFL)\n\n\ndef exec_shell(command, shell=True, cwd=None, show_exception=False, debug=True):\n \"\"\" Exec shell cmd \"\"\"\n command = \"%s\" % command\n g_logger.debug(\"cmd: %s\" % command) if debug else \"\"\n if not shell:\n command = shlex.split(command)\n if cwd is None:\n cwd = os.path.abspath(os.path.dirname(__file__))\n try:\n result = subprocess.check_output(command, shell=shell, stderr=subprocess.STDOUT,\n cwd=cwd, preexec_fn=restore_signals).decode('utf-8')\n g_logger.debug(\"result: %s\" % result) if debug else \"\"\n return result\n except subprocess.CalledProcessError as e:\n g_logger.exception(\"Execute shell command err: %s\" % e)\n return \"EXCEPTION\" if show_exception else \"\"\n\n\ndef clear_env(process_name):\n \"\"\" clear env \"\"\"\n cmd = \"for pid in $(ps -ef| grep \\\"%s\\\" | grep -v grep | awk '{print $2}');do kill -9 $pid;done\" % process_name\n try:\n exec_shell(cmd)\n except Exception as e:\n g_logger.exception(\"kill process error: %s\" % e)\n\n\ndef unix_socket():\n data = \"\"\n server_address = network_quality_sock\n try:\n os.unlink(server_address)\n except OSError as e:\n if os.path.exists(server_address):\n g_logger.exception(\"Can not remove unix sock file %s:, reason %s\" % (server_address, e))\n\n try:\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.settimeout(360)\n sock.bind(server_address)\n sock.listen(1)\n g_logger.info(\"Socket created (%s), and listening\" % sock)\n\n connection, client_address = sock.accept()\n connection.settimeout(350)\n g_logger.info(\"socket connection: %s\" % connection)\n try:\n data = connection.recv(1024)\n if data:\n g_logger.info(\"reception data: %s\" % data)\n else:\n g_logger.error(\"Do not have data be received\")\n except Exception as e:\n g_logger.exception(\"Socket exception: %s\" % e)\n finally:\n g_logger.info(\"connection closed\")\n connection.close()\n except Exception as e:\n g_logger.exception(\"Unix socket exception %s\" % e)\n return data\n\n\nclass LoopTimer(Timer):\n \"\"\" Trigger timer repeatedly \"\"\"\n def run(self):\n \"\"\" Coverage run method \"\"\"\n while not self.finished.is_set():\n self.finished.wait(self.interval)\n self.function(*self.args, **self.kwargs)\n\n\nclass MonitorLog(object):\n \"\"\" Monitor log dynamically by tail -f command \"\"\"\n # DMESG = \"dmesg | tail -100\"\n TAIL = \"tail -f /var/log/messages\"\n\n def __init__(self):\n \"\"\" Init \"\"\"\n self.stopped = False\n self.callback = None\n self.params = None\n self.command = str()\n\n def register_callback(self, func, log_name=\"tail\", params=None):\n \"\"\" Register callback \"\"\"\n self.callback = func\n self.params = params if params else dict()\n try:\n self.command = getattr(self, log_name.upper())\n except AttributeError as e:\n g_logger.exception(\"Do not find monitor %s log command, reason: %s\" % (log_name, e))\n raise \"Do not find monitor %s log command\" % log_name\n\n def __monitor_log(self):\n \"\"\" Monitor log (使用互动式指令提取日志) \"\"\"\n g_logger.info(\"Monitor log sub process pid: %s\" % os.getpid())\n proc = subprocess.Popen(shlex.split(self.command), stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n shell=False, preexec_fn=os.setsid)\n g_logger.info(\"Tail log command sub process pid: %s\" % proc.pid)\n while not self.stopped:\n line = str(proc.stdout.readline().strip(), encoding=\"utf-8\")\n if line and self.callback is not None:\n self.callback(line, self.params)\n else:\n g_logger.error(\"Process stdout: %s, stderr: %s\" % (line, proc.stderr.readline().strip()))\n proc.terminate()\n\n # def __extract_log(self):\n # \"\"\" Extract log \"\"\"\n # g_logger.info(\"Extract log sub process pid: %s\" % os.getpid())\n # while not self.stopped:\n # line = exec_shell(self.command, debug=False)\n # if line and line != \"EXCEPTION\" and self.callback is not None:\n # self.callback(line, self.params)\n\n def start_monitor(self):\n \"\"\" Start monitor log \"\"\"\n g_logger.info(\"Master pid: %s\" % os.getpid())\n p = Process(target=self.__monitor_log, args=(), daemon=True)\n p.start()\n g_logger.info(\"Running monitor log sub process, pid: %s\" % p.pid)\n\n def stop_monitor(self):\n \"\"\" Stop monitor log \"\"\"\n self.stopped = True\n clear_env(self.command)\n\n\nclass Daemon(object):\n \"\"\" Daemon process \"\"\"\n def __init__(self, application, pid_path='/dev/shm', stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):\n \"\"\" daemon init \"\"\"\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.application = application\n self.pid_file = os.path.join(pid_path, \"%s_daemon.pid\" % \"painull_tool\")\n\n def single_instance_protection(self):\n \"\"\" Daemon is single instance process, forbid multi instance running simultaneously \"\"\"\n try:\n if os.path.exists(self.pid_file):\n with open(self.pid_file, 'r') as f:\n raw_pid = f.read()\n if raw_pid:\n if int(raw_pid) in psutil.pids() and \"xxx\" in psutil.Process(int(raw_pid)).cmdline()[1]:\n err_string = \"Error: %s pressure test daemon already running, raw pid %s\"\n print(err_string % (self.application.title(), raw_pid))\n raise RuntimeError(err_string % (self.application.title(), raw_pid))\n else:\n g_logger.info(\"%s pid file content is NULL\" % self.application)\n else:\n g_logger.info(\"%s pid file is not exist\" % self.application)\n except OSError as e:\n print(\"Fork: can not open pid file\")\n raise RuntimeError(\"Fork: can not open pid file: %s, %s \" % (e.errno, e.strerror))\n except psutil.NoSuchProcess as e:\n g_logger.warning(\"Pid file(%s) exit, but process is not exits, %s\" % (self.pid_file, e))\n\n def demonize(self):\n \"\"\" Create daemon \"\"\"\n self.single_instance_protection()\n\n try:\n pid = os.fork()\n if pid:\n print(\"Start %s test OK\" % self.application)\n g_logger.info(\"%s pressure test, father process exit, son process pid %s\" % (self.application, pid))\n sys.exit(0)\n else:\n g_logger.info(\"%s pressure test, son process start, fork result: %s\" % (self.application, pid))\n except OSError as e:\n print(\"Fork: first fork failed\")\n raise RuntimeError(\"Fork: first fork failed: %s, %s \" % (e.errno, e.strerror))\n\n os.chdir('/')\n os.setsid()\n os.umask(0)\n\n try:\n pid = os.fork()\n if pid:\n g_logger.info(\"%s pressure test, son process exit, grandson process pid %s\" % (self.application, pid))\n sys.exit(0)\n else:\n g_logger.info(\"%s pressure test, grandson process start, fork result: %s\" % (self.application, pid))\n except OSError as e:\n g_logger.exception(\"Fork: second fork failed\")\n raise RuntimeError(\"Fork: second fork failed: %s, %s \" % (e.errno, e.strerror))\n\n sys.stdout.flush()\n sys.stderr.flush()\n with open(self.stdin, 'rb', 0) as f:\n os.dup2(f.fileno(), sys.stdin.fileno())\n with open(self.stdout, 'ab', 0) as f:\n os.dup2(f.fileno(), sys.stdout.fileno())\n with open(self.stderr, 'ab', 0) as f:\n os.dup2(f.fileno(), sys.stderr.fileno())\n\n try:\n with open(self.pid_file, 'w+') as f:\n current_pid = str(os.getpid())\n f.write(current_pid)\n g_logger.info(\"%s test daemon pid %s, pid file: %s\" % (self.application, current_pid, self.pid_file))\n except OSError as e:\n g_logger.exception(\"Fork: can not create pid file\")\n raise RuntimeError(\"Fork: can not create pid file: %s, %s \" % (e.errno, e.strerror))\n atexit.register(os.remove, self.pid_file) # 进程异常退出时,删除 pid 文件\n signal.signal(signal.SIGTERM, self.__sigterm_handler) # 捕获到 SIGTERM 信号时,退出并删除 pid 文件\n\n # @staticmethod\n # def __clear_env(process_name):\n # \"\"\" clear env \"\"\"\n # cmd =\"for pid in $(ps -ef| grep \\\"%s\\\" | grep -v grep | awk '{print $2}');do kill -9 $pid;done\" % process_name\n # try:\n # exec_shell(cmd)\n # except Exception as e:\n # g_logger.exception(\"kill process error: %s\" % e)\n\n def __sigterm_handler(self, signal_num, frame):\n g_logger.debug(\"handler params: %s, %s\" % (signal_num, frame))\n if os.path.exists(self.pid_file):\n os.remove(self.pid_file)\n clear_env(\"perl -w ./Run\")\n clear_env(\"fio\")\n clear_env(\"python3.8 painull_tool.py\")\n raise SystemExit(1)\n\n def start(self, *args, **kwargs):\n \"\"\" Start daemon process \"\"\"\n try:\n self.demonize()\n except Exception as e:\n g_logger.exception(\"%s pressure test daemon run error\" % self.application)\n raise RuntimeError(\"%s pressure test daemon run error: %s\" % (self.application.title(), e))\n\n g_logger.debug(\"%s daemon run args: %s; kwargs: %s\" % (self.application, args, kwargs))\n self.run(*args, **kwargs)\n\n def stop(self):\n \"\"\" Stop daemon process \"\"\"\n if os.path.exists(self.pid_file):\n try:\n with open(self.pid_file) as f:\n pid = f.read()\n except IOError as e:\n g_logger.exception(\"Stop %s test daemon, can not open pid file(%s)\" % (self.application, e))\n pid = None\n else:\n pid = None\n\n if not pid:\n g_logger.error('Pid file(%s) does not exist. Daemon no running' % self.pid_file)\n raise RuntimeError('Pid file(%s) does not exist. Daemon no running' % self.pid_file)\n else:\n try:\n os.kill(int(pid), signal.SIGTERM)\n except OSError as e:\n if \"No such process\" in str(e):\n g_logger.info(\"No %s pressure test daemon\" % self.application)\n else:\n g_logger.exception(\"%s pressure test stop daemon error: %s\" % (self.application.title(), e))\n raise RuntimeError(\"%s pressure test stop daemon error: %s\" % (self.application.title(), e))\n finally:\n if os.path.exists(self.pid_file):\n os.remove(self.pid_file)\n\n def run(self, *args, **kwargs):\n \"\"\" Daemon handler \"\"\"\n g_logger.error(\"%s daemon run function Not Implemented\" % self.application)\n raise NotImplementedError\n","sub_path":"project_python/asyncio/bandwidth_test_tool.py","file_name":"bandwidth_test_tool.py","file_ext":"py","file_size_in_byte":43494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554228071","text":"\n\n#calss header\nclass _ARABESQUE():\n\tdef __init__(self,): \n\t\tself.name = \"ARABESQUE\"\n\t\tself.definitions = [u'a position in ballet in which the dancer stands on one leg with the other leg held out straight behind', u'a type of design based on flowers, leaves, and branches twisted together, found especially in Islamic art']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_arabesque.py","file_name":"_arabesque.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55280543","text":"from flask import request\nfrom flask_restx import Resource, Namespace, fields\nfrom src.castingagency.api.models.movie import Movie, MovieSchema\nfrom src.castingagency.auth.auth import requires_auth\n\nmovie_namespace = Namespace(\"Movies\", description='Movies')\n\nmovie_model = movie_namespace.model(\n \"Movie\",\n {\n \"title\": fields.String(description='Actor Name', example=\"Jamaal\"),\n \"release_date\": fields.Date(example=\"1998-04-04\"),\n },\n)\n\n\nclass MoviesList(Resource):\n @movie_namespace.doc(params={'Authorization': {'in': 'header',\n 'description': 'Authorization: Bearer <access_token>'}})\n @movie_namespace.response(200, \"Success\")\n @movie_namespace.response(401, \"Unauthorized\")\n @movie_namespace.response(403, \"Permission not found.\")\n @requires_auth('get:movies')\n def get(self, jwt):\n \"\"\"Get a list of all movies\"\"\"\n movies = MovieSchema().dump(Movie.query.all(), many=True)\n response_object = {\n 'success': True,\n 'movies': movies\n }\n return response_object, 200\n @movie_namespace.doc(params={'Authorization': {'in': 'header',\n 'description': 'Authorization: Bearer <access_token>'}})\n @movie_namespace.response(201, \"<movie_id> was updated!\")\n @movie_namespace.response(401, \"Unauthorized\")\n @movie_namespace.response(403, \"Permission not found.\")\n @movie_namespace.response(422, \"unprocessable\")\n @movie_namespace.expect(movie_model)\n @requires_auth('post:movie')\n def post(self, jwt):\n \"\"\"Create a movie\"\"\"\n try:\n request.get_json().pop('permission', None)\n post_data = request.get_json()\n movie = MovieSchema().load(post_data)\n Movie(title=movie.title, release_date=movie.release_date).insert()\n response_object = {\n 'success': True,\n 'message': f'{movie.title} was added!',\n 'movie': {\"title\": movie.title,\n \"release_date\": str(movie.release_date)}\n }\n return response_object, 201\n except:\n movie_namespace.abort(422, succcess=False, message=\"unprocessable\")\n\n\nclass Movies(Resource):\n\n @movie_namespace.doc(params={'Authorization': {'in': 'header',\n 'description': 'Authorization: Bearer <access_token>'}})\n @movie_namespace.response(200, \"Success\")\n @movie_namespace.response(401, \"Unauthorized\")\n @movie_namespace.response(403, \"Permission not found.\")\n @movie_namespace.response(404, \"Movie <movie_id> does not exist\")\n @movie_namespace.response(422, \"unprocessable\")\n @requires_auth('get:movie')\n def get(self, jwt, movie_id):\n \"\"\"Get details about a specific movie\"\"\"\n movie = MovieSchema().dump(Movie.query.get(movie_id))\n if not movie:\n movie_namespace.abort(404, success=False,\n message=f\"User {movie_id} does not exist\")\n response_object = {\n 'success': True,\n 'movie': movie\n }\n return response_object, 200\n\n @movie_namespace.doc(params={'Authorization': {'in': 'header',\n 'description': 'Authorization: Bearer <access_token>'}})\n @movie_namespace.expect(movie_model)\n @movie_namespace.response(200, \"<movie_id> was updated!\")\n @movie_namespace.response(401, \"Unauthorized\")\n @movie_namespace.response(403, \"Permission not found.\")\n @movie_namespace.response(404, \"Movie <movie_id> does not exist\")\n @movie_namespace.response(422, \"unprocessable\")\n @requires_auth('patch:movie')\n def patch(self, jwt, movie_id):\n \"\"\"Update detials about a specific movie\"\"\"\n movie = Movie.query.get(movie_id)\n if not movie:\n movie_namespace.abort(404, f\"Movie {movie_id} does not exist\")\n try:\n request.get_json().pop('permission', None)\n body = request.get_json()\n movie = MovieSchema().load(body, instance=movie, partial=True)\n movie.update()\n response_object = {\n 'success': True,\n 'message': f'{movie.id} was updated!',\n 'movie': {\"id\": movie.id,\n \"title\": movie.title,\n \"release_date\": str(movie.release_date)}\n }\n return response_object, 200\n except:\n movie_namespace.abort(422, succcess=False, message=\"unprocessable\")\n\n @movie_namespace.doc(params={'Authorization': {'in': 'header',\n 'description': 'Authorization: Bearer <access_token>'}})\n @movie_namespace.response(200, \"<movie_id> was removed!\")\n @movie_namespace.response(401, \"Unauthorized\")\n @movie_namespace.response(403, \"Permission not found.\")\n @movie_namespace.response(404, \"Movie <movie_id> does not exist\")\n @movie_namespace.response(422, \"unprocessable\")\n @requires_auth('delete:movie')\n def delete(self, jwt, movie_id):\n \"\"\"Delete a specific movie\"\"\"\n movie = Movie.query.get(movie_id)\n if not movie:\n movie_namespace.abort(404, f\"Movie {movie_id} does not exist\")\n try:\n movie.delete()\n response_object = {\n 'message': f'Movie id {movie.id}, {movie.title} was deleted!',\n 'success': True\n }\n return response_object, 200\n except:\n movie_namespace.abort(422, succcess=False, message=\"unprocessable\")\n\n\nmovie_namespace.add_resource(MoviesList, '')\nmovie_namespace.add_resource(Movies, '/<int:movie_id>')\n","sub_path":"src/castingagency/api/routes/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":5775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595464248","text":"import random\r\nimport sys\r\nimport sqlite3\r\nfrom PyQt5.QtCore import pyqtSlot, Qt, QBasicTimer\r\nfrom PyQt5.QtGui import QFont, QPainter, QColor\r\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QLabel, QPushButton, QMessageBox, \\\r\n QLineEdit, QFrame, QTableView\r\nimport PyQt5.QtSql\r\nimport webbrowser\r\n\r\n\r\n# Стартовое окно\r\nclass Start(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n self.InitUI()\r\n\r\n def InitUI(self):\r\n self.setWindowTitle('GAME BOX')\r\n self.setFixedSize(400, 300)\r\n\r\n self.label = QLabel('<i>Welcome to</i> <b>GAME BOX</i>', self)\r\n self.label.setFont(QFont(\"Times\", 20))\r\n self.label.resize(300, 30)\r\n self.label.move(50, 110)\r\n\r\n self.start_button = QPushButton(self)\r\n self.start_button.resize(70, 30)\r\n self.start_button.setText('START')\r\n self.start_button.move(160, 160)\r\n\r\n self.start_button.clicked.connect(self.go_to_main_menu)\r\n\r\n # pyqtSlot необходим для связи между виджетами\r\n @pyqtSlot()\r\n def go_to_main_menu(self):\r\n self.cams = MainMenu()\r\n self.close()\r\n\r\n\r\n# основное окно - главное меню\r\nclass MainMenu(QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.InitUI()\r\n self.show()\r\n\r\n def InitUI(self):\r\n self.setFixedSize(220, 140)\r\n self.setWindowTitle('Main menu')\r\n\r\n self.tictacbutton = QPushButton('Крестики - Нолики', self)\r\n self.tictacbutton.resize(200, 30)\r\n self.tictacbutton.move(10, 10)\r\n\r\n self.tetris_button = QPushButton('Тетрис', self)\r\n self.tetris_button.resize(200, 30)\r\n self.tetris_button.move(10, 40)\r\n\r\n self.statistics_button = QPushButton('Статистика игр', self)\r\n self.statistics_button.resize(200, 30)\r\n self.statistics_button.move(10, 70)\r\n\r\n self.faqbutton = QPushButton('FAQ', self)\r\n self.faqbutton.resize(200, 30)\r\n self.faqbutton.move(10, 100)\r\n\r\n # подключаем кнопки к функициям, которые откроют нужное окно\r\n self.tictacbutton.clicked.connect(self.go_to_tic_tac)\r\n self.tetris_button.clicked.connect(self.go_to_tetris)\r\n self.statistics_button.clicked.connect(self.go_to_statistics)\r\n self.faqbutton.clicked.connect(self.go_to_faq)\r\n\r\n @pyqtSlot()\r\n def go_to_tic_tac(self):\r\n self.tictac = TicTacToe()\r\n self.close()\r\n\r\n @pyqtSlot()\r\n def go_to_tetris(self):\r\n self.snake = Tetris()\r\n self.close()\r\n\r\n @pyqtSlot()\r\n def go_to_statistics(self):\r\n self.stats = Statistics()\r\n self.close()\r\n\r\n @pyqtSlot()\r\n def go_to_faq(self):\r\n self.faq = FAQ()\r\n self.close()\r\n\r\n\r\nclass FAQ(QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.InitUI()\r\n self.show()\r\n\r\n def InitUI(self):\r\n self.setFixedSize(200, 90)\r\n self.setWindowTitle('Info')\r\n\r\n self.label_ok = QLabel('Вы можете прочитать о GameBox в\\n репозитории github',\r\n self)\r\n self.label_ok.move(10, 10)\r\n\r\n self.go_to_github_button = QPushButton('Перейти', self)\r\n self.go_to_github_button.setGeometry(10, 50, 85, 30)\r\n\r\n self.back_button = QPushButton('В гланое меню', self)\r\n self.back_button.setGeometry(105, 50, 85, 30)\r\n\r\n self.url = 'https://github.com/ParzivalEugene/GameBox/blob/main/README.md'\r\n self.go_to_github_button.clicked.connect(lambda: webbrowser.open(self.url))\r\n self.back_button.clicked.connect(self.go_to_main_menu)\r\n\r\n @pyqtSlot()\r\n def go_to_main_menu(self):\r\n self.main_menu = MainMenu()\r\n self.close()\r\n\r\n\r\nclass TicTacToe(QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.InitUI()\r\n self.show()\r\n\r\n # в этой функции создаем внешний вид игры и привязываем кнопки к фукнциям\r\n def InitUI(self):\r\n self.setFixedSize(500, 290)\r\n self.setWindowTitle('Крестики-Нолики')\r\n\r\n self.turn = 0\r\n self.times = 0\r\n self.field = []\r\n self.side = 90\r\n\r\n for i in range(3):\r\n line = []\r\n for j in range(3):\r\n line.append((QPushButton(self)))\r\n self.field.append(line)\r\n\r\n for i in range(3):\r\n for j in range(3):\r\n self.field[i][j].setGeometry(self.side * i + 10, self.side * j + 10, 90, 90)\r\n self.field[i][j].setFont(QFont('Times', 20))\r\n self.field[i][j].clicked.connect(self.moved)\r\n\r\n self.info_line = QLineEdit(self)\r\n self.info_line.setGeometry(290, 10, 200, 40)\r\n self.info_line.setDisabled(True)\r\n\r\n self.reset_button = QPushButton('Играть заново', self)\r\n self.reset_button.setGeometry(310, 125, 160, 40)\r\n\r\n self.main_menu_button = QPushButton('Главное меню', self)\r\n self.main_menu_button.setGeometry(310, 240, 160, 40)\r\n\r\n self.reset_button.clicked.connect(self.reset_game)\r\n self.main_menu_button.clicked.connect(self.go_to_main_menu)\r\n\r\n # в этой фун��ции осуществляем проверку победы любого из игроков\r\n def moved(self):\r\n self.times += 1\r\n button = self.sender()\r\n button.setDisabled(True)\r\n if self.turn:\r\n button.setText('O')\r\n self.turn = 0\r\n else:\r\n button.setText('X')\r\n self.turn = 1\r\n\r\n info = self.check_win()\r\n winner = ''\r\n if info:\r\n if self.turn:\r\n winner = 'X won'\r\n else:\r\n winner = 'O won'\r\n for buttons in self.field:\r\n for button in buttons:\r\n button.setDisabled(True)\r\n elif self.times == 9:\r\n winner = 'Draw'\r\n if winner:\r\n # если игра закончилась, вносим в базу данных итоги матча\r\n self.add_to_data_base(winner)\r\n self.info_line.setText(winner)\r\n\r\n # делать проверку наличия базы данных не нужно, потому что в начале программы мы создаем пустые\r\n # или проверяем наличие уже имеющихся баз данных\r\n def add_to_data_base(self, winner):\r\n con = sqlite3.connect(\"tic_tac_toe_statistics.db\")\r\n cursor = con.cursor()\r\n cursor.execute(f\"INSERT INTO statistics VALUES ('player vs. player', '{winner.split()[0]}')\")\r\n con.commit()\r\n\r\n # функция, которая начинают игру заново\r\n def reset_game(self):\r\n self.turn = 0\r\n self.times = 0\r\n self.info_line.clear()\r\n for elems in self.field:\r\n for elem in elems:\r\n elem.setEnabled(True)\r\n elem.setText('')\r\n\r\n # Проверяем наличие победителя\r\n def check_win(self):\r\n cell = [[j.text() for j in i] for i in self.field]\r\n # проверка строк и столбцов\r\n for i in range(3):\r\n if cell[0][i] == cell[1][i] == cell[2][i] != '' \\\r\n or cell[i][0] == cell[i][1] == cell[i][2] != '':\r\n return True\r\n # проверка диагоналей\r\n if cell[0][0] == cell[1][1] == cell[2][2] != '' \\\r\n or cell[0][2] == cell[1][1] == cell[2][0] != '':\r\n return True\r\n # если нет линии из 3 х или о\r\n return False\r\n\r\n # возврат в главное меню\r\n @pyqtSlot()\r\n def go_to_main_menu(self):\r\n self.menu = MainMenu()\r\n self.close()\r\n\r\n\r\nclass Tetris(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n self.initUI()\r\n\r\n # оформляем внешний вид окна\r\n def initUI(self):\r\n self.info_line = QLineEdit('0', self)\r\n self.info_line.move(10, 770)\r\n self.info_line.resize(230, 30)\r\n self.info_line.setDisabled(True)\r\n\r\n self.back_button = QPushButton('В главное меню', self)\r\n self.back_button.resize(100, 30)\r\n self.back_button.move(250, 770)\r\n self.back_button.clicked.connect(self.go_to_main_menu)\r\n\r\n self.tetris_field = Field(self)\r\n self.tetris_field.resize(360, 760)\r\n\r\n self.tetris_field.start()\r\n self.setFixedSize(360, 810)\r\n self.setWindowTitle('Tetris')\r\n self.show()\r\n\r\n @pyqtSlot()\r\n def go_to_main_menu(self):\r\n self.menu = MainMenu()\r\n self.close()\r\n\r\n\r\nclass Field(QFrame):\r\n # объявляем константы поля и скорости\r\n FieldWidth = 10\r\n FieldHeight = 22\r\n Speed = 300\r\n\r\n def __init__(self, parent):\r\n super().__init__(parent)\r\n self.initField()\r\n # используем родительский класс для вывода информации в line edit\r\n self.parent = parent\r\n self.pauses_counter = 0\r\n\r\n def initField(self):\r\n self.timer = QBasicTimer()\r\n\r\n self.is_waiting = False\r\n self.is_started = False\r\n self.is_paused = False\r\n\r\n self.current_x = 0\r\n self.current_y = 0\r\n self.number_of_removed_lines = 0\r\n self.field = []\r\n\r\n self.setFocusPolicy(Qt.StrongFocus)\r\n self.clear_field()\r\n\r\n # возвращает форму фигуры\r\n def shape_at(self, x, y):\r\n return self.field[(y * Field.FieldWidth) + x]\r\n\r\n # задает форму фигуры\r\n def set_shape_at(self, x, y, shape):\r\n self.field[(y * Field.FieldWidth) + x] = shape\r\n\r\n # возвращает высоту квадрата\r\n def square_width(self):\r\n return self.contentsRect().width() // Field.FieldWidth\r\n\r\n # возвращает ширину квадрата\r\n def square_height(self):\r\n return self.contentsRect().height() // Field.FieldHeight\r\n\r\n # функции старта и паузы, начинают и останавливают игру соответственно\r\n def start(self):\r\n if self.is_paused:\r\n return\r\n\r\n self.is_started = True\r\n self.is_waiting = False\r\n\r\n self.number_of_removed_lines = 0\r\n\r\n self.clear_field()\r\n self.parent.info_line.setText(str(self.number_of_removed_lines))\r\n self.new_piece()\r\n self.timer.start(Field.Speed, self)\r\n\r\n def pause(self):\r\n if not self.is_started:\r\n return\r\n\r\n self.is_paused = not self.is_paused\r\n\r\n if self.is_paused:\r\n self.timer.stop()\r\n self.parent.info_line.setText('Пауза')\r\n self.pauses_counter += 1\r\n\r\n else:\r\n self.timer.start(Field.Speed, self)\r\n self.parent.info_line.setText(str(self.number_of_removed_lines))\r\n\r\n self.update()\r\n\r\n # объявляем правила рисования фигур\r\n def paintEvent(self, event):\r\n painter = QPainter(self)\r\n rect = self.contentsRect()\r\n\r\n # откуда будут появляться\r\n fieldTop = rect.bottom() - Field.FieldHeight * self.square_height()\r\n\r\n for i in range(Field.FieldHeight):\r\n for j in range(Field.FieldWidth):\r\n shape = self.shape_at(j, Field.FieldHeight - i - 1)\r\n\r\n if shape != TetrminoShape.No:\r\n self.draw_square(painter,\r\n rect.left() + j * self.square_width(),\r\n fieldTop + i * self.square_height(), shape)\r\n\r\n if self.piece.shape() != TetrminoShape.No:\r\n for i in range(4):\r\n x = self.current_x + self.piece.x(i)\r\n y = self.current_y - self.piece.y(i)\r\n self.draw_square(painter, rect.left() + x * self.square_width(),\r\n fieldTop + (Field.FieldHeight - y - 1) * self.square_height(),\r\n self.piece.shape())\r\n\r\n # привязваем действия к клавишам\r\n def keyPressEvent(self, event):\r\n if not self.is_started or self.piece.shape() == TetrminoShape.No:\r\n super(Field, self).keyPressEvent(event)\r\n return\r\n key = event.key()\r\n\r\n # ставит на паузу\r\n if key == Qt.Key_P:\r\n self.pause()\r\n return\r\n if self.is_paused:\r\n return\r\n\r\n # двигает фигуру влево\r\n elif key == Qt.Key_Left:\r\n self.try_to_move(self.piece, self.current_x - 1, self.current_y)\r\n\r\n # двигает фигуру вправо\r\n elif key == Qt.Key_Right:\r\n self.try_to_move(self.piece, self.current_x + 1, self.current_y)\r\n\r\n # вращает фигуру по часовой стрелке\r\n elif key == Qt.Key_Down:\r\n self.try_to_move(self.piece.rotate_left(), self.current_x, self.current_y)\r\n\r\n # вращает фигуру против часовой стрелки\r\n elif key == Qt.Key_Up:\r\n self.try_to_move(self.piece.rotate_left(), self.current_x, self.current_y)\r\n\r\n # полный спуск вниз\r\n elif key == Qt.Key_Space:\r\n self.drop_down()\r\n\r\n # более быстрый спуск вниз\r\n elif key == Qt.Key_D:\r\n self.one_line_down()\r\n else:\r\n super(Field, self).keyPressEvent(event)\r\n\r\n # создаем таймер чтобы фигура спускалась по шагам\r\n def timerEvent(self, event):\r\n if event.timerId() == self.timer.timerId():\r\n if self.is_waiting:\r\n self.is_waiting = False\r\n self.new_piece()\r\n else:\r\n self.one_line_down()\r\n else:\r\n super(Field, self).timerEvent(event)\r\n\r\n # очищаем поле\r\n def clear_field(self):\r\n for i in range(Field.FieldHeight * Field.FieldWidth):\r\n self.field.append(TetrminoShape.No)\r\n\r\n # быстрый спуск фигуры вниз\r\n def drop_down(self):\r\n newY = self.current_y\r\n while newY > 0:\r\n if not self.try_to_move(self.piece, self.current_x, newY - 1):\r\n break\r\n newY -= 1\r\n self.piece_dropped()\r\n\r\n # быстрее чем стандартный и контролируемый спуск\r\n def one_line_down(self):\r\n if not self.try_to_move(self.piece, self.current_x, self.current_y - 1):\r\n self.piece_dropped()\r\n\r\n # функция обозначающая что фигура достигла низа для проверки полной строки\r\n def piece_dropped(self):\r\n for i in range(4):\r\n x = self.current_x + self.piece.x(i)\r\n y = self.current_y - self.piece.y(i)\r\n self.set_shape_at(x, y, self.piece.shape())\r\n self.remove_full_lines()\r\n if not self.is_waiting:\r\n self.new_piece()\r\n\r\n # удаляет соболненую строку\r\n def remove_full_lines(self):\r\n numFullLines = 0\r\n rowsToRemove = []\r\n for i in range(Field.FieldHeight):\r\n n = 0\r\n for j in range(Field.FieldWidth):\r\n if not self.shape_at(j, i) == TetrminoShape.No:\r\n n = n + 1\r\n if n == 10:\r\n rowsToRemove.append(i)\r\n rowsToRemove.reverse()\r\n for m in rowsToRemove:\r\n for k in range(m, Field.FieldHeight):\r\n for l in range(Field.FieldWidth):\r\n self.set_shape_at(l, k, self.shape_at(l, k + 1))\r\n numFullLines = numFullLines + len(rowsToRemove)\r\n if numFullLines > 0:\r\n self.number_of_removed_lines = self.number_of_removed_lines + numFullLines\r\n self.parent.info_line.setText(str(self.number_of_removed_lines))\r\n self.is_waiting = True\r\n self.piece.set_shape(TetrminoShape.No)\r\n self.update()\r\n\r\n # создает новую фигуру\r\n def new_piece(self):\r\n self.piece = Shape()\r\n self.piece.set_shape_random()\r\n self.current_x = Field.FieldWidth // 2\r\n self.current_y = Field.FieldHeight - 1 + self.piece.min_y()\r\n if not self.try_to_move(self.piece, self.current_x, self.current_y):\r\n self.piece.set_shape(TetrminoShape.No)\r\n self.timer.stop()\r\n self.is_started = False\r\n self.parent.info_line.setText('Игра окончена')\r\n self.add_to_data_base()\r\n self.message()\r\n\r\n # по заверщению игры добавляет статистику в базу данных\r\n def add_to_data_base(self):\r\n lines = self.number_of_removed_lines\r\n pauses = self.pauses_counter\r\n con = sqlite3.connect(\"tetris_statistics.db\")\r\n cursor = con.cursor()\r\n cursor.execute(f\"INSERT INTO statistics VALUES ({lines}, {pauses})\")\r\n con.commit()\r\n\r\n # сообщение о проигрыше\r\n def message(self):\r\n QMessageBox.about(self, \"Игра окончена\", \"Вы проиграли\")\r\n\r\n # сдвиг фигуры в пределах границ поля\r\n def try_to_move(self, new_piece, newX, newY):\r\n for i in range(4):\r\n x = newX + new_piece.x(i)\r\n y = newY - new_piece.y(i)\r\n if x < 0 or x >= Field.FieldWidth or y < 0 or y >= Field.FieldHeight:\r\n return False\r\n if self.shape_at(x, y) != TetrminoShape.No:\r\n return False\r\n self.piece = new_piece\r\n self.current_x = newX\r\n self.current_y = newY\r\n self.update()\r\n return True\r\n\r\n # рисует единичный квадрат фигуры\r\n def draw_square(self, painter, x, y, shape):\r\n colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,\r\n 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]\r\n color = QColor(colorTable[shape])\r\n painter.fillRect(x + 1, y + 1, self.square_width() - 2,\r\n self.square_height() - 2, color)\r\n painter.setPen(color.lighter())\r\n painter.drawLine(x, y + self.square_height() - 1, x, y)\r\n painter.drawLine(x, y, x + self.square_width() - 1, y)\r\n painter.setPen(color.darker())\r\n painter.drawLine(x + 1, y + self.square_height() - 1,\r\n x + self.square_width() - 1, y + self.square_height() - 1)\r\n painter.drawLine(x + self.square_width() - 1,\r\n y + self.square_height() - 1, x + self.square_width() - 1, y + 1)\r\n\r\n\r\n# Все возможные формы\r\nclass TetrminoShape:\r\n No = 0\r\n Z = 1\r\n S = 2\r\n Line = 5\r\n T = 4\r\n Square = 3\r\n L = 6\r\n MirroredL = 7\r\n\r\n\r\n# генератор фигур\r\nclass Shape:\r\n coordinates_table = (\r\n ((0, 0), (0, 0), (0, 0), (0, 0)),\r\n ((0, -1), (0, 0), (-1, 0), (-1, 1)),\r\n ((0, -1), (0, 0), (1, 0), (1, 1)),\r\n ((0, -1), (0, 0), (0, 1), (0, 2)),\r\n ((-1, 0), (0, 0), (1, 0), (0, 1)),\r\n ((0, 0), (1, 0), (0, 1), (1, 1)),\r\n ((-1, -1), (0, -1), (0, 0), (0, 1)),\r\n ((1, -1), (0, -1), (0, 0), (0, 1))\r\n )\r\n\r\n def __init__(self):\r\n self.coords = [[0, 0] for _ in range(4)]\r\n self.current_shape = TetrminoShape.No\r\n self.set_shape(TetrminoShape.No)\r\n\r\n # функиции ниже имеют говорящие имена, которые описывают их назначения\r\n def shape(self):\r\n return self.current_shape\r\n\r\n def set_shape(self, shape):\r\n table = Shape.coordinates_table[shape]\r\n for i in range(4):\r\n for j in range(2):\r\n self.coords[i][j] = table[i][j]\r\n self.current_shape = shape\r\n\r\n def set_shape_random(self):\r\n self.set_shape(random.randint(1, 7))\r\n\r\n def x(self, index):\r\n return self.coords[index][0]\r\n\r\n def y(self, index):\r\n return self.coords[index][1]\r\n\r\n def set_x(self, index, x):\r\n self.coords[index][0] = x\r\n\r\n def set_y(self, index, y):\r\n self.coords[index][1] = y\r\n\r\n def min_y(self):\r\n y = self.coords[0][1]\r\n for i in range(4):\r\n y = min(y, self.coords[i][1])\r\n return y\r\n\r\n def rotate_left(self):\r\n if self.current_shape == TetrminoShape.Square:\r\n return self\r\n\r\n result = Shape()\r\n result.current_shape = self.current_shape\r\n\r\n # пересобираем фигуру с наклоном\r\n for i in range(4):\r\n result.set_x(i, self.y(i))\r\n result.set_y(i, -self.x(i))\r\n\r\n return result\r\n\r\n def rotate_right(self):\r\n if self.current_shape == TetrminoShape.Square:\r\n return self\r\n\r\n result = Shape()\r\n result.current_shape = self.current_shape\r\n\r\n for i in range(4):\r\n result.set_x(i, -self.y(i))\r\n result.set_y(i, self.x(i))\r\n\r\n return result\r\n\r\n\r\n# окно с выводом стистики игр\r\nclass Statistics(QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.initUI()\r\n self.show()\r\n\r\n def initUI(self):\r\n self.setFixedSize(800, 400)\r\n self.setWindowTitle('Статистика игр')\r\n\r\n self.label1 = QLabel('Статистика игры Крестики - Нолики', self)\r\n self.label1.setGeometry(120, 10, 300, 30)\r\n\r\n tic_tac = PyQt5.QtSql.QSqlDatabase.addDatabase('QSQLITE')\r\n tic_tac.setDatabaseName('tic_tac_toe_statistics.db')\r\n tic_tac.open()\r\n view = QTableView(self)\r\n model = PyQt5.QtSql.QSqlTableModel(self, tic_tac)\r\n model.setTable('statistics')\r\n model.select()\r\n view.setModel(model)\r\n view.move(10, 50)\r\n view.resize(380, 300)\r\n\r\n self.label2 = QLabel('Статистика игры Тетрис', self)\r\n self.label2.setGeometry(520, 10, 300, 30)\r\n\r\n tic_tac = PyQt5.QtSql.QSqlDatabase.addDatabase('QSQLITE')\r\n tic_tac.setDatabaseName('tetris_statistics.db')\r\n tic_tac.open()\r\n view = QTableView(self)\r\n model = PyQt5.QtSql.QSqlTableModel(self, tic_tac)\r\n model.setTable('statistics')\r\n model.select()\r\n view.setModel(model)\r\n view.move(410, 50)\r\n view.resize(380, 300)\r\n\r\n self.back_button = QPushButton('В главное меню', self)\r\n self.back_button.setGeometry(690, 360, 100, 30)\r\n self.back_button.clicked.connect(self.go_to_main_menu)\r\n\r\n def go_to_main_menu(self):\r\n self.menu = MainMenu()\r\n self.close()\r\n\r\n\r\n# создает базу данных статистики игр и проверяет существование уже имеющихся\r\ndef create_data_base():\r\n try:\r\n f = open('tic_tac_toe_statistics.db')\r\n except FileNotFoundError:\r\n con = sqlite3.connect(\"tic_tac_toe_statistics.db\")\r\n cursor = con.cursor()\r\n cursor.execute(\"CREATE TABLE statistics (info text, winner text)\")\r\n try:\r\n f = open('tetris_statistics.db')\r\n except FileNotFoundError:\r\n con = sqlite3.connect(\"tetris_statistics.db\")\r\n cursor = con.cursor()\r\n cursor.execute(\"CREATE TABLE statistics ([number of lines] integer, \"\r\n \"[number of pauses] integer)\")\r\n\r\n\r\nsys._excepthook = sys.excepthook\r\n\r\ndef my_exception_hook(exctype, value, traceback):\r\n # Print the error and traceback\r\n print(exctype, value, traceback)\r\n # Call the normal Exception hook after\r\n sys._excepthook(exctype, value, traceback)\r\n sys.exit(1)\r\n\r\n# Set the exception hook to our wrapping function\r\nsys.excepthook = my_exception_hook\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n create_data_base()\r\n ex = Start()\r\n ex.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"gamebox.py","file_name":"gamebox.py","file_ext":"py","file_size_in_byte":24551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"104995032","text":"from math import*\r\nimport numpy as np\r\nfrom numpy import*\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import*\r\nfrom scipy.integrate import romberg\r\n\r\nu = 0.0\r\nh = 0.05\r\nIn = []\r\nIn.append(0)\r\n\r\nfor i in range (20):\r\n u = u + h\r\n def f(x): return ((u**3)*((x**4)*exp(x)))/(exp(x) - 1)\r\n resultado = romberg (f, 0., 1./u, show = True)\r\n In.append(resultado)\r\n\r\nw = linspace(0.0, 1.0, 19)\r\nplt.plot(w, In)\r\nplt.xlabel(\"el valor de u\")\r\nplt.ylabel(\"el valor de la integral en funcion de u\")\r\nplt.show()\r\n","sub_path":"Tema 3 - Ecuaciones Diferenciales Ordinarias/2013-1 Alumnos/Gerardo, Rangel Paredes/fwtareaexamen2-1/ejercicio 8 exa 2 computacional.py","file_name":"ejercicio 8 exa 2 computacional.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263342863","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom reader import extract\r\nfrom graphic.visualization import Visualization\r\nfrom spaces.local_space import LocalSpace\r\nfrom spaces.world_space import WorldSpace, Camera\r\nfrom PIL import Image\r\nfrom time import time\r\nimport os\r\n\r\n\r\ndef render_with_shaders(world_space, visual_model, img):\r\n buffer = np.array(np.ones((visual_model.height, visual_model.width)) * -np.inf)\r\n for obj in world_space.objs:\r\n model_view = world_space.model_matrix()\r\n if world_space.camera.type_camera == 0:\r\n camera_matrix = world_space.orthographic_matrix()\r\n else:\r\n camera_matrix = world_space.perspective_matrix()\r\n obj.data['old_vertexes'] = np.zeros((len(obj.data['vertexes']), 4))\r\n data_face = {}\r\n for i in range(len(obj.data['edges'])):\r\n print(i)\r\n data_face['new_vertexes'], data_face['new_normals'], data_face['vertexes_before_ndc'] \\\r\n = world_space.vertex_shader(obj, model_view, camera_matrix, i)\r\n visual_model.fill_triangle(obj, data_face, i, buffer, img)\r\n\r\n\r\nif __name__ == '__main__':\r\n size = (512, 512)\r\n path = '../models'\r\n b = os.path.join(path,'floor.obj')\r\n a = os.path.join(path,'face.obj')\r\n c = os.path.join(path,'BRBC.obj')\r\n d = os.path.join(path,'eye_model.obj')\r\n eye_tex = Image.open('../models/eye_tex.tga')\r\n storm_tex = Image.open('../models/BRBC_tex.PNG')\r\n african_tex = Image.open('../models/african_head_diffuse.tga')\r\n floor_tex = Image.open('../models/floor_diffuse.tga')\r\n yoda = 'yoda.obj'\r\n name_file = a\r\n img = np.zeros(shape=(size[0] + 1, size[1] + 1, 3)).astype(np.uint8)\r\n face = LocalSpace(a, size=200, position=[0, 270, 0])\r\n floor = LocalSpace(b, size=200, position=[0, 100, 0])\r\n eye = LocalSpace(d, size=200, position=[0, 300, 0])\r\n stormtrooper = LocalSpace(c, size=200, position=[0, 400, 0],rot_y=90)\r\n\r\n\r\n camera = Camera([300, 300, 300],stormtrooper.data['position'])\r\n cam_front = Camera([0, 300, 500], face.data['position'])\r\n cam_top = Camera([0, 700, 1], face.data['position'])\r\n cam_bot = Camera([0, -700, 1], face.data['position'])\r\n cam_right = Camera([700, 100, 0], face.data['position'])\r\n cam_left = Camera([-700, 100, 0], face.data['position'])\r\n cam_back = Camera([0, 100, -400], face.data['position'])\r\n cam_orth = Camera([-100, 270, 0], face.data['position'], type_camera=0, height_view=(200, -250))\r\n\r\n\r\n objs = [stormtrooper]\r\n colors = [storm_tex]\r\n cam = camera\r\n WS = WorldSpace(objs, cam)\r\n s = time()\r\n # WS.pipeline_for_obj()\r\n vis = Visualization(img, objs, colors, cam.camera_position, type_shadows=0, type_model=1)\r\n render_with_shaders(WS, vis, img)\r\n # vis.show()\r\n print(time() - s)\r\n plt.imshow(np.rot90(img), cmap=\"gray\", interpolation=\"none\")\r\n plt.show()\r\n","sub_path":"ExampleResults/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463711362","text":"import cv2\nimport numpy as np\nfrom PIL import Image\n\nimport libpreviewer\n\n\ndef clip(v, minv, maxv):\n return max(min(v, maxv), minv)\n\n\nclass BaseGenerator(object):\n\n def _setup(self, image_size, fov=50.0, latitude=0.0, longitude=0.0, preview_size=(1000, 750)):\n self.image_size = tuple(map(int, image_size))\n self.image_w2 = image_size[0] / 2\n self.image_h2 = image_size[1] / 2\n\n self._scale = self.image_w2 / np.math.pi\n self._fov = fov\n\n # NB: Force int casting since having floats here would fail with the C++ bindings.\n self.preview_size = tuple(map(int, preview_size))\n self.preview_w2 = preview_size[0] / 2\n self.preview_h2 = preview_size[1] / 2\n\n # rotation corresponding to the preview being generated\n # R = np.eye(3)\n lat_rad = -1.0 * latitude / 180.0 * np.pi\n lng_rad = -1.0 * longitude / 180.0 * np.pi\n Rx = np.array([\n [1,0,0],\n [0, np.math.cos(lat_rad), -np.math.sin(lat_rad)],\n [0, np.math.sin(lat_rad), np.math.cos(lat_rad)]\n ])\n Ry = np.array([\n [np.math.cos(lng_rad), 0, -np.math.sin(lng_rad)],\n [0, 1, 0],\n [np.math.sin(lng_rad), 0, np.math.cos(lng_rad)]\n ])\n R = np.dot(Ry, Rx)\n\n # intrinsic matrix for the projection\n # fov_dimension = max(*self.preview_size)\n fov_dimension = self.preview_size[1]\n fov_rad = float(fov) / 180 * np.pi\n fx = fy = (fov_dimension / 2) / np.math.tan(fov_rad / 2)\n ppx = preview_size[0] / 2\n ppy = preview_size[1] / 2\n K = np.array((fx, 0, ppx, 0, fy, ppy, 0, 0, 1)).reshape((3,3))\n\n # build the `R * Kinv` transform matrix\n Kinv = np.linalg.inv(K)\n self.R_Kinv = np.dot(R, Kinv)\n\n def _input_optimal_size(self):\n \"\"\"NB: The fov determines the vertical fov of the output\"\"\"\n height = float(180) / self._fov * self.preview_size[1]\n height = min(height, self.image_size[1]) # bound the image height\n width = float(self.image_size[0]) / self.image_size[1] * height\n return tuple(map(int, (width, height)))\n\n def _map_backward(self, x, y):\n \"\"\"Map backward the final preview image pixel (x,y) to the \n original equirectangular coords (u,v)\"\"\"\n x_ = self.R_Kinv.item(0) * x + self.R_Kinv.item(1) * y + self.R_Kinv.item(2)\n y_ = self.R_Kinv.item(3) * x + self.R_Kinv.item(4) * y + self.R_Kinv.item(5)\n z_ = self.R_Kinv.item(6) * x + self.R_Kinv.item(7) * y + self.R_Kinv.item(8)\n\n # project on a spherical map\n u = self._scale * np.math.atan2(x_, z_) + self.image_w2\n v = self._scale * ((np.math.pi / 2) - np.math.acos(y_ / np.math.sqrt(x_ * x_ + + y_ * y_ + z_ * z_))) + self.image_h2\n\n return (u,v)\n\n def generate(self):\n raise NotImplementedError\n\n\nclass PreviewNativeProcessor(BaseGenerator):\n\n def __init__(self, image_path, **kwargs):\n self.image = Image.open(image_path)\n self._setup(self.image.size, **kwargs)\n\n def _bilinear_interpolation(self, xy):\n \"\"\"Bilinear implementation\"\"\"\n im = self.image\n x,y = xy\n\n x0 = np.math.floor(x)\n x1 = x0 + 1\n y0 = np.math.floor(y)\n y1 = y0 + 1\n\n x0 = clip(x0, 0, im.size[0] - 1)\n x1 = clip(x1, 0, im.size[0] - 1)\n y0 = clip(y0, 0, im.size[1] - 1)\n y1 = clip(y1, 0, im.size[1] - 1)\n\n Ia = np.array(im.getpixel((x0, y0)))\n Ib = np.array(im.getpixel((x0, y1)))\n Ic = np.array(im.getpixel((x1, y0)))\n Id = np.array(im.getpixel((x1, y1)))\n\n wa = (x1 - x) * (y1 - y)\n wb = (x1 - x) * (y - y0)\n wc = (x - x0) * (y1 - y)\n wd = (x - x0) * (y - y0)\n\n return tuple(np.rint(wa * Ia + wb * Ib + wc * Ic + wd * Id).astype(int))\n\n def generate(self):\n \"\"\"Generate the preview\"\"\"\n im = self.image\n out = Image.new(im.mode, self.preview_size)\n for x in xrange(self.preview_size[0]):\n for y in xrange(self.preview_size[1]):\n uv = self._map_backward(x, y)\n pix = self._bilinear_interpolation(uv)\n out.putpixel((x,y), pix)\n return out\n\n\nclass PreviewOpenCVProcessor(BaseGenerator):\n\n def __init__(self, image_path, **kwargs):\n self.image = cv2.imread(image_path)\n image_size = (self.image.shape[1], self.image.shape[0])\n self._setup(image_size, **kwargs)\n\n def generate(self):\n \"\"\"Generate the preview\"\"\"\n # first we resize the input image\n # so that the remaping step produce a nice image\n optimal_size = self._input_optimal_size()\n if optimal_size != self.image_size:\n resized_image = cv2.resize(self.image, optimal_size)\n else:\n resized_image = self.image\n\n # build the remaping maps\n P = libpreviewer.Projector(\n optimal_size[0],\n optimal_size[1],\n self.preview_size[0],\n self.preview_size[1],\n self.R_Kinv\n )\n P.unproject()\n map_x = P.get_map_x()\n map_y = P.get_map_y()\n\n out = cv2.remap(resized_image, map_x, map_y, cv2.INTER_LANCZOS4)\n return out\n","sub_path":"previewer/processors.py","file_name":"processors.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"301066811","text":"from opcua import Client\n\n\nif __name__ == \"__main__\":\n\n client = Client(\"opc.tcp://localhost:49320\")\n\n try:\n client.connect()\n\n # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects\n root = client.get_root_node()\n print(\"Objects node is: \", root)\n\n # Node objects have methods to read and write node attributes as well as browse or populate address space\n print(\"Children of root are: \", root.get_children())\n\n myvar = root.get_child([\"0:Objects\", \"2:模拟器示例\", \"2:函数\", \"2:Random1\"]).get_value()\n\n print(\"myvar is: \", myvar)\n\n # Stacked myvar access\n print(\"myvar is: \", client.get_node(\"ns=2;s=通道 1.设备 1.标记 1\").get_value())\n\n finally:\n client.disconnect()","sub_path":"opc/opcclient.py","file_name":"opcclient.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"9076390","text":"import logging, time\nfrom odoo import models, fields, api\nfrom datetime import datetime, timedelta\n\n_logger = logging.getLogger(\"WooCommerce\")\n\n\nclass WooCouponDataQueueLineEpt(models.Model):\n _name = \"woo.coupon.data.queue.line.ept\"\n _description = \"WooCommerce Coupon Data Queue LineEpt\"\n _rec_name = \"number\"\n\n coupon_data_queue_id = fields.Many2one(\"woo.coupon.data.queue.ept\", ondelete=\"cascade\")\n instance_id = fields.Many2one(related=\"coupon_data_queue_id.woo_instance_id\", copy=False,\n help=\"Coupon imported from this Woocommerce Instance.\")\n state = fields.Selection([(\"draft\", \"Draft\"), (\"failed\", \"Failed\"),\n (\"cancelled\", \"Cancelled\"), (\"done\", \"Done\")],\n default=\"draft\", copy=False)\n woo_coupon = fields.Char(string=\"Woo Coupon Id\", help=\"Id of imported coupon.\", copy=False)\n coupon_id = fields.Many2one(\"woo.coupons.ept\", copy=False,\n help=\"coupon created in Odoo.\")\n coupon_data = fields.Text(help=\"Data imported from Woocommerce of current coupon.\", copy=False)\n processed_at = fields.Datetime(help=\"Shows Date and Time, When the data is processed.\",\n copy=False)\n common_log_lines_ids = fields.One2many(\"common.log.lines.ept\", \"woo_coupon_data_queue_line_id\",\n help=\"Log lines created against which line.\",\n string=\"Log Message\")\n number = fields.Char(string='Coupon Name')\n\n\n def process_coupon_queue_line(self):\n \"\"\"\n Process the imported coupon data and create the coupon.\n @author: Nilesh Parmar on Date 31 Dec 2019.\n \"\"\"\n common_log_book_obj = self.env[\"common.log.book.ept\"]\n start = time.time()\n #below two line add by Haresh Mori on date 7/1/2020, this is used to set is_process_queue as False.\n self.env.cr.execute(\"\"\"update woo_coupon_data_queue_ept set is_process_queue = False \n where is_process_queue = True\"\"\")\n self._cr.commit()\n queue_id = self.coupon_data_queue_id\n if queue_id.common_log_book_id:\n common_log_book_id = queue_id.common_log_book_id\n else:\n common_log_book_id = common_log_book_obj.create({\"type\":\"import\",\n \"module\":\"woocommerce_ept\",\n \"woo_instance_id\":queue_id.woo_instance_id.id,\n \"active\":True})\n\n coupons = self.env[\"woo.coupons.ept\"].create_or_write_coupon(self, common_log_book_id)\n if not common_log_book_id.log_lines:\n common_log_book_id.sudo().unlink()\n else:\n queue_id.common_log_book_id = common_log_book_id\n end = time.time()\n _logger.info(\"Processed %s Coupons in %s seconds.\" % (str(len(self)), str(end - start)))\n\n @api.model\n def check_woo_coupon_child_cron(self):\n \"\"\"\n Cron method which checks if draft order data is there, than make the child cron active.\n @author: Nilesh Parmar on Date 31 Dec 2019.\n \"\"\"\n # child_cron = self.env.ref(\"woo_commerce_ept.process_woo_coupon_data_queue_child_cron\")\n # if child_cron and not child_cron.active:\n # records = self.search([(\"state\", \"=\", \"draft\")], limit=50).ids\n # if not records:\n # return True\n # child_cron.write({\"active\": True,\n # \"nextcall\": datetime.now() + timedelta(seconds=10),\n # \"numbercall\": 1})\n self.auto_coupon_queue_lines_process()\n return True\n\n def auto_coupon_queue_lines_process(self):\n \"\"\"\n This method used to find a coupon queue line records .\n @author: Nilesh Parmar on Date 31 Dec 2019.\n \"\"\"\n query = \"\"\"SELECT coupon_data_queue_id FROM woo_coupon_data_queue_line_ept WHERE state = \n 'draft' ORDER BY \"create_date\" ASC limit 1;\"\"\"\n self._cr.execute(query)\n coupon_queue_data = self._cr.fetchone()\n coupon_queue_id = self.env[\"woo.coupon.data.queue.ept\"].browse(coupon_queue_data)\n coupon_queue_lines = coupon_queue_id and coupon_queue_id.coupon_data_queue_line_ids.filtered(\n lambda x:x.state == \"draft\")\n coupon_queue_lines and coupon_queue_lines.process_coupon_queue_line()\n return True","sub_path":"woo_commerce_ept/models/coupon_data_queue_line_ept.py","file_name":"coupon_data_queue_line_ept.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81338345","text":"\nimport boto3\n\nclient = boto3.client('ec2')\nec2 = boto3.resource('ec2')\n\ndef add_ingress_rule(group_id, protocol, cidr_ip, from_port, to_port):\n response = client.authorize_security_group_ingress(\n CidrIp=cidr_ip,\n FromPort=from_port,\n GroupId=group_id,\n IpProtocol=protocol,\n ToPort=to_port,\n DryRun=False\n )\n\ndef build_sg(group_name):\n response = client.create_security_group(\n Description='ec2test sg',\n GroupName=group_name\n )\n group_id = response['GroupId']\n return group_id\n \ndef build_sgs(sgs):\n for sg in sgs:\n build_sg(sg['GroupName'])\n\ndef build_nic(group_ids, private_ips, subnet_id):\n response = client.create_network_interface(\n DryRun=False,\n Groups= group_ids,\n PrivateIpAddresses=private_ips,\n InterfaceType='efa',\n SubnetId=subnet_id\n )\n return response\n\ndef build_nics(nic_infos):\n for nic_info in nic_infos:\n build_nic(nic_info)\n\ndef allocate_eip():\n response = client.allocate_address(\n DryRun=False\n )\n return response['AllocationId']\n\ndef associate_eip(allocation_id, nic_ip, private_ip):\n response = client.associate_address(\n AllocationId=allocation_id,\n NetworkInterfaceId=nic_ip,\n PrivateIpAddress=private_ip\n )\n return response['AssociationId']\n\ndef load_param_dict():\n return {}\n\ndef restore_nic():\n param_dict = load_param_dict() \n build_sgs(param_dict['SecurityGroups'])\n build_nics(param_dict['NetworkInterfaces'])\n allocate_eip()\n associate_eip() \n\n\n# print(allocate_eip())\n\ngroup_id = build_sg(\"test_sg\")\nadd_ingress_rule(group_id, \"tcp\", \"0.0.0.0/0\", 80, 80)\nadd_ingress_rule(group_id, \"tcp\", \"0.0.0.0/0\", 443, 443)\n\ngroup_ids = [group_id]\nprivate_ips = [\n {\n 'Primary': True,\n 'PrivateIpAddress': '172.31.32.123'\n },\n {\n 'Primary': False,\n 'PrivateIpAddress': '172.31.32.124'\n },\n] \nsubnet_id = 'subnet-05bae92d'\nnic_info = build_nic(group_ids, private_ips, subnet_id)\n\nallocation_id = \"eipalloc-0310703399962ae7f\"\nnic_id = nic_info[\"NetworkInterface\"][\"NetworkInterfaceId\"] \nprivate_ip = \"172.31.32.123\"\nprint(associate_eip(allocation_id, nic_id, private_ip))\n\n\n","sub_path":"nic.py","file_name":"nic.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"377428351","text":"from .base import BaseAPI\n\nfrom ..exceptions import RecommendAuthenticationError\n\n__all__ = [\n 'AuthenticateAPI',\n]\n\n\nclass AuthenticateAPI(BaseAPI):\n \"\"\"Authenticate API.\"\"\"\n\n def __call__(self, api_key, **kw):\n r\"\"\"\n Return JWT tokens.\n\n :param api_key: api_key (required).\n :param \\**kw: additional keyword arguments are passed to requests.\n\n :raises: :class:`recommendpy.exceptions.RecommendAPIError`.\n\n :return: result of response.json().\n \"\"\"\n return self._client.send(\n 'post', self.get_path(), {'key': api_key}, **kw\n )\n\n def refresh(self, refresh_token=None, update_refresh_token=False, **kw):\n r\"\"\"\n Refresh JWT tokens.\n\n :param refresh_token: refresh token. Defaults to ``None``.\n :param update_refresh_token: updates refresh token.\n Defaults to ``False``.\n :param \\**kw: additional keyword arguments are passed to requests.\n\n :raises: :class:`recommendpy.exceptions.RecommendAPIError`.\n :raises: :class:`recommendpy.exceptions.RecommendAuthenticationError`\n if refresh token is expired.\n\n :return: result of response.json().\n \"\"\"\n refresh_token = refresh_token or self._client.get_token('refresh')\n if not refresh_token or refresh_token.is_expired:\n raise RecommendAuthenticationError('Invalid refresh token.')\n return self._client.send(\n 'post', self.get_path(method='refresh'), {\n 'refresh_token': refresh_token.token,\n 'update_refresh_token': update_refresh_token\n }, **kw\n )\n","sub_path":"src/recommendpy/api/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"651891429","text":"import time\nimport vk\nfrom vk_client import config\n\n\ndef create_api(access_token=None, captcha_handler=None):\n if captcha_handler is not None:\n session_class = type(\"Session\", (vk.Session,), {\n \"get_captcha_key\": captcha_handler\n })\n else:\n session_class = vk.Session\n session = session_class(access_token)\n\n sleep_hook = create_sleep_hook(config.API_RATE_LIMIT)\n session.requests_session.hooks[\"response\"].append(sleep_hook)\n\n return vk.API(session, v=config.API_VERSION)\n\n\ndef create_sleep_hook(seconds):\n def hook(r, *args, **kwargs):\n time.sleep(seconds)\n return hook\n","sub_path":"src/vk_client/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"426523476","text":"# -*- coding:utf-8 -*-\nfrom django.http import HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect\nfrom adapter import get_adapter\nfrom django.shortcuts import render\n\nimport logging\nimport sys\n\nreload(sys)\n\nsys.setdefaultencoding('utf-8')\n\nlogger = logging.getLogger('comments.views')\n\n\ndef _ajax_response(request, response, form=None, data=None):\n try:\n if request.is_ajax():\n if (isinstance(response, HttpResponseRedirect) or isinstance(\n response, HttpResponsePermanentRedirect)):\n redirect_to = response['Location']\n else:\n redirect_to = None\n response = get_adapter(request).ajax_response(\n request,\n response,\n form=form,\n data=data,\n redirect_to=redirect_to)\n return response\n\n except Exception as e:\n logger.error(e)\n\n\nclass AjaxCapableProcessFormViewMixin(object):\n\n def get(self, request, *args, **kwargs):\n try:\n response = super(AjaxCapableProcessFormViewMixin, self).get(\n request, *args, **kwargs)\n form = self.get_form()\n return _ajax_response(\n self.request, response, form=form, data=self._get_ajax_data_if())\n except Exception as e:\n logger.error(e)\n\n\n def post(self, request, *args, **kwargs):\n try:\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n if form.is_valid():\n response = self.form_valid(form)\n else:\n response = self.form_invalid(form)\n return _ajax_response(\n self.request, response, form=form, data=self._get_ajax_data_if())\n except Exception as e:\n logger.error(e)\n\n def get_form(self, form_class=None):\n try:\n form = getattr(self, '_cached_form', None)\n if form is None:\n form = super(AjaxCapableProcessFormViewMixin, self).get_form(\n form_class)\n self._cached_form = form\n return form\n except Exception as e:\n logger.error(e)\n\n def _get_ajax_data_if(self):\n try:\n return self.get_ajax_data() if self.request.is_ajax() else None\n except Exception as e:\n logger.error(e)\n\n def get_ajax_data(self):\n return None\n\n","sub_path":"comments/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"478183064","text":"import json\nimport os\nimport random\nimport socket\nimport subprocess as sp\nimport tempfile\n\nimport click\n\ndef ip(name):\n return sp.check_output([\n 'sudo', 'lxc-info', '--name', name, '-i']).strip().split()[1]\n\n\ndef os_distro():\n return sp.check_output(['lsb_release', '-is']).strip().lower()\n\n\ndef os_release():\n return sp.check_output(['lsb_release', '-cs']).strip()\n\n\ndef ansible(host, module, argument):\n cmd = [\n 'ansible', 'all', '-i', '{},'.format(host), '-m',\n module, '-a', '{}'.format(argument), '--become']\n if host == 'localhost':\n cmd += ['-c', 'local']\n sp.call(cmd)\n\n\ndef ansible_playbook(host, playbook=None, playbook_content=None,\n extra_vars=None, tags=[]):\n if playbook_content:\n with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as f:\n playbook = f.name\n f.write(playbook_content)\n cmd = ['ansible-playbook', '-i', '{},'.format(host),]\n if host == 'localhost':\n cmd += ['-c', 'local']\n if extra_vars:\n cmd += ['--extra-vars', json.dumps(extra_vars)]\n if tags:\n cmd += ['--tags', ','.join(tags)]\n cmd += [playbook]\n sp.call(cmd)\n if playbook_content:\n os.remove(f.name)\n\n\ndef random_unused_ip():\n for iteration in xrange(100, 256):\n ip = '10.0.3.{}'.format(random.randint(100, 256))\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n if sock.connect_ex((ip, 22)):\n return ip\n finally:\n sock.close()\n click.secho('None unsued IP found', fg='red')\n sys.exit(1)\n","sub_path":"lxcw/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"531671384","text":"from os.path import join, dirname\n\nPROJECT_ROOT = dirname(dirname(__file__))\n\n\ndef get_full_path(*path):\n \"\"\"\n Get full path within project directory.\n\n :param path: Path to join with PROJECT_ROOT\n \"\"\"\n return join(PROJECT_ROOT, *path)\n\n\ndef replace_in_file(file, replacements):\n \"\"\"\n Replace strings with the replacements in the given file.\n\n :param file: File to replace strings in\n :param replacements: {string to replace: replacement, }\n \"\"\"\n lines = []\n with open(file) as infile:\n for line in infile:\n for src, target in replacements.items():\n line = line.replace(src, target)\n lines.append(line)\n with open(file, 'w') as outfile:\n for line in lines:\n outfile.write(line)\n","sub_path":"nxstart/utils/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384518872","text":"\nimport pandas as pd\nimport re\n\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom lmf.dbv2 import db_write,db_command,db_query\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException,StaleElementReferenceException\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nimport sys\nimport time\n\nimport json\nfrom zhulong.util.etl import add_info,est_meta,est_html,est_tbs\n\n\n_name_=\"yiwu\"\n\n\n# __conp=[\"postgres\",\"since2015\",\"192.168.3.171\",\"hunan\",\"changsha\"]\n\n\n# url=\"https://ggzy.changsha.gov.cn/spweb/CS/TradeCenter/tradeList.do?Deal_Type=Deal_Type2\"\n# driver=webdriver.Chrome()\n# driver.minimize_window()\n# driver.get(url)\n\n\n\n\n\n\n\ndef f1(driver, num):\n locator = (By.XPATH, \"//ul[@class='ewb-nbd-items']/li[1]/a\")\n val = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text\n try:\n locator = (By.XPATH, \"//span[@id='index']\")\n str = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text\n cnum = re.findall(r'(\\d+)/', str)[0]\n except:\n cnum = 1\n\n url = driver.current_url\n\n if num != int(cnum):\n if (\"list3gc.html\" in url) or (\"list3\" in url) or (\"list3qt\" in url):\n s = \"/%d.html\" % (num) if num > 1 else \"/1.html\"\n url = re.sub(\"/list3gc\\.html\", s, url)\n url = re.sub(\"/list3\\.html\", s, url)\n url = re.sub(\"/list3qt\\.html\", s, url)\n elif num == 1:\n url = re.sub(\"/[0-9]*\\.html\", \"/1.html\", url)\n else:\n s = \"/%d.html\" % (num) if num > 1 else \"/1.html\"\n url = re.sub(\"/[0-9]*\\.html\", s, url)\n # print(cnum)\n driver.get(url)\n try:\n locator = (By.XPATH, \"//ul[@class='ewb-nbd-items']/li[1]/a[string()!='%s']\" % val)\n WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))\n except:\n driver.refresh()\n locator = (By.XPATH, \"//ul[@class='ewb-nbd-items']/li[1]/a[string()!='%s']\" % val)\n WebDriverWait(driver, 3).until(EC.presence_of_element_located(locator))\n\n\n page = driver.page_source\n\n soup = BeautifulSoup(page, 'lxml')\n\n table = soup.find(\"ul\", class_='ewb-nbd-items')\n\n trs = table.find_all(\"li\")\n data = []\n for tr in trs:\n a = tr.find(\"a\")\n try:\n title = a[\"title\"].strip()\n except:\n title = a.text.strip()\n try:\n link = a[\"href\"]\n except:\n continue\n td = tr.find(\"span\", class_=\"ewb-date r\").text.strip()\n\n link = \"http://ywjypt.com\"+link.strip()\n\n tmp = [title, td, link]\n data.append(tmp)\n\n\n df = pd.DataFrame(data)\n df['info'] = None\n return df\n\n\n\n\n\ndef f2(driver):\n # url = driver.current_url\n locator = (By.XPATH, \"//ul[@class='ewb-nbd-items']/li[1]/a\")\n WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))\n try:\n locator = (By.XPATH, \"//span[@id='index']\")\n str = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text\n num = int(re.findall(r'/(\\d+)', str)[0])\n except:\n num = 1\n driver.quit()\n return int(num)\n\n\n\ndef f3(driver, url):\n driver.get(url)\n\n locator = (By.CLASS_NAME, \"ewb-body\")\n\n WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located(locator))\n\n before = len(driver.page_source)\n time.sleep(0.1)\n after = len(driver.page_source)\n i = 0\n while before != after:\n before = len(driver.page_source)\n time.sleep(0.1)\n after = len(driver.page_source)\n i += 1\n if i > 5: break\n\n page = driver.page_source\n\n soup = BeautifulSoup(page, 'lxml')\n\n div = soup.find('div', class_=\"news-article\")\n # div=div.find_all('div',class_='ewb-article')[0]\n\n return div\n\n\ndata = [\n\n [\"gcjs_yuzhaobiao_gg\",\n \"http://ywjypt.com/jyxx/070001/070001015/list3gc.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_zhaobiao_gg\",\n \"http://ywjypt.com/jyxx/070001/070001001/list3gc.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_biangen_gg\",\n \"http://ywjypt.com/jyxx/070001/070001006/list3gc.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"gcjs_liubiao_gg\",\n \"http://ywjypt.com/jyxx/070001/070001007/list3gc.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_zishenjieguo_gg\",\n \"http://ywjypt.com/jyxx/070001/070001009/list3gc.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_zhongbiaohx_gg\",\n \"http://ywjypt.com/jyxx/070001/070001004/list3gc.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n\n [\"gcjs_dingbiao_gg\",\n \"http://ywjypt.com/jyxx/070001/070001008/list3gc.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n\n [\"gcjs_zhongbiao_gg\",\n \"http://ywjypt.com/jyxx/070001/070001005/list3gc.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n\n [\"zfcg_zhaobiao_gg\",\n \"http://ywjypt.com/jyxx/070002/070002001/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_yucai_gg\",\n \"http://ywjypt.com/jyxx/070002/070002004/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_biangen_gg\",\n \"http://ywjypt.com/jyxx/070002/070002003/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_zhongbiao_gg\",\n \"http://ywjypt.com/jyxx/070002/070002002/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_yanshou_gg\",\n \"http://ywjypt.com/jyxx/070002/070002008/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"qsydw_yucai_gg\",\n \"http://ywjypt.com/jyxx/070005/070005003/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_zhaobiao_gg\",\n \"http://ywjypt.com/jyxx/070005/070005001/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_biangen_gg\",\n \"http://ywjypt.com/jyxx/070005/070005002/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_zhongbiaohx_gg\",\n \"http://ywjypt.com/jyxx/070005/070005006/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_dingbiao_gg\",\n \"http://ywjypt.com/jyxx/070005/070005010/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_zhongbiao_gg\",\n \"http://ywjypt.com/jyxx/070005/070005004/list3.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_zhaobiao_gg\",\n \"http://ywjypt.com/jyxx/070008/070008001/list3qt.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_biangen_gg\",\n \"http://ywjypt.com/jyxx/070008/070008002/list3qt.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_zhongbiao_gg\",\n \"http://ywjypt.com/jyxx/070008/070008003/list3qt.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_xiangzhen_yucai_gg\",\n \"http://ywjypt.com/jyxx/070008/070008007/list3qt.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_xiangzhen_zhaobiao_gg\",\n \"http://ywjypt.com/jyxx/070008/070008004/list3qt.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_xiangzhen_biangen_gg\",\n \"http://ywjypt.com/jyxx/070008/070008005/list3qt.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_xiangzhen_zhongbiao_gg\",\n \"http://ywjypt.com/jyxx/070008/070008006/list3qt.html\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n\n]\n\n\ndef work(conp,**args):\n est_meta(conp,data=data,diqu=\"浙江省义乌市\",**args)\n est_html(conp,f=f3,**args)\n\n\nif __name__=='__main__':\n work(conp=[\"postgres\",\"since2015\",\"192.168.3.171\",\"zhejiang\",\"yiwu\"])\n\n # driver=webdriver.Chrome()\n # url=\"http://ywjypt.com/jyxx/070005/070005006/list3.html\"\n # driver.get(url)\n # df = f2(driver)\n # print(df)\n # # driver = webdriver.Chrome()\n # # url = \"http://www.jhztb.gov.cn/jhztb/gcjyysgs/index.htm\"\n # # driver.get(url)\n # for i in range(1, 6):\n # df=f1(driver, i)\n # print(df)\n","sub_path":"zl_spider/zhejiang/yiwu.py","file_name":"yiwu.py","file_ext":"py","file_size_in_byte":8341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"485980001","text":"import random\nimport time as t\nimport os\nimport subprocess\n\nWALLPAPER_DIR = '/home/malcolm/Pictures/wallpapers'\nSWITCH_FILE = \"/tmp/switch\"\n\nSWITCH_TIME = 3600\nREFRESH_TIME = 3\n\ndef switch_wallpaper():\n files = None\n for root, _, fs in os.walk(WALLPAPER_DIR):\n files = [os.path.join(root, f) for f in fs]\n\n wallpaper = random.choice(files)\n subprocess.run(['feh', '--bg-fill', wallpaper], stdout=subprocess.PIPE)\n\ntry:\n time = 0\n while True:\n if time >= SWITCH_TIME:\n time = 0\n switch_wallpaper()\n elif os.path.isfile(SWITCH_FILE):\n os.remove(SWITCH_FILE)\n switch_wallpaper()\n\n time += REFRESH_TIME\n t.sleep(REFRESH_TIME)\nexcept Exception as e:\n with open('/home/malcolm/error', 'w') as f:\n f.write(str(e))\n\n","sub_path":".config/i3/wallpaper.py","file_name":"wallpaper.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83237102","text":"\nimport pygame\nimport sys\n\nfrom pygame.sprite import Group\nfrom pygame.sprite import Sprite\n\n\nclass Settings():\n \"\"\"A class that stores all settings.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game's settings.\"\"\"\n # Screen settings\n self.screen_width = 1200\n self.screen_height = 800\n self.bg_color = (230, 230, 230)\n\n # Raindrop settings\n self.raindrop_speed_factor = 1\n\n\nclass Raindrop(Sprite):\n \"\"\"A class to represent a single raindrop.\"\"\"\n\n def __init__(self, settings, screen):\n \"\"\"Initialize raindrop and set its starting position.\"\"\"\n super().__init__()\n self.settings = settings\n self.screen = screen\n\n # load raindrop image and set its rect attribute.\n self.image = pygame.image.load('images/raindrops.bmp')\n self.rect = self.image.get_rect()\n\n # Start each new raindrop near the top left of the screen.\n self.rect.x = self.rect.width\n self.rect.y = self.rect.height\n\n # Store the raindrop's exact position.\n self.y = float(self.rect.y)\n\n def blitme(self):\n \"\"\"Draw the start at its current location.\"\"\"\n self.screen.blit(self.image, self.rect)\n\n def check_edges(self):\n \"\"\"Return True if raindrop is at edge of screen.\"\"\"\n screen_rect = self.screen.get_rect()\n if self.rect.top >= screen_rect.bottom:\n return True\n elif self.rect.top <= 0:\n return True\n\n def update(self):\n \"\"\"Move the raindrop down.\"\"\"\n self.y += self.settings.raindrop_speed_factor\n self.rect.y = self.y\n\n\ndef check_keydown_events(event, settings, screen):\n \"\"\"Respond to key presses.\"\"\"\n if event.key == pygame.K_q:\n sys.exit()\n\n\ndef check_keyup_events(event):\n \"\"\"Respond to key releases.\"\"\"\n pass\n\n\ndef check_events(settings, screen):\n \"\"\"Respond to key presses and mouse events.\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event, settings, screen)\n elif event.type == pygame.KEYUP:\n check_keyup_events(event)\n\n\ndef update_screen(settings, screen, raindrops):\n \"\"\"Update images on the screen and flip to the new screen.\"\"\"\n # Redraw the screen during each pass through the loop.\n screen.fill(settings.bg_color)\n # Redraw all raindrops.\n raindrops.draw(screen)\n\n # Make the most recently drawn screen visible.\n pygame.display.flip()\n\n\ndef get_number_rows(settings, raindrop_height):\n \"\"\"Determine the number of rows of raindrops that fit on the screen.\"\"\"\n avaiable_space_y = (settings.screen_height - raindrop_height)\n number_rows = int(avaiable_space_y / (2 * raindrop_height))\n return number_rows\n\n\ndef get_number_raindrops_x(settings, raindrop_width):\n \"\"\"Determine the number of raindrops that fit in a row.\"\"\"\n avaiable_space_x = settings.screen_width - raindrop_width\n number_raindrops_x = int(avaiable_space_x / (2 * raindrop_width))\n return number_raindrops_x\n\n\ndef create_raindrop(settings, screen, raindrops, raindrop_number, row_number):\n \"\"\"Create a draindrop and place it in the row.\"\"\"\n raindrop = Raindrop(settings, screen)\n raindrop_width = raindrop.rect.width\n raindrop_height = raindrop.rect.height\n raindrop.x = raindrop_width + 2 * raindrop_width * raindrop_number\n raindrop.rect.x = raindrop.x\n raindrop.rect.y = raindrop_height + 2 * raindrop_height * row_number\n raindrop.y = float(raindrop.rect.y)\n raindrops.add(raindrop)\n\n\ndef create_raindrops(settings, screen, raindrops):\n \"\"\"Create a full group of raindrops.\"\"\"\n # Create a raindrop and find the number of raindrops in a row.\n raindrop = Raindrop(settings, screen)\n number_raindrops_x = get_number_raindrops_x(settings, raindrop.rect.width)\n number_rows = get_number_rows(settings, raindrop.rect.height)\n\n # Create group of raindrops.\n for row_number in range(number_rows):\n for raindrop_number in range(number_raindrops_x):\n create_raindrop(settings, screen, raindrops, raindrop_number, row_number)\n\n\ndef check_raindrops_edges(raindrops):\n \"\"\"Respond appropriately if raindop have reached an edge.\"\"\"\n # Get rid of raindrops that have disappeared.\n for raindrop in raindrops.copy():\n if raindrop.check_edges():\n raindrops.remove(raindrop)\n\n\ndef update_raindrops(raindrops):\n \"\"\"Update the position of all raindrops.\"\"\"\n check_raindrops_edges(raindrops)\n raindrops.update()\n\n\ndef run():\n \"\"\"Initialize pygame, settings and screen objects.\"\"\"\n pygame.init()\n settings = Settings()\n screen = pygame.display.set_mode(\n (settings.screen_width, settings.screen_height))\n pygame.display.set_caption('Raindrops')\n\n # Make a group to store raindrops.\n raindrops = Group()\n\n # Create group of raindrops.\n create_raindrops(settings, screen, raindrops)\n\n # Main loop\n while True:\n check_events(settings, screen)\n update_raindrops(raindrops)\n update_screen(settings, screen, raindrops)\n\n\nrun()\n","sub_path":"crash_course/ch13/exec/raindrops.py","file_name":"raindrops.py","file_ext":"py","file_size_in_byte":5165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"488012340","text":"import math\nh= float(input(\"請輸入身高 : \"))\nw= float(input(\"請輸入體重 : \"))\nbmi = w/math.pow((h/100),2)\nprint(\"BMI 計算結果 : %.2f\" % bmi)\nif bmi>23:\n print(\"Too Fat\")\nelif bmi<=18:\n print(\"Too Thin\")\nelse:\n print(\"Regular\")\n","sub_path":"day03/BMI 輸入2.py","file_name":"BMI 輸入2.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"209567745","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# stdlib imports\nimport json\n\n\nclass Source:\n \"\"\"\n A conversion class used to create, parse, and validate source data as part\n of processing data.\n \"\"\"\n\n # JSON Keys\n AGENCYID_KEY = \"AgencyID\" # required\n AUTHOR_KEY = \"Author\" # required\n TYPE_KEY = \"Type\" # required\n\n def __init__(self, newAgencyID=None, newAuthor=None, newType=None):\n \"\"\"Intialize source object, constructs empty object if all arguments are None\n\n newAgencyID: a required String containing the agency identifier\n newAuthor: a required String containing the author\n newType: a required String containing the type\n \"\"\"\n\n if newAgencyID is not None:\n self.agencyID = newAgencyID\n\n if newAuthor is not None:\n self.author = newAuthor\n\n if newType is not None:\n self.type = newType\n\n def fromJSONString(self, JSONString):\n \"\"\"Populate object from JSON formatted string\n\n JSONString: a required String containing the JSON formatted text\n \"\"\"\n JSONObject = json.loads(JSONString)\n self.fromDict(JSONObject)\n\n def fromDict(self, aDict):\n \"\"\"Populates object from a dictionary\n\n aDict: a required dictionary\n \"\"\"\n try:\n self.agencyID = aDict[self.AGENCYID_KEY]\n self.author = aDict[self.AUTHOR_KEY]\n self.type = aDict[self.TYPE_KEY]\n\n except (ValueError, KeyError, TypeError) as e:\n print(\"Dictionary format error, missing required keys: %s\" % e)\n\n def toJSONString(self):\n \"\"\"Converts object to JSON formatted string\n\n Returns: JSON formatted message as a String\n \"\"\"\n JSONObject = self.toDict()\n\n return json.dumps(JSONObject, ensure_ascii=False)\n\n def toDict(self):\n \"\"\"Converts the object to a dictionary\n\n Returns: the dictionary\n \"\"\"\n aDict = {}\n\n try:\n aDict[self.AGENCYID_KEY] = self.agencyID\n aDict[self.AUTHOR_KEY] = self.author\n aDict[self.TYPE_KEY] = self.type\n\n except (NameError, AttributeError) as e:\n print(\"Missing required data error: %s\" % e)\n\n return aDict\n\n def isValid(self):\n \"\"\"Checks to see if object is valid\n\n Returns: true if object is valid, false otherwise\n \"\"\"\n errorList = self.getErrors()\n\n return not errorList\n\n def getErrors(self):\n \"\"\"Gets a list of object validation errors\n\n Returns: a list of Strings containing the validation error messages\n \"\"\"\n errorList = []\n\n # AgencyID\n try:\n if self.agencyID == \"\":\n errorList.append(\"Empty AgencyID in Source Class\")\n\n except (NameError, AttributeError):\n errorList.append(\"No AgencyID in Source Class\")\n\n # Author\n try:\n if self.author == \"\":\n errorList.append(\"Empty Author in Source Class\")\n\n except (NameError, AttributeError):\n errorList.append(\"No Author in Source Class\")\n\n # Type\n try:\n match = False\n\n if self.type == \"\":\n errorList.append(\"Empty Type in Source Class\")\n\n elif self.type == \"Unknown\":\n match = True\n\n elif self.type == \"LocalHuman\":\n match = True\n\n elif self.type == \"LocalAutomatic\":\n match = True\n\n elif self.type == \"ContributedHuman\":\n match = True\n\n elif self.type == \"ContributedAutomatic\":\n match = True\n\n else:\n match = False\n\n if not match:\n errorList.append(\"Invalid Type in Source Class\")\n\n except (NameError, AttributeError):\n errorList.append(\"No Type in Source Class\")\n\n return errorList\n\n def isEmpty(self):\n \"\"\"Checks to see if object is empty\n\n Returns: true if object is empty, false otherwise\n \"\"\"\n if hasattr(self, \"agencyID\"):\n return False\n\n if hasattr(self, \"author\"):\n return False\n\n if hasattr(self, \"type\"):\n return False\n\n return True\n","sub_path":"python/processingformats/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"345624770","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/7/22 18:17\n# @Author : qidl\n# @Software: PyCharm\n# @Description : 封装Redis类\n\nimport pickle\nimport redis\n\nfrom flask import current_app as app\n\nclass Redis(object):\n\n @staticmethod\n def _getRedis():\n host = app.config['REDIS_HOST']\n port = app.config['REDIS_PORT']\n db = app.config['REDIS_DB']\n passwd = app.config['REDIS_PW']\n r = redis.StrictRedis(host= host, port= port, db= db, password= passwd)\n\n return r\n\n @classmethod\n def write(self, key, value, expire=None):\n if expire:\n expire_in_seconds = expire\n else:\n expire_in_seconds = app.config['REDIS_EXPIRE']\n r = self._getRedis()\n r.set(key, value, ex=expire_in_seconds)\n\n @classmethod\n def write_dict(self, key, value, expire=None):\n if expire:\n expire_in_seconds = expire\n else:\n expire_in_seconds = app.config['REDIS_EXPIRE']\n r = self._getRedis()\n r.set(pickle.dumps(key), pickle.dumps(value), ex=expire_in_seconds)\n\n @classmethod\n def read_dict(self, key):\n r = self._getRedis()\n data = r.get(pickle.dumps(key))\n if data is None:\n return None\n return pickle.loads(data)\n\n @classmethod\n def read(self, key):\n r = self._getRedis()\n value = r.get(key)\n\n return value.decode('utf-8') if value else value\n\n #写入hash表\n @classmethod\n def hset(self, name, key, value):\n r = self._getRedis()\n r.hset(name, key, value)\n\n #读取指定hash表的所有给定字段的值\n @classmethod\n def hmset(self, key, *value):\n r = self._getRedis()\n value = r.hmset(key, *value)\n return value\n\n #读取指定hash表的键值\n @classmethod\n def hget(self, name, key):\n r = self._getRedis()\n value = r.hget(name, key)\n return value.decode('utf-8') if value else value\n\n #获取指定hash表所有的值\n @classmethod\n def hgetall(self, name):\n r = self._getRedis()\n return r.hgetall(name)\n\n #删除一个或者多个\n @classmethod\n def delete(self, *names):\n r = self._getRedis()\n r.delete(*names)\n\n #删除指定hash表的键值\n @classmethod\n def hdel(self, name, key):\n r = self._getRedis()\n r.hdel(name, key)\n\n @classmethod\n def expire(self, name, expire=None):\n if expire:\n expire_in_seconds = expire\n else:\n expire_in_seconds = app.config['REDIS_EXPIRE']\n r = self._getRedis()\n r.expire(name, expire_in_seconds)\n\n","sub_path":"RiskMonitor/utils/redisUtils.py","file_name":"redisUtils.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"416992938","text":"import unittest\nimport os\nfrom os.path import exists, join\nimport numpy as np\nfrom test_helper import TESTDIR, TESTDATA, TMPDATA\nimport datetime\nfrom copy import copy\n\nfrom karta.vector import shp, read_shapefile\nfrom karta.vector.geometry import Point, Multipoint, Line, Polygon\nfrom karta.crs import LonLatWGS84\n\nclass TestShapefile(unittest.TestCase):\n\n def setUp(self):\n self.points = [Point((1, 1), data={\"species\": \"T. officianale\"}, crs=LonLatWGS84),\n Point((3, 1), data={\"species\": \"C. tectorum\"}, crs=LonLatWGS84),\n Point((4, 3), data={\"species\": \"M. alba\"}, crs=LonLatWGS84),\n Point((2, 2), data={\"species\": \"V. cracca\"}, crs=LonLatWGS84)]\n\n self.multipoint = Multipoint([(1,1), (3,1), (4,3), (2,2)],\n data={\"species\": [\"T. officianale\", \"C. tectorum\",\n \"M. alba\", \"V. cracca\"]},\n crs=LonLatWGS84)\n\n self.line = Line([(1.0,5.0),(5.0,5.0),(5.0,1.0),(3.0,3.0),(1.0,1.0)],\n properties={\"geom_id\": 27, \"name\": \"test line\"},\n crs=LonLatWGS84)\n\n self.polygon = Polygon([(1.0,5.0),(5.0,5.0),(5.0,1.0),(3.0,3.0),(1.0,1.0)],\n crs=LonLatWGS84)\n\n self.points3 = [Point((1, 1, 0), crs=LonLatWGS84),\n Point((3, 1, 3), crs=LonLatWGS84),\n Point((4, 3, 2), crs=LonLatWGS84),\n Point((2, 2, -1), crs=LonLatWGS84)]\n\n self.line3 = Line([(1,5,2),(5,5,-1),(5,1,3),(3,3,1),(1,1,0)], crs=LonLatWGS84)\n\n self.polygon3 = Polygon([(1,5,2),(5,5,-1),(5,1,3),(3,3,1),(1,1,0)], crs=LonLatWGS84)\n\n testfiles = [\"points.shp\", \"line.shp\", \"polygon.shp\"]\n if any(not exists(join(TMPDATA, \"shapefiles/\", fnm)) for fnm in testfiles):\n self.saveTestData()\n return\n\n def saveTestData(self):\n testfiles = [(self.multipoint, \"points\"),\n (self.line, \"line\"),\n (self.polygon, \"polygon\")]\n os.makedirs(os.path.join(TMPDATA, \"shapefiles\"))\n for (geom, fnm) in testfiles:\n geom.to_shapefile(os.path.join(TMPDATA, \"shapefiles\", fnm))\n return\n\n def assertGeomEqual(self, this, that):\n self.assertTrue(np.all(this.get_vertices() == that.get_vertices()))\n try:\n self.assertEqual(this.crs.get_proj4(), that.crs.get_proj4())\n except AttributeError:\n print(\"warning: crs equality not established\")\n return\n\n def test_writepoint(self):\n point = self.points[0]\n point.to_shapefile(os.path.join(TESTDIR, \"data/point\"))\n for fnm in (\"point.shx\", \"point.shx\", \"point.dbf\", \"point.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_writepoints(self):\n points = self.points\n shp.write_shapefile(os.path.join(TESTDIR, \"data/points.shp\"), *points)\n for fnm in (\"points.shx\", \"points.shx\", \"points.dbf\", \"points.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_writemultipoint(self):\n mp = Multipoint(self.points)\n mp.to_shapefile(os.path.join(TESTDIR, \"data/multipoint\"))\n for fnm in (\"multipoint.shx\", \"multipoint.shx\", \"multipoint.dbf\", \"multipoint.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_writeline(self):\n self.line.to_shapefile(os.path.join(TESTDIR, \"data/line\"))\n for fnm in (\"line.shx\", \"line.shx\", \"line.dbf\", \"line.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_writepoly(self):\n self.polygon.to_shapefile(os.path.join(TESTDIR, \"data/polygon\"))\n for fnm in (\"polygon.shx\", \"polygon.shx\", \"polygon.dbf\", \"polygon.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_writepoints3(self):\n mp = Multipoint(self.points3)\n mp.to_shapefile(os.path.join(TESTDIR, \"data/multipointz\"))\n for fnm in (\"multipointz.shx\", \"multipointz.shx\", \"multipointz.dbf\", \"multipointz.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_writeline3(self):\n self.line3.to_shapefile(os.path.join(TESTDIR, \"data/linez\"))\n for fnm in (\"linez.shx\", \"linez.shx\", \"linez.dbf\", \"linez.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_writepoly3(self):\n self.polygon3.to_shapefile(os.path.join(TESTDIR, \"data/polygonz\"))\n for fnm in (\"polygonz.shx\", \"polygonz.shx\", \"polygonz.dbf\", \"polygonz.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_write_collection_multipoint(self):\n mp = Multipoint([p.vertex for p in self.points])\n mp0 = copy(mp)\n mp1 = copy(mp.shift((4, 2)))\n mp2 = copy(mp.shift((-2, 3)))\n shp.write_shapefile(os.path.join(TESTDIR, \"data/mp_collection.shp\"),\n mp0, mp1, mp2)\n for fnm in (\"mp_collection.shx\", \"mp_collection.shx\", \"mp_collection.dbf\", \"mp_collection.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_write_collection_lines(self):\n line0 = copy(self.line)\n line1 = copy(self.line.shift((4, 2)))\n line2 = copy(self.line.shift((-2, 3)))\n shp.write_shapefile(os.path.join(TESTDIR, \"data/line_collection.shp\"),\n line0, line1, line2)\n for fnm in (\"line_collection.shx\", \"line_collection.shx\", \"line_collection.dbf\", \"line_collection.prj\"):\n self.assertTrue(os.path.isfile(os.path.join(TESTDIR, \"data\", fnm)))\n return\n\n def test_read_points(self):\n points = read_shapefile(os.path.join(TESTDATA, \"shp_input\", \"points\"))\n self.assertEqual(len(points), 4)\n pt = points[0]\n self.assertTrue(\"+proj=lonlat\" in pt.crs.get_proj4())\n self.assertTrue(\"+a=6378137.0\" in pt.crs.get_proj4())\n self.assertTrue(\"+f=0.00335281\" in pt.crs.get_proj4())\n mp = Multipoint(points)\n self.assertEqual(mp.d[\"species\"], ['T. officianale', 'C. tectorum', 'M. alba', 'V. cracca'])\n self.assertEqual(mp.d[\"ID\"], ['0', '1', '2', '3'])\n self.assertEqual(mp.coordinates, ((1.0, 3.0, 4.0, 2.0), (1.0, 1.0, 3.0, 2.0)))\n\n def test_read_line(self):\n line = read_shapefile(os.path.join(TESTDATA, \"shp_input\", \"line\"))[0]\n self.assertTrue(\"+proj=lonlat\" in line.crs.get_proj4())\n self.assertTrue(\"+a=6378137.0\" in line.crs.get_proj4())\n self.assertTrue(\"+f=0.00335281\" in line.crs.get_proj4())\n self.assertEqual(line.coordinates, ((1.0, 5.0, 5.0, 3.0, 1.0), (5.0, 5.0, 1.0, 3.0, 1.0)))\n return\n\n def test_read_polygon(self):\n polygon = read_shapefile(os.path.join(TESTDATA, \"shp_input\", \"polygon\"))[0]\n self.assertTrue(\"+proj=lonlat\" in polygon.crs.get_proj4())\n self.assertTrue(\"+a=6378137.0\" in polygon.crs.get_proj4())\n self.assertTrue(\"+f=0.00335281\" in polygon.crs.get_proj4())\n self.assertEqual(polygon.coordinates, ((1.0, 5.0, 5.0, 3.0, 1.0), (5.0, 5.0, 1.0, 3.0, 1.0)))\n return\n\n def test_read_points_newp(self):\n # Read a multipoint with a projected cooridnate system\n newp = read_shapefile(os.path.join(TESTDATA, \"shp_input\", \n \"newp_nsidc_north\"))\n\n proj4 = ('+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 '\n '+y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs')\n\n for part in proj4.split():\n self.assertTrue(part[:8] in newp[0].crs.get_proj4())\n\n coords = list(zip(*[pt.vertex[:2] for pt in newp]))\n self.assertEqual(coords, [(521236.8297444395, 521236.8297444395,\n 521236.8297444395, 547490.4452879033,\n 547490.4452879033, 547490.4452879033,\n 587584.1578033275, 587584.1578033275,\n 587584.1578033275, 571828.4918982167,\n 571828.4918982167),\n (-888853.1384770898, -888853.1384770898,\n -888853.1384770898, -902049.3617542256,\n -902049.3617542256, -902049.3617542256,\n -871214.0673764511, -871214.0673764511,\n -871214.0673764511, -850080.914674058,\n -850080.914674058)])\n\n meterno = [pt.properties[\"meterno\"] for pt in newp]\n self.assertEqual(meterno, ['IMS1/1', 'IMS2/1', '5952/2', 'IMS4/1',\n '5953/2', '1963/13', 'IMS5/1', '5213/A',\n '2121/13', 'IMS3/1', '3613/2'])\n\n depth = [pt.properties[\"depth_m\"] for pt in newp]\n self.assertEqual(depth, ['73', '143', '247', '86', '147', '250', '74', \n '142', '235', '150', '248'])\n return\n\nclass ShapefileAttributeTests(unittest.TestCase):\n\n def test_infer_ogr_fieldtype(self):\n self.assertEqual(shp.ogr_get_fieldtype(1), (0, 32))\n self.assertEqual(shp.ogr_get_fieldtype([1, 2]), (1, 1000))\n\n self.assertEqual(shp.ogr_get_fieldtype(1.0), (2, 32))\n self.assertEqual(shp.ogr_get_fieldtype([1.0, 1.5]), (3, 1000))\n\n # everything should be interpretted as WideString\n self.assertEqual(shp.ogr_get_fieldtype(\"hello\"), (4, 180))\n self.assertEqual(shp.ogr_get_fieldtype([\"list\",\"of\",\"strings\"]),(5, 1000))\n\n # doesn't work on Python 2\n #self.assertEqual(shp.ogr_get_fieldtype(b'0b110001'), 8)\n\n # dates\n self.assertEqual(shp.ogr_get_fieldtype(datetime.date(2013, 11, 17)), (9, 32))\n self.assertEqual(shp.ogr_get_fieldtype(datetime.time(8, 30, 0)), (10, 32))\n self.assertEqual(shp.ogr_get_fieldtype(datetime.datetime(2013, 11, 17, 8, 30, 0)), (11, 64))\n return\n\n\nclass ShapelibTestSuite(unittest.TestCase):\n \"\"\" Open and verify the shapefiles provided with the shapelib testsuite. \"\"\"\n\n def setUp(self):\n self.dirname = os.path.join(TESTDATA, \"shapefile\", \"shapelib\")\n\n def test_(self):\n res = read_shapefile(os.path.join(self.dirname, \"test.shp\"))\n\n def test_0(self):\n res = read_shapefile(os.path.join(self.dirname, \"test0.shp\"))\n\n def test_1(self):\n res = read_shapefile(os.path.join(self.dirname, \"test1.shp\"))\n\n def test_2(self):\n res = read_shapefile(os.path.join(self.dirname, \"test2.shp\"))\n\n def test_3(self):\n res = read_shapefile(os.path.join(self.dirname, \"test3.shp\"))\n\n def test_4(self):\n res = read_shapefile(os.path.join(self.dirname, \"test4.shp\"))\n\n def test_5(self):\n res = read_shapefile(os.path.join(self.dirname, \"test5.shp\"))\n\n def test_6(self):\n res = read_shapefile(os.path.join(self.dirname, \"test6.shp\"))\n\n def test_7(self):\n res = read_shapefile(os.path.join(self.dirname, \"test7.shp\"))\n\n def test_8(self):\n res = read_shapefile(os.path.join(self.dirname, \"test8.shp\"))\n\n def test_9(self):\n res = read_shapefile(os.path.join(self.dirname, \"test9.shp\"))\n\n def test_10(self):\n res = read_shapefile(os.path.join(self.dirname, \"test10.shp\"))\n\n def test_11(self):\n res = read_shapefile(os.path.join(self.dirname, \"test11.shp\"))\n\n def test_12(self):\n res = read_shapefile(os.path.join(self.dirname, \"test12.shp\"))\n\n def test_13(self):\n res = read_shapefile(os.path.join(self.dirname, \"test13.shp\"))\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/shapefile_tests.py","file_name":"shapefile_tests.py","file_ext":"py","file_size_in_byte":12041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"207771959","text":"\"\"\"start_kernel is a convenience script for starting a kernel thread in python\n\n\"\"\"\n\nimport sys, os, argparse\n\nsys.stdout.flush()\n\ntrue_file = os.path.abspath(__file__)\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(true_file)))\n\nfrom PJLink import *\n\n### I should do a lot more argparsing... but I don't\n\nparser = argparse.ArgumentParser(description='Start a PJLink kernel.')\nparser.add_argument('--blocking', dest='block', type=bool, nargs='?', default=False,\n help='whether the kernel should block or not')\nparser.add_argument('--debug', dest='debug', type=int, nargs='?', default=0,\n help='debug level for underlying PJLink lib')\nparser.add_argument('-linkname', dest='name', type=str, nargs='?',\n help='name for the link')\nparser.add_argument('-linkmode', dest='mode', type=str, nargs='?',\n help='mode for the link')\nparser.add_argument('-linkprotocol', dest='protocol', type=str, nargs='?',\n help='protocol for the link')\n\nparser = parser.parse_args()\n\nblocking = parser.block\ndebug = parser.debug\nname = parser.name\nmode = parser.mode\nprotocol = parser.protocol\n\nopts = { 'linkname' : parser.name, 'linkmode' : parser.mode, 'linkprotocol' : parser.protocol }\nopts = [ ('-'+k, v) for k, v in opts.items() if v is not None]\ninit = [ None ] * (2 * len(opts))\nfor i, t in enumerate(opts):\n init[2*i] = t[0]\n init[2*i+1] = t[1]\n\nreader = create_reader_link(init=init, debug_level=debug)\n# print(reader.link.drain())\n\n# stdout = open(os.path.expanduser(\"~/Desktop/stdout.txt\"), \"w+\")\n# stderr = open(os.path.expanduser(\"~/Desktop/stderr.txt\"), \"w+\")\n# sys.stdout = stdout\n# sys.stderr = stderr\n\nif blocking:\n# reader.run()\n# else:\n import code\n code.interact(banner = \"\", local={\"Kernel\":reader.link, \"KernelReader\":reader})\n","sub_path":"PJLink/start_kernel.py","file_name":"start_kernel.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"74735860","text":"# Lets import random for chosing randomly between rock , paper or Scissors..!\nimport random\n\n# Also , lets add 2 functions\n# 1 for getting user and computers choices and\n# 2 for evaluating who won between each of them.\n\ndef rock_paper_get_choices():\n \"\"\"\n This function gets the user's inputs and choses randomly for computers choices..\n \"\"\"\n user_inp=input(\"'r':- Rock\\n'p':- Paper\\n's':- Scissors\\nWhat\\'s your choice\\n\")\n comp_choice=random.choice(['r','p','s'])\n\n print(f\"You chose {user_inp} and computer chose {comp_choice}..!!\")\n\n # let's handle a scenario where both have same choice.\n if user_inp==comp_choice:\n return \"It's a Tie..!!\"\n \n if rock_paper_who_wins(user_inp,comp_choice):\n return \"You Won..!!\"\n\n return \"You lost to Computer..!\"\n\n\ndef rock_paper_who_wins(user,comp):\n \"\"\"\n This function evaluates who won the actual game and returns true only if user won.\n i/p:- is choices from user and computer.\n \"\"\"\n # Rock paper scissor logic is as below\n # r>s , s>p and p>r\n if (user=='r' and comp=='s') or (user=='s' and comp=='p') or (user=='p' and comp=='r'):\n return True\n\nresult=rock_paper_get_choices()\nprint(result)","sub_path":"4_RockPaperScissors.py","file_name":"4_RockPaperScissors.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372242283","text":"#!/usr/bin/python3\n\"\"\"\nStarts a flask application.\n\"\"\"\n\n\nfrom flask import Flask, escape, render_template\nfrom models import storage, State\nfrom collections import OrderedDict\n\n\napp = Flask(__name__)\n\n\n@app.teardown_appcontext\ndef remove_session(self):\n \"\"\"\n Remove the current SQLAlchemy Session after each request.\n \"\"\"\n storage.close()\n\n\n@app.route('/states_list', strict_slashes=False)\ndef get_states_list():\n \"\"\"\n Return states list HTML template.\n \"\"\"\n states_list = [v for k, v in (storage.all(State)).items()]\n r = render_template(\n '7-states_list.html',\n states_list=states_list\n )\n return r\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"web_flask/7-states_list.py","file_name":"7-states_list.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"638505020","text":"\"\"\"\nInductive Representation Learning on Large Graphs\nPaper: http://papers.nips.cc/paper/6703-inductive-representation-learning-on-large-graphs.pdf\nCode: https://github.com/williamleif/graphsage-simple\nSimple reference implementation of GraphSAGE.\n\"\"\"\nimport argparse\nimport time\nimport numpy as np\nimport networkx as nx\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport load_dgl_data\nfrom torch.autograd import Variable\nfrom dgl import DGLGraph\nfrom dgl.nn.pytorch.conv import SAGEConv\n\n\nclass GraphSAGE(nn.Module):\n def __init__(self,\n in_feats,\n n_hidden,\n n_classes,\n n_layers,\n activation,\n dropout,\n aggregator_type):\n super(GraphSAGE, self).__init__()\n self.layers = nn.ModuleList()\n\n # input layer\n self.layers.append(SAGEConv(in_feats, n_hidden, aggregator_type, feat_drop=dropout, activation=activation))\n # hidden layers\n for i in range(n_layers - 1):\n self.layers.append(SAGEConv(n_hidden, n_hidden, aggregator_type, feat_drop=dropout, activation=activation))\n # output layer\n self.layers.append(SAGEConv(n_hidden, n_classes, aggregator_type, feat_drop=dropout, activation=None)) # activation None\n\n def forward(self, g, features):\n h = features\n for layer in self.layers:\n h = layer(g, h)\n return h\n\nclass GraphSAGEFlatten(nn.Module):\n def __init__(self, in_feats, n_hidden, n_classes, n_layers, activation, dropout, aggregator_type):\n super(GraphSAGEFlatten, self).__init__()\n self.graphsage = GraphSAGE(in_feats, n_hidden, n_classes, n_layers,\n activation, dropout, aggregator_type)\n self.fc = nn.Linear(116*116, 128)\n self.fc2 = nn.Linear(128, 64)\n self.fc3 = nn.Linear(64, 3)\n\n def forward(self, g, features):\n h = self.graphsage(g, features)\n h = torch.reshape(h, [116*116])\n h = self.fc(h)\n h = self.fc2(h)\n h = self.fc3(h)\n h = torch.softmax(h, dim=-1)\n return h\n\ndef evaluate(model, features, labels, mask):\n model.eval()\n with torch.no_grad():\n logits = model(features)\n logits = logits[mask]\n labels = labels[mask]\n _, indices = torch.max(logits, dim=1)\n correct = torch.sum(indices == labels)\n return correct.item() * 1.0 / len(labels)\n\ndef main(args):\n # load and preprocess dataset\n X, y, onehot = load_dgl_data.LoadDGLFromBinary()\n\n # create GraphSAGE model\n model = GraphSAGEFlatten(116,\n args.n_hidden,\n 116,\n args.n_layers,\n F.relu,\n args.dropout,\n args.aggregator_type\n )\n\n loss_fcn = torch.nn.CrossEntropyLoss()\n\n # use optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n\n idx_train = range(0, int(len(X) * 0.7))\n idx_test = range(int(len(X) * 0.7), len(X))\n\n # initialize graph\n dur = []\n for epoch in range(args.n_epochs):\n model.train()\n correct = 0\n loss = None\n for i in idx_train:\n features = Variable(X[i].ndata['h'])\n # Train it\n logits = model(X[i], features)\n #print(logits, onehot[i])\n loss = loss_fcn(torch.stack([logits]), y[i])\n if torch.argmax(logits) == y[i]:\n correct = correct + 1\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n acc = 1.0 * correct / len(idx_train)\n print(\"Epoch {:05d} | Loss {:.4f} | Accuracy {:.4f} | \"\n \"\".format(epoch, loss.item(), acc))\n\n model.training = False\n correct = 0\n for i in idx_test:\n features = Variable(X[i].ndata['h'])\n # Test it\n logits = model(X[i], features)\n if torch.argmax(logits) == y[i]:\n correct = correct + 1\n acc = 1.0 * correct / len(idx_test)\n\n print(\"Test Accuracy {:.4f}\".format(acc))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='GraphSAGE')\n #register_data_args(parser)\n parser.add_argument(\"--dropout\", type=float, default=0.5,\n help=\"dropout probability\")\n parser.add_argument(\"--gpu\", type=int, default=-1,\n help=\"gpu\")\n parser.add_argument(\"--lr\", type=float, default=1e-3,\n help=\"learning rate\")\n parser.add_argument(\"--n-epochs\", type=int, default=10,\n help=\"number of training epochs\")\n parser.add_argument(\"--n-hidden\", type=int, default=16,\n help=\"number of hidden gcn units\")\n parser.add_argument(\"--n-layers\", type=int, default=1,\n help=\"number of hidden gcn layers\")\n parser.add_argument(\"--weight-decay\", type=float, default=5e-4,\n help=\"Weight for L2 loss\")\n parser.add_argument(\"--aggregator-type\", type=str, default=\"gcn\",\n help=\"Aggregator type: mean/gcn/pool/lstm\")\n args = parser.parse_args()\n print(args)\n\n main(args)","sub_path":"graphsage3.py","file_name":"graphsage3.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"396310577","text":"\nclass Node(object):\n def __init__(self, data, next = None):\n self.data = data\n self.next = next\n\n def get_data(self):\n return self.data\n\n def get_next(self):\n return self.next\n\n def set_next(self, next):\n self.next = next\n\n\nclass LinkedList(object):\n\n def __init__(self, head = None):\n self.head = head\n\n def add(self, data):\n node = Node(data)\n node.next = self.head\n self.head = node\n\n def size(self):\n count = 0\n if not self.head:\n return count\n node = self.head\n while node:\n count = count + 1\n node = node.next\n return count\n\n def search(self, data):\n if not self.head:\n return False\n node = self.head\n\n while node:\n if node.data == data:\n return True\n node = node.next\n\n return False\n\n def delete(self, data):\n if not self.head:\n return False\n\n prev_node = None\n node = self.head\n while node:\n if node.data == data:\n if prev_node:\n prev_node.next = node.next\n else:\n self.head = node.next\n return True\n else:\n prev_node = node\n node = node.next\n return False\n\n\n\n","sub_path":"linked_lists/linked_list_old.py","file_name":"linked_list_old.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325532206","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import login\nfrom ticket.models import Tickets, Employee, Departments, Comments\nfrom ticket.forms import FormTicket, FormComment\nfrom django.db.models import Q\n# Create your views here.\n\ndef all_tickets( request ):\n\treturn render( request, \"ticket/list.html\", {})\n\ndef welcome_view(request):\n\treturn render( request, \"ticket/welcome.html\")\n\n\ndef login_view( request ):\n\tif request.method == 'POST':\n\t\t#return render( request, 'hi', {})\n\t\tform = AuthenticationForm(data=request.POST)\n\t\tif form.is_valid():\n\t\t\t#login the user\n\t\t\tuser = form.get_user()\n\t\t\tlogin(request, user)\n\t\t\treturn redirect('ticket:all_tickets')\n\telse:\n\t\tform = AuthenticationForm()\n\treturn render( request, 'ticket/login.html', {'form': form})\t\n\ndef list_view(request):\n\tdata = Tickets.objects.all().order_by('-pk')\n\tquery = request.POST.get('q')\n\tif query:\n\t\tqueryset_list = Tickets.objects.filter(Q(subject__icontains=query) | Q(pk__icontains=query))\n\t\tdata = queryset_list\n\treturn render(request, 'ticket/list.html', {'data':data})\n\n\ndef info_view(request):\n\tdata = Tickets.objects.get(pk=2)\n\tcomments_list = Comments.objects.filter(ticket_id=data.pk).order_by('-created_date')\n\tif request.method == 'POST':\n\t\tform = FormComment(request.POST)\n\t\tif form.is_valid():\n\t\t\tcomment = request.POST.get('comment')\n\t\t\temp_id = request.POST.get('emp_id')\n\t\t\tticket_id = Tickets.objects.get(id=data.pk)\n\t\t\temp_id = Employee.objects.get(id=emp_id)\n\t\t\tcomment_obj = Comments(message=comment, ticket_id=ticket_id, emp_id=emp_id)\n\t\t\tcomment_obj.save()\n\telse:\n\t\tform = FormComment()\n\t#print(comments_list.message)\n\treturn render(request, 'ticket/info.html', {'data':data, 'comments': comments_list, 'form': form})\n\ndef add_ticket_view(request):\n\tif request.method == 'POST':\n\t\tform = FormTicket(request.POST)\n\t\tif form.is_valid():\n\t\t\t#form_items = form.save(commit=False)\n\t\t\t#form_items.save()\n\t\t\tsubject = request.POST.get('subject')\n\t\t\tdescription = request.POST.get('description')\n\t\t\tstatus = request.POST.get('status')\n\t\t\tpriority = request.POST.get('priority')\n\t\t\tticket_owner = request.POST.get('ticket_owner')\n\t\t\tassign_to = request.POST.get('assign_to')\n\t\t\tticket_owner_name = Employee.objects.get(id=ticket_owner)\n\t\t\tassing_name = Employee.objects.get(id=assign_to)\n\t\t\tprint (ticket_owner_name)\n\t\t\tticket_obj = Tickets(subject=subject, description=description, status=status, priority=priority, ticket_owner=ticket_owner_name, assigned_to=assing_name)\n\t\t\tticket_obj.save()\n\t\t\treturn redirect('ticket:add_ticket')\n\telse:\n\t\tform = FormTicket()\n\treturn render(request, 'ticket/ticket_form.html', {'form': form})","sub_path":"ticket/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529026273","text":"import requests\r\nimport xlsxwriter\r\nfrom bs4 import BeautifulSoup\r\n\r\n#Lấy số page trong website\r\nurl = f'https://nghiahsgs.com'\r\ndayLaHeaders = {\r\n\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'\r\n}\r\nres = requests.get(url,headers=dayLaHeaders)\r\nsoup = BeautifulSoup(res.text,'lxml')\r\n\r\naTag = soup.find_all('a',class_ = 'page-numbers')\r\npage_number = int(aTag[1].text)+1\r\n#>>>> aTag[1].text = 11\r\n\r\n#Lấy ra danh sách link và tên bài viết\r\nlink = []\r\ntitle = []\r\n\r\nfor i in range(page_number):\r\n\turl2 = f'https://nghiahsgs.com/page/{i}/'\r\n\tdata = requests.get(url2,headers=dayLaHeaders)\r\n\tsoup2 = BeautifulSoup(data.text,'lxml')\r\n\tlistH2 = soup2.find_all('h2',class_ = 'entry-title')\r\n\tfor j in listH2:\r\n\t\tlink.append(j.a.get('href'))\r\n\t\ttitle.append(j.a.text)\r\nfinalLink = set(link)\r\nfinalTitle = set(title)\r\nfinalResult = zip(finalLink,finalTitle)\r\n#Viết ra excel\r\ncreateWB = xlsxwriter.Workbook('result.xlsx')\r\nsheet = createWB.add_worksheet()\r\nrow = 0 \r\ncol = 0 \r\nfor n,v in finalResult:\r\n\tsheet.write(row,col,n)\r\n\tsheet.write(row,col+1,v)\r\n\trow+=1\r\ncreateWB.close()\t\r\n","sub_path":"BTVN/BTVN beautifulsoup.py","file_name":"BTVN beautifulsoup.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"135187999","text":"from uuid import uuid4\nfrom django.db import models\n\nimport datetime\n# Create your models here.\n\nTAX_VALUE = 0.18\n\n# Create your models here.\n\n\nclass Producto(models.Model):\n\n id = models.UUIDField(primary_key=True, default=uuid4, editable=False)\n\n presentancion = models.CharField(max_length=50)\n nombre = models.CharField(max_length=200, unique=True)\n\n fecha_expiracion = models.DateField()\n fecha_produccion = models.DateField()\n descripcion = models.TextField(max_length=400)\n precio_Compra = models.DecimalField(\n max_digits=5, decimal_places=2, default=0.00)\n precio_venta = models.DecimalField(\n max_digits=5, decimal_places=2, default=0.00)\n stock = models.PositiveSmallIntegerField()\n\n def __unicode__(self):\n return self.nombre\n\n def preeciototal(self):\n precio_total = self.precio_compra * self.stock\n return precio_total\n\n def estadoproducto(self):\n hoy = datetime.date.today()\n dias = (self.fecha_expiracion - hoy).days\n return dias\n\n def incrementarlote(self, *args, **kwargs):\n if self.lote == 0:\n self.lote += 1\n self.store.save()\n super(Producto, self).save(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n if self.precio_venta:\n self.igv = round(float(self.precio_venta) * TAX_VALUE, 3)\n super(Producto, self).save(*args, **kwargs)\n else:\n self.igv = 0\n super(Producto, self).save(*args, **kwargs)\n","sub_path":"market_serve/market_service_apps/registro/models/producto.py","file_name":"producto.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"180513499","text":"import sys\n\ndef toggle_case(s):\n if s.isupper():\n return s.lower()\n elif s.islower():\n return s.upper()\n else:\n return s\n\ndef is_caps_lock(s):\n len_s = len(s)\n if s.isupper():\n return True\n elif (len_s == 1) or s[1:].isupper():\n return True\n else:\n return False\n\ndef process_caps_lock(s):\n if is_caps_lock(s):\n return ''.join([toggle_case(x) for x in s])\n else:\n return s\n\ndef main(args):\n lines = sys.stdin.readlines()\n print(process_caps_lock(lines[0].strip()))\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"101_200/problem_131_a/problem_131_a.py","file_name":"problem_131_a.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"611859969","text":"import os\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\"keys.json\"\n\nimport pandas as pd\nfrom bq_helper import BigQueryHelper\nimport plotly.graph_objs as go\nfrom plotly.offline import plot\n\nbq_assistant = BigQueryHelper('bigquery-public-data', 'nhtsa_traffic_fatalities')\n\nQUERY = \"\"\"\n SELECT state_number, consecutive_number, vehicle_number, contributing_circumstances_motor_vehicle \n FROM `bigquery-public-data.nhtsa_traffic_fatalities.factor_2015`\n LIMIT 10000\n \"\"\"\ndf = bq_assistant.query_to_pandas(QUERY)\n\nstate_group = df.groupby(['state_number'])\ntrace1_data = state_group['state_number'].count()\ntrace1 = go.Bar(\n x = trace1_data.index\n ,y = trace1_data.values\n )\nvehicle_group = df.groupby(['vehicle_number'])\ntrace2_data = state_group['vehicle_number'].count()\ntrace2 = go.Pie(\n title = 'Vehicle number, which have an accident'\n ,labels = trace2_data.index\n ,values = trace2_data.values\n )\n# consecutive_number_group = df.groupby(['consecutive_number'])\n# trace3_data = state_group['consecutive_number'].count()\n# trace3 = go.Scatter(\n# x=trace3_data.index\n# ,y=trace3_data.values\n# ,name = 'Consecutive Number'\n# )\n# plot(trace3)\n\ntrace1_layout = go.Layout(title = 'Traffic fatalities'\n ,xaxis= dict(title= 'State')\n ,yaxis=dict(title='Number of vehicles')\n )\n\nfig = dict(data = [trace1], layout = trace1_layout)\n\nplot(fig)\nplot(go.Figure(trace2))","sub_path":"km92/IvanovaES/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"351421092","text":"import xadmin\nfrom .models import UserAsk,UserCourse,UserMessage,CourseComments,UserFavorite\n\n# Register your models here.\n\nclass UserAskAdmin(object):\n '''用户表单我要学习'''\n list_display = ['name','mobile','course_name','add_time']\n search_fields = ['name','mobile','course_name',]\n list_filter = ['name','mobile','course_name','add_time']\n model_icon = 'fa fa-phone'\n\n\nclass UserCourseAdmin(object):\n '''用户课程学习'''\n list_display = ['user', 'course', 'add_time']\n search_fields = ['user', 'course']\n list_filter = ['user', 'course', 'add_time']\n model_icon = 'fa fa-bars'\n\n\nclass UserMessageAdmin(object):\n '''用户消息后台'''\n list_display = ['user','message','has_read','add_time']\n search_fields = ['user','message','has_read']\n list_filter = ['user','message','has_read','add_time']\n model_icon = 'fa fa-comments'\n\n\nclass CourseCommentAdmin(object):\n '''用户评论后台'''\n list_display = ['user','course','comments','add_time']\n search_fields = ['user','course','comments']\n list_filter = ['user','course','comments','add_time']\n model_icon = 'fa fa-comment-o'\n\n\nclass UserFavoriteAdmin(object):\n '''用户收藏后台'''\n list_display = ['user','fav_id','fav_type','add_time']\n search_fields = ['user','fav_id','fav_type']\n list_filter = ['user','fav_id','fav_type','add_time']\n model_icon = 'fa fa-heart'\n\n\n#将后台管理器与Model进行关联注册\nxadmin.site.register(UserAsk,UserAskAdmin)\nxadmin.site.register(UserCourse,UserCourseAdmin)\nxadmin.site.register(UserMessage,UserMessageAdmin)\nxadmin.site.register(CourseComments,CourseCommentAdmin)\nxadmin.site.register(UserFavorite,UserFavoriteAdmin)\n","sub_path":"apps/operation/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"57939855","text":"import os\nimport time\nmrgStart, mrgStop, fileReadST, fileReadSTP, fileWriteST, fileWriteSTP = 0, 0, 0, 0, 0, 0\nmsST_75K, msST_150K, msST_300K, msST_450K = 0, 0, 0, 0\nmsSTP_75K, msSTP_150K, msSTP_300K, msSTP_450K = 0, 0, 0, 0\n\n\ndef merge(left, right):\n if not len(left) or not len(right):\n return left or right\n\n result = []\n i, j = 0, 0\n while (len(result) < len(left) + len(right)):\n if left[i] < right[j]:\n result.append(left[i])\n i += 1\n else:\n result.append(right[j])\n j += 1\n if i == len(left) or j == len(right):\n result.extend(left[i:] or right[j:])\n break\n\n return result\n\n\ndef mergeSort(list):\n if len(list) < 2:\n return list\n\n middle = len(list)//2\n left = mergeSort(list[:middle])\n right = mergeSort(list[middle:])\n\n return merge(left, right)\n\n\ndef mergeMain():\n global mrgStart, mrgStop, msST_75K, msST_150K, msST_300K, msST_450K, msSTP_75K, msSTP_150K, msSTP_300K, msSTP_450K, fileReadST, fileReadSTP, fileWriteST, fileWriteSTP\n mrgStart = time.time()\n\n fileReadST = time.time()\n file1_Data = []\n file2_Data = []\n file3_Data = []\n file4_Data = []\n file5_Data = []\n file6_Data = []\n\n with open(\"file1.txt\", \"r\") as file1, open(\"file1.txt\", \"r\") as file2, open(\"file3.txt\", \"r\") as file3, open(\"file4.txt\", \"r\") as file4, open(\"file5.txt\", \"r\") as file5, open(\"file6.txt\", \"r\") as file6:\n file1_Data = file1.read().splitlines()\n file1_Data = list(map(int, file1_Data))\n\n file2_Data = file2.read().splitlines()\n file2_Data = list(map(int, file2_Data))\n\n file3_Data = file3.read().splitlines()\n file3_Data = list(map(int, file3_Data))\n\n file4_Data = file4.read().splitlines()\n file4_Data = list(map(int, file4_Data))\n\n file5_Data = file5.read().splitlines()\n file5_Data = list(map(int, file5_Data))\n\n file6_Data = file6.read().splitlines()\n file6_Data = list(map(int, file6_Data))\n\n file1.close()\n file2.close()\n file3.close()\n file4.close()\n file5.close()\n file6.close()\n\n os.remove(\"file1.txt\")\n os.remove(\"file2.txt\")\n os.remove(\"file3.txt\")\n os.remove(\"file4.txt\")\n os.remove(\"file5.txt\")\n os.remove(\"file6.txt\")\n\n fileReadSTP = time.time()\n print(\"file-read: %s sec\" % (fileReadSTP-fileReadST))\n\n msST_75K = time.time()\n file1_Data = mergeSort(file1_Data)\n msSTP_75K = time.time()\n print(\"merge-sort @ 75K: %s sec\" % (msSTP_75K-msST_75K))\n\n file2_Data = mergeSort(file2_Data)\n file3_Data = mergeSort(file3_Data)\n file4_Data = mergeSort(file4_Data)\n file5_Data = mergeSort(file5_Data)\n file6_Data = mergeSort(file6_Data)\n\n file7_Data = file1_Data + file2_Data\n msST_150K = time.time()\n file7_Data = mergeSort(file7_Data)\n msSTP_150K = time.time()\n print(\"merge-sort @ 150K: %s sec\" % (msSTP_150K-msST_150K))\n\n file8_Data = file3_Data + file4_Data\n file8_Data = mergeSort(file8_Data)\n\n file9_Data = file5_Data + file6_Data\n file9_Data = mergeSort(file9_Data)\n\n file10_Data = file7_Data + file8_Data\n msST_300K = time.time()\n file10_Data = mergeSort(file10_Data)\n msSTP_300K = time.time()\n print(\"merge-sort @ 300K: %s sec\" % (msSTP_300K-msST_300K))\n\n # This is the main sorted file\n file11_Data = file9_Data + file10_Data\n msST_450K = time.time()\n file11_Data = mergeSort(file11_Data)\n msSTP_450K = time.time()\n print(\"merge-sort @ 450K: %s sec\" % (msSTP_450K-msST_450K))\n\n fileWriteST = time.time()\n os.remove(\"elementsFile.txt\")\n with open(\"elementsFile.txt\", \"w\") as file:\n for item in file11_Data:\n file.write(\"%s\\n\" % item)\n file.close()\n fileWriteSTP = time.time()\n print(\"file-write: %s sec\" % (fileWriteSTP-fileWriteST))\n\n mrgStop = time.time()\n print(\"merge Sort : %s sec\" % (mrgStop-mrgStart))\n\n# # Driver code\n# a = [12, 11, 13, 5, 6, 7,15,200,22,64,128,229,500,11,12,10,55,250,2,0,15,20,420,2500]\n# print(\"Given array is \")\n# print(a)\n# print(\"Sorted array is \")\n# print(mergeSort(a))\n","sub_path":"College/Lab/Algorithms_Lab/Experiment1/mergeSort.py","file_name":"mergeSort.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335885635","text":"import argparse\nfrom pathlib import Path\nfrom operations.compress import compress_image, write_to_file, open_image, split_into_tiles, tiles_to_symbols\nfrom operations.extract import extract, extract_dimensions, read_compressed_image, save_extracted_image, join_tiles, unpad_representation\nfrom data_classes.tree import HuffmanTree\nfrom utils import compute_average_code_length, compute_entropy\n\nif __name__ == '__main__':\n\n args_parser = argparse.ArgumentParser()\n\n args_parser.add_argument('--compress', action='store_true', help='Flag to compress file')\n args_parser.add_argument('--extract', action='store_true', help='Flag to extract file')\n args_parser.add_argument('-f', action='store', dest='file_path', type=str, required=True, help='Path of the file to compress/extract')\n args = args_parser.parse_args()\n\n file_path: Path = Path(args.file_path)\n\n if args.compress:\n raw_image = open_image(file_path)\n heigth, width = raw_image.shape\n\n tiled_image = split_into_tiles(raw_image, 2, 2)\n input_sequence = tiles_to_symbols(tiled_image)\n\n huffman_tree = HuffmanTree()\n huffman_tree.build_tree(input_sequence)\n\n average_code_length = compute_average_code_length(input_sequence, huffman_tree._symbol_table)\n entropy = compute_entropy(input_sequence)\n print(f\"L(C) = {average_code_length}\")\n print(f\"H(X) = {entropy}\")\n print(f\"[H(X) <= L(C) < H(X) + 1]: {average_code_length - entropy < 1}\")\n\n compressed_image = compress_image(input_sequence, huffman_tree._symbol_table)\n\n original_image_size = heigth * width\n print(f\"Compression rate: {original_image_size/len(compressed_image)}\")\n\n write_to_file(file_path, heigth,width, compressed_image, huffman_tree)\n \n elif args.extract:\n compressed_image = read_compressed_image(file_path)\n huffman_tree = HuffmanTree()\n\n unpadded_compressed_image = unpad_representation(compressed_image)\n heigth, width, remaining_compressed_image = extract_dimensions(unpadded_compressed_image)\n\n extracted_image = extract(remaining_compressed_image, huffman_tree)\n two_dimensional_image = join_tiles(extracted_image, heigth, width)\n\n save_extracted_image(file_path, two_dimensional_image)\n\n print(\"Image extracted successfully!\")\n else:\n print(\"Pass --compress or --decompress flags.\")","sub_path":"MSc/Compressão e Codificação de Dados/Trabalho Final/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595135725","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport socket\nimport time\nimport random\nfrom threading import Thread\nfrom random import randint\nimport ssl\n\nhost = 'localhost'\nport = 26697\nnick = 'beefbot'\nident = 'pythonbeefBot'\nrealname = 'i_heart_beef'\nreadbuffer = ''\nchannel = '#testtimmch'\nline = ''\nirc_sock = socket\nirc_wrapped = socket\nconnected_servers = []\nsplitline = []\nsplitlineupper = []\nlastlineChange = \"\"\nkeyword = ''\n\n#Change this path!\nquizfilePath = 'quizbot_quiz.txt'\nquizlist = []\nquiz_question = ''\nquiz_answer = ''\n\n\ndef _connect():\n # join the said channel\n global irc_sock\n global irc_wrapped\n irc_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n irc_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\n irc_wrapped = ssl.wrap_socket(irc_sock)\n irc_wrapped.connect((host, port))\n irc_wrapped.sendall(bytes(\"NICK %s\\r\\n\" % nick, 'UTF-8'))\n irc_wrapped.sendall(bytes(\"USER %s %s bla :%s\\r\\n\" % (ident, host, realname), 'UTF-8'))\n time.sleep(2)\n irc_wrapped.sendall(bytes(\"JOIN %s %s \\r\\n\" % (channel, keyword), 'UTF-8'))\n connected_servers.append(host)\n\ndef _ping(pingmsg):\n irc_wrapped.sendall(bytes(\"PONG \" + pingmsg + \"\\r\\n\", 'UTF-8'))\n print(\"Pong gesendet\")\n\n\ndef _getsender(line):\n sender = line.split('!')[0][1:]\n return sender\n\n\ndef _sendeasy(message):\n irc_wrapped.sendall(bytes(\"PRIVMSG \" + channel + \" :\" + message + \"\\r\\n\", 'UTF-8'))\n print(\"sending: PRIVMSG \" + channel + \" :\" + message)\n # pass\n \nbad_words = [\"Hure\", \"Schlampe\", \" Arsch\", \"Wixxer\", \"Penis\", \"volldepp\", \"spinner\", \"fick\", \"pimmel\", \"depp\", \"homo\",\n \"fotze\", \"schwanzlutscher\", \"analverkehr\", \"anal \", \"Knecht\", \"Grattler\", \"Schalke\", \"Dortmund\", \"glubb\",\n \"Fc Bayern\", \"wichser\", \"halts maul\", \"fresse\"]\n\nbeef_keywords = [\"null\", \"dumm\", \"blöd\", \"doof\", \"nervt\", \"nerven\", \"langeweile\", \"langweilig\",\"kaffee\", \"hunger\", \"hungrig\", \"frühstück\", \"fs\", \"vors D\"]\nbeef_phrases = [\"Fick dich selbst \", \"Halt selbst die Fresse \", \"Halt selbst dein Maul \", \"Deine Mutter war gestern auch ziemlich geil \"]\n\nflirt_phrases = [\"Bock zu ficken?\", \"hey torte bock auf füllung?\", \"hast du 5 minuten zeit und 20 cm platz\",\n \"du bist einsam ich bin einsam lass mich dich einsamen\"\n , \"siehst du die sterne funkeln willst mir nicht einen runterholen\",\n \"glaubst du an liebe auf den ersten blick oder soll ich nochmal vorbei kommen\",\n \"das leben ist eing geben und nehmen, nimm mich und ich gibs dir\",\n \"Hey, biste öfters hier?\",\n \"das leben ist ein nehmen und geben, ich gebe dir penis und nehme den nächsten bus\"]\n\nyour_mother = [\"Deine Mutter ist so fett! Wenn dein Papa ihr morgens auf den Hintern schlägt,\"\n \" dann wackelt der Po noch, wenn er abends nach Hause kommt \",\"Deine Mutter schminkt sich mit Edding \",\n \"Deine Mutter ist wie ein Ketchupfleck, jeder darf mal seine Wurst reinstecken \",\n \"Deine Mutter geht zu “Wer wird Millionär?” und macht Schulden! \",\n \"Deine Mutter ist so fett, sie benutzt eine Matratze als Tampon.\",\n \"Deine Mutter ist so fett, die bricht vom Stammbaum ab.\",\n \"Deine Mutter ist so dumm. Sie probiert M&Ms nach dem Aphabet zu ordnen.\",\n \"Deine Mutter steckt sich einen Fisch in den Hintern und sagt: “Ich bin eine Meerjungfrau!”\"]\ndef _beefSender(line):\n sender = _getsender(line)\n if \"fick dich\" in line.lower():\n _sendeasy(beef_phrases[0] + sender)\n elif \"fresse\" in line.lower():\n _sendeasy(beef_phrases[1] + sender)\n elif \"halts maul\" in line.lower():\n _sendeasy(beef_phrases[2] + sender)\n elif \"null\".lower() in line.lower():\n _sendeasy(\"Hat jemand gerade die Null gewählt oder warum redest du \" + _getsender(line))\n elif \"dumm\".lower() in line.lower():\n _sendeasy(\"Was soll man bei einem IQ von 70 auch sonst erwarten \" + _getsender(line))\n elif \"blöd\".lower() in line.lower():\n _sendeasy(\"Was soll man bei einem IQ von 70 auch sonst erwarten \" + _getsender(line))\n elif \"doof\".lower() in line.lower():\n _sendeasy(\"Was soll man bei einem IQ von 70 auch sonst erwarten \" + _getsender(line))\n elif \"nervt\".lower() in line.lower():\n _sendeasy(\"DU nervst \" + _getsender(line) + \". Geh Baum spielen!\")\n elif \"nerven\".lower() in line.lower():\n _sendeasy(\"DU nervst \" + _getsender(line) + \". Geh Baum spielen!\")\n elif \"langeweile\".lower() in line.lower():\n _sendeasy(\"Geh doch ein bisschen auf der Autobahn spielen \" + _getsender(line))\n elif \"langweilig\".lower() in line.lower():\n _sendeasy(\"Geh doch ein bisschen auf der Autobahn spielen \" + _getsender(line))\n elif \" fs \".lower() in line.lower():\n _sendeasy(\"Ich gehe nicht mit frühstücken, ich war heute schon bei deiner Mum \" + _getsender(line))\n elif \"frühstück\".lower() in line.lower():\n _sendeasy(\"Ich gehe nicht mit frühstücken, ich war heute schon bei deiner Mum \" + _getsender(line))\n elif \"hunger\".lower() in line.lower():\n _sendeasy(\"Kinder in Afrika haben auch Hunger und heulen nicht so rum \" + _getsender(line))\n elif \"hungrig\".lower() in line.lower():\n _sendeasy(\"Kinder in Afrika haben auch Hunger und heulen nicht so rum \" + _getsender(line))\n elif \"kaffee\".lower() in line.lower():\n _sendeasy(\"Soll ich dir Sahne zum Kaffee machen, \" + _getsender(line) + \"?\")\n elif \"vors D\".lower() in line.lower():\n _sendeasy(\"Ich komm auch und nehm meine Homies mit \" + _getsender(line))\n\ndef _searchandanswer(line):\n global irc_wrapped\n if \"ERROR :Closing Link: suse.com (Ping timeout: 600 seconds)\" == line:\n print(\"Ping timeout\")\n reconnect()\n print(\"reconnect done, continue\")\n if \"ERROR :Closing Link: suse.com (Excess Flood)\" == line:\n print(\"Excess Flood\")\n reconnect()\n print(\"reconnect done, continue\")\n if any(s.lower() in line.lower() and nick in line.lower() for s in bad_words):\n print(\"Beefbot!\")\n _beefSender(line)\n if any(s.lower() in line.lower() for s in beef_keywords):\n _beefSender(line)\n if (\"danke \" + nick).lower() in line.lower():\n _sendeasy(\"Bitte \" + _getsender(line))\n if \"geil\".lower() in line.lower():\n _sendeasy(beef_phrases[3] + \"\" + _getsender(line))\n if \"deine mutter\".lower() in line.lower():\n _sendeasy(your_mother[randint(0, len(your_mother) - 1)] + \" \" + _getsender(line))\n #A logical \"OR\" hasn't worked because of Pythons logic\n if \"deine mudda\".lower() in line.lower():\n _sendeasy(your_mother[randint(0, len(your_mother) - 1)] + \" \" + _getsender(line))\n if \"anmachspruch\".lower() in line.lower():\n _sendeasy(flirt_phrases[randint(0, len(flirt_phrases) - 1)])\n if \"gogo\".lower() in line.lower():\n _sendeasy(\"Ich komm auch und nehm meine Homies mit \" + _getsender(line))\n if (\"MODE \" + channel + \" +o \" + nick in line):\n print(\"got op\")\n _sendeasy(\"danke \" + _getsender(line))\n opcount = 0\n\n\ndef _action():\n while 1:\n global readbuffer\n global splitline\n global splitlineupper\n global line\n global watch_thread\n\n readbuffer = readbuffer + irc_wrapped.recv(1024).decode('UTF-8')\n temp = str.split(readbuffer, \"\\n\")\n readbuffer = temp.pop()\n\n for line in temp:\n print(\"\\033[94m\" + \"line \" + \"\\033[0m\" + line)\n line = str.rstrip(line)\n splitline = str.split(line)\n # answer to server ping\n if (splitline[0] == \"PING\"):\n print(line)\n _ping(splitline[1])\n thread = Thread(target=_searchandanswer(line))\n thread.start()\n\n\ndef reconnect():\n print(\"do the shutdown\")\n irc_wrapped.shutdown(socket.SHUT_RDWR)\n print(\"close the connection\")\n irc_wrapped.close()\n print(\"reopen the connection\")\n _connect()\n\n\n_connect()\n_action()\n\n","sub_path":"beefbot.py","file_name":"beefbot.py","file_ext":"py","file_size_in_byte":8079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"217736159","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('home', views.home),\n path('', views.home),\n #authentification\n path('go_connexion', views.go_connexion),\n path('authentification', views.authentification),\n\n #contact\n path('send_mail_to_me', views.send_mail_to_me, name='send_mail_to_me'),\n\n #database\n path('load_database', views.load_database)\n]","sub_path":"portfolio/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"160180297","text":"from sympy import symbols\nfrom sympy import solve\nfrom sympy import diff\n\n\nx = symbols('x')\nf = (63 * x**5 - 70 * x**3 + 15 * x) / 8\ng = diff(f)\t\t#对f求导\n\nm = solve(g)\t#m列表是g(x) = 0的解\nm.insert(0, -1)\nm.append(1)\nm = sorted(m)\t#给m排序\n\ne = 1e-8\t\t#精度\nj = 0\t\t\t#解的个数\nfor i in range(len(m) - 1):\n\tcnt = 0\t\t#迭代次数\n\ta, b = m[i], m[i+1]\n\twhile True:\n\t\tmid = (a + b) / 2\n\t\tA = f.evalf(subs = {x:a})\n\t\tMid = f.evalf(subs = {x:mid})\n\t\tif Mid == 0:\n\t\t\tbreak\n\t\tcnt += 1\n\t\tif A * Mid < 0:\n\t\t\tb = mid\n\t\telse:\n\t\t\ta = mid\n\t\tif abs(b - a) < e:\n\t\t\tbreak\n\tj += 1\n\tprint(\"x{} = {},迭代了{}次\".format(j, float(mid), cnt))\n","sub_path":"Bisection.py","file_name":"Bisection.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538235969","text":"\"\"\"\nThis script returns the average conservation (phastCons) score for a \ngiven interval region, as defined in the sorted input bed file.\n\n\"\"\"\n\nimport argparse\nimport pandas as pd\nimport numpy as np\nimport gzip\nimport multiprocessing\nfrom functools import partial\n\n\n# wig functions courtesy of Chris Hartl\nclass WigReader(object):\n def __init__(self, file_):\n self._handle = gzip.open(file_) if file_.endswith('gz') else open(file_)\n self._header = self._handle.readline()\n self._header_info = dict([t.split('=') for t in self._header.strip().split(' ')[1:]])\n self._header_info = {k: (v if k == 'chrom' else int(v)) for k, v in self._header_info.items()}\n self._offset = 0\n\n @property\n def chrom(self):\n return self._header_info['chrom']\n\n def start(self):\n return self._header_info['start']\n\n def step(self):\n return self._header_info['step']\n\n def __iter__(self):\n for line in self._handle:\n if line.startswith('fixedStep'):\n self._header = line\n self._header_info = dict([t.split('=') for t in self._header.strip().split()[1:]])\n self._header_info = {k: (v if k == 'chrom' else int(v)) for k, v in self._header_info.items()}\n self._offset = 0\n continue\n data = (self.start() + self._offset * self.step(), float(line.strip()))\n self._offset += 1\n yield data\n\n\ndef in_interval(pos, interval):\n return interval[0] <= pos <= interval[1]\n\n\n# def get_interval(itr, interval):\n# e = next(itr)\n# while e[0] < interval[0]:\n# e = next(itr)\n# while in_interval(e[0], interval):\n# yield e\n# e = next(itr)\n# # note: skips first base outside of interval, but ours are\n# # not overlapping\n\n\ndef get_interval(itr, interval, curr_base=None):\n\tif not curr_base:\n\t\t# initialize\n\t\te = next(itr)\n\telse:\n\t\t# start at current base, do not iterate through an extra base\n\t\te = curr_base\n\twhile e[0] < interval[0]:\n\t\te = next(itr)\n\twhile in_interval(e[0], interval):\n\t\tyield e \n\t\te = next(itr)\n\tyield e \n # note: will always yield one base outside of region so that no base\n # is ever skipped\n\n\ndef bed_iter(filename):\n\t\"\"\"\n\tIterate through a bed file, yielding all intervals for one chromosome\n\t\"\"\"\n\twith open(filename) as bed:\n\t\t# initialize \n\t\tchr_info = []\n\t\tinterval = next(bed).strip().split('\\t')\n\t\t# format: chr, start, end, name\n\t\tcurr_chrom = interval[0]\n\t\tchr_info.append(interval)\n\t\tfor line in bed:\n\t\t\tinterval = line.strip().split('\\t')\n\t\t\tchrom = interval[0]\n\t\t\tif chrom != curr_chrom:\n\t\t\t\tyield chr_info\n\t\t\t\tchr_info = []\n\t\t\t\tcurr_chrom = chrom\n\t\t\tchr_info.append(interval)\n\t\t# end of file\n\t\tyield chr_info\n\n\ndef chrom_extract_cons(chrom_region, cons_folder):\n\t\"\"\"\n\tThis function takes as input a chromosome (e.g. chr9) and regions in that\n\tchromosome as parsed by bed_iter(). It opens the appropriate wig file and\n\textracts the mean conservation scores for each region.\n\n\tchrom_region: chromosome regions, list of lists. Each element in the list is a\n\tregion, which is itself a list with four fields (chromosome, start, end, name).\n\tThis is the format returned from bed_iter()\n\tcons_folder: directory where conservation files are located\n\n\treturn: chrom_region with an extra field for conservation added to each region\n\t\"\"\"\n\t# suffix common to all files\n\tcons_suffix = '.phastCons100way.wigFix.gz'\n\t# get chromosome from chrom_region\n\tchrom = chrom_region[0][0]\n\t# open appropriate wig file\n\twig = WigReader(cons_folder + chrom + cons_suffix)\n\n\t# initialize iter with first region\n\t# region format: [chrN, start, end, name]\n\t# outputs tuple, (position, score)\n\tfirst_region = chrom_region.pop(0)\n\tcons_scores = list(get_interval(iter(wig), (int(first_region[1]), int(first_region[2]))))\n\t# pop first base outside interval from end of list\n\tcurr_base = cons_scores.pop()\n\t# get average\n\tcons_mean = np.mean([x[1] for x in cons_scores])\n\tfirst_region.append(str(cons_mean))\n\n\n\tfor region in chrom_region:\n\t\t# initialize with current base so that no base is ever skipped\n\t\tcons_scores = list(get_interval(iter(wig), (int(region[1]), int(region[2])),\n\t\t\tcurr_base=curr_base))\n\t\tif len(cons_scores) >= 1:\n\t\t\t# pop first base outside interval from end of list\n\t\t\tcurr_base = cons_scores.pop()\n\t\t# get average\n\t\tcons_mean = np.mean([x[1] for x in cons_scores])\n\t\tregion.append(str(cons_mean))\n\t\n\t# finally, add the first region we popped in the beginning\n\tchrom_region.insert(1, first_region)\n\treturn chrom_region\n\n\ndef main(bed, cons_folder, output, num_processes):\n\n\toutfile = open(output, 'w')\n\n\tbed_chroms = bed_iter(bed)\n\t\n\tpool = multiprocessing.Pool(processes=num_processes)\n\n\t# assign constant parameter to function\n\tfunc = partial(chrom_extract_cons, cons_folder=cons_folder)\n\t# map each chromosome in bed_chroms to the function and run in parallel\n\tcons_scores = pool.map(func, bed_chroms)\n # write to file\n\twith open(output, 'w') as outfile:\n\t\tfor chrom_region in cons_scores:\n\t\t\tfor region in chrom_region:\n\t\t\t\toutfile.write('\\t'.join(region)+'\\n')\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser('wrapper for accessing phastCons files.\\\n\t\tReturns average conservation score for regions defined in BED file')\n\tparser.add_argument('bed', help='BED file of interval regions.')\n\tparser.add_argument('cons_folder', help='path to folder with compressed phastCons files')\n\tparser.add_argument('output', help='name of output file')\n\tparser.add_argument('--num_processes', type=int, default=3,\n\t\thelp='number of parallel processes')\n\n\targs = parser.parse_args()\n\tmain(args.bed, args.cons_folder, args.output, args.num_processes)\n\t\t\n\n\n\n","sub_path":"exac/scripts/phastCons_wrapper.py","file_name":"phastCons_wrapper.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"233473018","text":"import re\n\ndata = \"data_bad.xml\"\nregex = \"<Detail\\s+Полное_и_сокращенное_наименование_организации_с_указанием_ее_организационно___правовой_формы=(.*?)\\s+ИНН\"\ni = 0\nwith open(data, encoding='utf-8') as file:\n for line in file.readlines():\n i += 1\n print(i)\n print(re.sub(regex, '\\g<1>', line))\n #print(re.finditer(regex, line))\n '''matches = re.finditer(regex, line, re.MULTILINE)\n\n for matchNum, match in enumerate(matches):\n matchNum = matchNum + 1\n print(\"Match {matchNum} was found at {start}-{end}: {match}\".format(matchNum=matchNum, start=match.start(),\n end=match.end(), match=match.group()))\n print(\"Match found for line:\", i)\n print((match.group(1)).replace('\"', \"\"))\n for groupNum in range(1, len(match.groups())):\n groupNum = groupNum + 1\n print(match.group(groupNum))'''","sub_path":"RegExp_parse.py","file_name":"RegExp_parse.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26642524","text":"# -*- coding: utf-8 -*-\n'''\nCreated on Sep 12, 2014\n\n@author: dinh.pham\n'''\n\nimport logging\nfrom flask import request\nfrom fscore.helper import routing\nfrom fscore.app import app\nfrom fscore.helper.response import get_response, get_unauthorized_response, STATUS_OK, \\\n STATUS_FORBIDDEN, SUBCODE_PERM_INSUFFICIENT, SUBCODE_VALID_IDENTITY_NOT_FOUND, \\\n get_service_unavailable_response, STATUS_INTERNAL_ERROR, STATUS_BAD_REQUEST, \\\n SUBCODE_VALID_OBJECT_NOT_FOUND\nfrom fscore.helper.azure_utils import make_blob_sas_url, make_container_sas_url\nfrom fscore.service.file_retrieval import FileService, PERM_VALID_RECIPIENT, PERM_OWNER\nfrom appconfig import constants\n\n\nlogger = logging.getLogger('fscore.app')\n\n\n@app.route('/2.0/azure/blob/<uid>/<blob_id>/shared-access', methods=['GET', ])\n@routing.login_required\ndef get_azure_file_shared_access_signature(session_info, uid, blob_id):\n '''\n A shared access signature is a URI that grants restricted access rights to containers, blobs, \n queues, and tables for a specific time interval.\n\n When user is activated, he will be assigned with his own Azure container with rw permission\n \n GET /2.0/azure/blob/<container-name>/<blob-id>/shared-access?access_token=xxxxxx&permission=r|rw\n \n + permission: Default to 'r'\n\n Response\n \n {\n \"body\":{\n \"signature\": \"<string>\"\n },\n \"meta\":{\n \"message\": null,\n \"code\": 200,\n \"detail\": null\n }\n }\n \n https://fscs1.cloudapp.net/2.0/azure/blob/6009a4e3-4969-4f05-aa40-fbd4541f18e6/46913cb5-4ce5-4b39-9340-a2ad8a3a2bfc.docx/shared-access?access_token=sn9-VK0MQAAbOhBjLV0rDt__ZVc\n\n @see https://communicate.atlassian.net/browse/FCOR-426\n @see http://msdn.microsoft.com/en-us/library/azure/jj721951.aspx Create and Use a Shared Access Signature\n @see http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-shared-access-signature-part-2/\n FIXME: Check permission on requested file_id (is the authenticated user a file recipient or owner?)\n '''\n azure_perm = request.args.get('permission', 'r')\n '''\n if perm not in ('r', 'rw', 'rwd'):\n return get_invalid_param_response('Parameter \"permission\" accepts \"r\" or \"rw\" or \"rwd\" only')\n '''\n blob_id = blob_id.lower()\n if '.' in blob_id:\n file_id = blob_id[:blob_id.index('.')]\n else:\n file_id = blob_id\n perm, status = FileService().find_permission(file_id, uid, constants.PERM_VIEW)\n if status == 1:\n if perm in (0, PERM_OWNER, PERM_VALID_RECIPIENT):\n return get_response(body={\n 'signature': make_blob_sas_url(uid.lower(), blob_id.lower(), perm=azure_perm)\n },\n as_json=True,\n status=STATUS_OK)\n return get_unauthorized_response(detail={'subcode': SUBCODE_PERM_INSUFFICIENT})\n if status == -1:\n return get_response(message='An error occurs in our data store', # Redis, DB error\n as_json=True,\n status=STATUS_INTERNAL_ERROR)\n # We have a timeout event here\n if status == -2:\n return get_service_unavailable_response()\n\n\n@app.route('/2.0/azure/container/<uid>/shared-access', methods=['GET', ])\n@routing.login_required\ndef get_azure_container_shared_access_signature(session_info, uid):\n '''\n A shared access signature is a URI that grants restricted access rights to containers, blobs, \n queues, and tables for a specific time interval.\n\n When user is activated, he will be assigned with a Azure container\n\n GET /2.0/azure/container/<container-name>/shared-access?access_token=xxxxxx\n \n + permission: Default to 'rw'\n\n Response\n \n {\n \"body\":{\n \"signature\": \"<string>\"\n },\n \"meta\":{\n \"message\": null,\n \"code\": 200,\n \"detail\": null\n }\n }\n\n @see https://communicate.atlassian.net/browse/FCOR-426\n @see http://msdn.microsoft.com/en-us/library/azure/jj721951.aspx Create and Use a Shared Access Signature\n @see http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-shared-access-signature-part-2/\n '''\n # Standardize the value\n uid = uid.lower()\n # Ensure that user will not abuse our system\n if session_info['uid'] != uid:\n return get_unauthorized_response()\n perm = request.args.get('permission', 'r')\n '''\n if perm not in ('r', 'rw', 'rwd'):\n return get_invalid_param_response('Parameter \"permission\" accepts \"r\" or \"rw\" or \"rwd\" only')\n '''\n return get_response(body={\n 'signature': make_container_sas_url(uid.lower(), perm=perm)\n },\n as_json=True,\n status=STATUS_OK)\n","sub_path":"fscore/api/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55029541","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom flask import Flask, render_template, request, redirect, send_file\nimport csv\n\ndb = {}\n\n\ndef extract_job(url):\n temp_list = []\n # extracting StackOverflow jobs\n result = requests.get(url[0]).text\n soup = BeautifulSoup(result, \"html.parser\")\n cards = soup.find(\"div\", {\"class\": \"listResults\"}).find_all(\"div\", {\"class\": \"grid--cell fl1\"})\n\n for card in cards:\n card_a = card.find(\"h2\", {\"class\": \"mb4 fc-black-800 fs-body3\"})\n title = card.find(\"a\")[\"title\"]\n link = \"https://stackoverflow.com\" + card.find(\"a\")[\"href\"]\n company = card.find(\"h3\", {\"class\": \"fc-black-700 fs-body1 mb4\"}).find(\"span\").text.strip()\n\n temp_list.append({'title': title, 'link': link, 'company': company})\n\n # extracting WeWork jobs \n result = requests.get(url[1]).text\n soup = BeautifulSoup(result, \"html.parser\")\n cards = soup.find(\"section\", {\"class\": \"jobs\"}).find(\"ul\").find_all(\"li\")\n\n for card in cards:\n link = \"https://weworkremotely.com\" + card.find(\"a\")[\"href\"]\n title = card.find(\"span\", {\"class\": \"title\"})\n if title != None:\n title = title.text\n company = card.find(\"span\", {\"class\": \"company\"})\n if company != None:\n company = company.text\n \n temp_list.append({'title': title, 'link': link, 'company': company})\n\n\n # extracting RemoteOk jobs\n result = requests.get(url[2]).text\n soup =BeautifulSoup(result, \"html.parser\")\n cards = soup.find(\"table\", {\"id\": \"jobsboard\"}).find_all(\"tr\", {\"class\": \"job\"})\n for card in cards:\n company = card.find(\"td\", {\"class\": \"company position company_and_position\"}).find(\"a\", {\"itemprop\": \"hiringOrganization\"}).find(\"h3\").text\n title = card.find(\"td\", {\"class\": \"company position company_and_position\"}).find(\"h2\", {\"itemprop\": \"title\"}).text\n link = \"https://remoteok.io\" + card[\"data-href\"]\n\n temp_list.append({'title': title, 'link': link, 'company': company})\n \n return temp_list\n\n\ndef save_to_file(jobs, name):\n file = open(f\"csv/{name}.csv\", mode='w', encoding='utf-8', newline='')\n writer = csv.writer(file)\n writer.writerow([\"title\", \"link\", \"company\"])\n for job in jobs:\n writer.writerow(job.values())\n print(\"All Jobs save safety!\")\n return\n\napp = Flask(\"Final Homework\")\n\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.route(\"/search\")\ndef search():\n name = request.args.get('term').lower()\n url_list = []\n url_list.append(f\"https://stackoverflow.com/jobs?r=true&q={name}\")\n url_list.append(f\"https://weworkremotely.com/remote-jobs/search?term={name}\")\n url_list.append(f\"https://remoteok.io/remote-dev+{name}-jobs\")\n\n if db.get(name):\n job_list = db.get(name)\n else:\n job_list = extract_job(url_list)\n db[name] = job_list\n \n \n return render_template(\"search.html\", job_list=job_list, length=len(job_list), name=name)\n\n@app.route(\"/export\")\ndef export():\n try:\n word = request.args.get('term').lower()\n if not word:\n raise Exception()\n jobs = db.get(word)\n if not jobs:\n raise Exception()\n except:\n redirect(\"/\")\n save_to_file(jobs, word)\n \n return send_file(f\"csv/{word}.csv\", as_attachment=True)\n\napp.run(host=\"127.0.0.1\")","sub_path":"Day13-14/Day13.py","file_name":"Day13.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"561881062","text":"# -*- coding: utf-8 -*-\nimport hashlib # new\nimport logging\nimport re\nfrom datetime import datetime, timedelta\n\nfrom fastapi import Depends, FastAPI, HTTPException # new\nfrom fastapi.security import HTTPBasic, HTTPBasicCredentials # new\nfrom starlette.requests import Request\nfrom starlette.responses import RedirectResponse\nfrom starlette.status import HTTP_401_UNAUTHORIZED # new\nfrom starlette.templating import Jinja2Templates\n\nimport db # new\nfrom auth import auth\nfrom models import Task, User # new\nfrom mycalender import MyCalendar\n\napp = FastAPI(\n title='FastAPIでつくるtoDoアプリケーション',\n description='FastAPIチュートリアル:FastAPI(とstarlette)でシンプルなtoDoアプリを作りましょう.',\n version='0.9 beta'\n)\n\n\ntemplates = Jinja2Templates(directory=\"templates\")\njinja_env = templates.env\n\n\ndef index(request: Request):\n return templates.TemplateResponse('index.html', {'request': request})\n\n\nsecurity = HTTPBasic() \ndef admin(request: Request, credentials: HTTPBasicCredentials = Depends(security)):\n # Basic認証で受け取った情報\n username = auth(credentials)\n password = hashlib.md5(credentials.password.encode()).hexdigest()\n\n \"\"\" [new] 今日の日付と来週の日付\"\"\"\n today = datetime.now()\n next_w = today + timedelta(days=7) # 1週間後の日付\n\n # データベースからユーザ名が一致するデータを取得\n user = db.session.query(User).filter(User.username == username).first()\n task = db.session.query(Task).filter(Task.user_id == user.id).all()\n db.session.close()\n \n\n # 該当ユーザがいない場合\n if user is None or user.password != password:\n error = 'ユーザ名かパスワードが間違っています.'\n raise HTTPException(\n status_code=HTTP_401_UNAUTHORIZED,\n detail=error,\n headers={\"WWW-Authenticate\": \"Basic\"},\n )\n\n \n\n \"\"\" [new] カレンダー関連 \"\"\"\n # カレンダーをHTML形式で取得\n cal = MyCalendar(username,\n {t.deadline.strftime('%Y%m%d'): t.done for t in task}) # 予定がある日付をキーとして渡す\n\n cal = cal.formatyear(today.year, 4) # カレンダーをHTMLで取得\n\n # 直近のタスクだけでいいので、リストを書き換える\n task = [t for t in task if today <= t.deadline <= next_w]\n links = [t.deadline.strftime('/todo/'+username+'/%Y/%m/%d') for t in task] # 直近の予定リンク\n\n return templates.TemplateResponse('admin.html',\n {'request': request,\n 'user': user,\n 'task': task,\n 'links': links,\n 'calender': cal})\n\n\npattern = re.compile(r'\\w{4,20}') # 任意の4~20の英数字を示す正規表現\npattern_pw = re.compile(r'\\w{6,20}') # 任意の6~20の英数字を示す正規表現\npattern_mail = re.compile(r'^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$')\n\n\nasync def register(request: Request):\n if request.method == 'GET':\n return templates.TemplateResponse('register.html',\n {'request': request,\n 'username': '',\n 'error': []})\n\n if request.method == 'POST':\n # POSTデータ\n data = await request.form()\n username = data.get('username')\n password = data.get('password')\n password_tmp = data.get('password_tmp')\n mail = data.get('mail')\n\n # new ここから\n error = []\n\n tmp_user = db.session.query(User).filter(\n User.username == username).first()\n\n # 怒涛のエラー処理\n if tmp_user is not None:\n error.append('同じユーザ名のユーザが存在します。')\n if password != password_tmp:\n error.append('入力したパスワードが一致しません。')\n if pattern.match(username) is None:\n error.append('ユーザ名は4~20文字の半角英数字にしてください。')\n if pattern_pw.match(password) is None:\n error.append('パスワードは6~20文字の半角英数字にしてください。')\n if pattern_mail.match(mail) is None:\n error.append('正しくメールアドレスを入力してください。')\n\n # エラーがあれば登録ページへ戻す\n if error:\n return templates.TemplateResponse('register.html',\n {'request': request,\n 'username': username,\n 'error': error})\n\n # 問題がなければユーザ登録\n user = User(username, password, mail)\n db.session.add(user)\n db.session.commit()\n db.session.close()\n \n\n return templates.TemplateResponse('complete.html',\n {'request': request,\n 'username': username})\n\ndef detail(request: Request, username, year, month, day, credentials: HTTPBasicCredentials = Depends(security)):\n \"\"\" URLパターンは引数で取得可能 \"\"\"\n username_temp = auth(credentials)\n\n if username_temp != username:\n return RedirectResponse('/')\n\n user = db.session.query(User).filter(User.username == username).first()\n task = db.session.query(Task).filter(Task.user_id == user.id).all()\n\n theday = '{}{}{}'.format(year,month.zfill(2),day.zfill(2))\n task = [t for t in task if t.deadline.strftime('%Y%m%d') == theday]\n\n return templates.TemplateResponse('detail.html',\n {'request': request,\n 'username': username,\n 'task':task,\n 'year': year,\n 'month': month,\n 'day': day})\n\n# controllers.py\nasync def done(request: Request, credentials: HTTPBasicCredentials = Depends(security)):\n # 認証OK?\n username = auth(credentials)\n\n # ユーザ情報を取得\n user = db.session.query(User).filter(User.username == username).first()\n\n # ログインユーザのタスクを取得\n task = db.session.query(Task).filter(Task.user_id == user.id).all()\n\n # フォームで受け取ったタスクの終了判定を見て内容を変更する\n data = await request.form()\n t_dones = data.getlist('done[]') # リストとして取得\n\n for t in task:\n if str(t.id) in t_dones: # もしIDが一致すれば \"終了した予定\" とする\n t.done = True\n\n db.session.commit() # update!!\n db.session.close()\n \n\n return RedirectResponse('/admin') # 管理者トップへリダイレクト\n\nasync def add(request: Request, credentials: HTTPBasicCredentials = Depends(security)):\n # 認証\n username = auth(credentials)\n\n # ユーザ情報を取得\n user = db.session.query(User).filter(User.username == username).first()\n \n # フォームからデータを取得\n data = await request.form()\n year = int(data['year'])\n month = int(data['month'])\n day = int(data['day'])\n hour = int(data['hour'])\n minute = int(data['minute'])\n deadline = datetime(year=year, month=month, day=day,\n hour=hour, minute=minute)\n\n # 新しくタスクを生成しコミット\n task = Task(user.id, data['content'], deadline)\n db.session.add(task)\n db.session.commit()\n db.session.close()\n \n\n return RedirectResponse('/admin')\n\ndef delete(request: Request, t_id, credentials: HTTPBasicCredentials = Depends(security)):\n # 認証\n username = auth(credentials)\n \n # ログインユーザ情報を取得\n user = db.session.query(User).filter(User.username == username).first()\n \n # 該当タスクを取得\n task = db.session.query(Task).filter(Task.id == t_id).first()\n \n # もしユーザIDが異なれば削除せずリダイレクト\n if task.user_id != user.id:\n return RedirectResponse('/admin')\n \n # 削除してコミット\n db.session.delete(task)\n db.session.commit()\n db.session.close()\n \n\n return RedirectResponse('/admin')\n","sub_path":"env/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":8459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"555621058","text":"import requests\nfrom dotenv import load_dotenv\nimport os\nimport json \nimport random\nimport datetime\nimport calendar\n\n\ndef oura_ring():\n api_key = os.getenv(\"oura_api_key\")\n\n oura_base_url = \"https://api.ouraring.com/v1/sleep?access_token={}\"\n\n response = requests.get(oura_base_url.format(api_key)).json()\n\n if response['sleep'] : \n day = response['sleep'][-1]['summary_date']\n sleep_night = datetime.datetime.strptime(day, \"%Y-%m-%d\")\n \n oura = {\n 'sleep_date': calendar.day_name[sleep_night.weekday() + 1],\n 'sleep_score': response['sleep'][-1]['score'],\n 'sleep_duration': round((response['sleep'][-1]['total'] / 3600), 2)\n }\n \n else: \n oura = {\n 'sleep_date': \"Date\",\n 'sleep_score': \"0\",\n 'sleep_duration': \"0\"\n }\n\n return oura\n\ndef weather_request(): \n api_key = os.getenv(\"api_key\")\n \n # Give city name \n city_name = \"90250\"\n # base_url variable to store url \n base_url = \"http://api.openweathermap.org/data/2.5/weather?appid={}&zip={}&units=imperial\"\n # get method of requests module \n # return response object \n response = requests.get(base_url.format(api_key,city_name)).json()\n\n weather = {\n 'city': city_name.split(',')[0], \n 'temperature': round(response['main']['temp']), \n 'description': response['weather'][0]['description'],\n 'icon': response['weather'][0]['icon'],\n }\n\n return weather\n\n\ndef quote_request(): \n with open('static/quotes.json') as num:\n data = json.load(num)\n return random.choice(data['quotes']) \n\n\n ","sub_path":"modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"113736433","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, reverse, get_object_or_404\nfrom .models import Category\nfrom django import forms\nfrom django.views.generic import UpdateView,CreateView\nfrom django.urls import reverse_lazy\nfrom django.forms import ModelForm\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit\nfrom django.db import models\nfrom django.core.cache import caches\nfrom likes.models import Like\nfrom django.http import JsonResponse\ncache = caches['default']\nfrom jsonrpc import jsonrpc_method\nimport json\nfrom django.core.serializers import serialize\nfrom time import sleep\nfrom django.views.decorators.csrf import csrf_exempt\n\n\nclass CategoryListForm(forms.Form):\n\n sort = forms.ChoiceField(\n choices=(\n ('name', 'По алфавиту'),\n ('-name', 'С конца алфавита'),\n ('id', 'По порядку'),\n ('-created', 'По дате создания'),\n ),\n required=False\n )\n\n search = forms.CharField(\n required=False\n )\n\n def __init__(self, *args, **kwargs):\n super(CategoryListForm, self).__init__(*args, **kwargs)\n self.fields['sort'].widget.attrs['class'] = 'form-control'\n self.fields['search'].widget.attrs['class'] = 'form-control'\n\n\ndef categories_list(request):\n\n categories = Category.objects.all()\n\n if request.method == 'GET':\n form = CategoryListForm(request.GET)\n if form.is_valid():\n data = form.cleaned_data\n if data['sort']:\n categories = categories.order_by(data['sort'])\n if data['search']:\n categories = categories.filter(name__icontains=data['search'])\n context = {\n 'categories': categories,\n 'form': form,\n }\n return render(request, 'categories/categories_list.html', context)\n\n\nclass CategoryForm(ModelForm):\n class Meta:\n model = Category\n fields = ['name','description','image']\n\n def __init__(self,*args,**kwargs):\n super(CategoryForm,self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.add_input(Submit('submit', 'Сохранить'))\n self.helper.form_tag = False\n\n\nclass CategoryEdit(UpdateView):\n form_class = CategoryForm\n context_object_name = 'category'\n template_name = 'categories/category_edit.html'\n\n def get_queryset(self):\n return Category.objects.all()\n\n def get_success_url(self):\n return reverse('categories:category_detail', kwargs={'pk': self.object.pk})\n\n\nclass CategoryCreate(CreateView):\n form_class = CategoryForm\n context_object_name = 'category'\n template_name = 'categories/category_create.html'\n\n def form_valid(self, form):\n form.instance.author = self.request.user\n return super(CategoryCreate, self).form_valid(form)\n\n def get_success_url(self):\n\n return reverse('categories:category_detail', kwargs={'pk': self.object.pk})\n\n\ndef category_detail(request, pk=None):\n\n category = get_object_or_404(Category, id=pk)\n\n tasks = category.tasks.all()\n tasks = tasks.annotate_everything()\n\n if request.method == 'GET':\n form = TaskListForm(request.GET)\n if form.is_valid():\n data = form.cleaned_data\n if data['sort']:\n tasks = tasks.order_by(data['sort'])\n if data['search']:\n tasks = tasks.filter(name__icontains=data['search'])\n\n for task in tasks:\n cache_key = 'post{}likescount'.format(task.id)\n likes_count = cache.get(cache_key)\n if likes_count is None:\n likes_count = Like.objects.filter(models.Q(task=task.id) & models.Q(is_active=True)).count()\n cache.set(cache_key,likes_count,10)\n task.likes_count = likes_count\n\n context = {\n 'category': category,\n 'tasks': tasks,\n 'form': form,\n }\n return render(request, 'categories/category_detail.html', context)\n\n\nclass TaskListForm(forms.Form):\n\n sort = forms.ChoiceField(\n choices=(\n ('name', 'По алфавиту'),\n ('-viewcount', 'По просмотрам'),\n ('-created', 'По дате создания'),\n ),\n required=False\n )\n\n search = forms.CharField(\n required=False\n )\n\n def __init__(self, *args, **kwargs):\n super(TaskListForm, self).__init__(*args, **kwargs)\n self.fields['sort'].widget.attrs['class'] = 'form-control'\n self.fields['search'].widget.attrs['class'] = 'form-control'\n\n\ndef testfunc(request):\n title = Category.objects.last().name\n return JsonResponse({'category': title})\n\ndef mock():\n sleep(10)\n return 200\n\n\nimport requests\nfrom application.settings import CENTRIFUGE_API_KEY\n\n\ndef publish_category(category):\n command = {\n \"method\": \"publish\",\n \"params\": {\n \"channel\": \"public:screen-updates\",\n \"data\": {\n \"category\": serialize('json', [ category, ], )\n }\n }\n }\n api_key = CENTRIFUGE_API_KEY\n data = json.dumps(command)\n headers = {'Content-type': 'application/json', 'Authorization': 'apikey ' + api_key}\n resp = requests.post(\"http://localhost:9000/api\", data=data, headers=headers)\n print(resp.json())\n\n\n@csrf_exempt\ndef get_all_categories(request):\n categories = Category.objects.all()\n\n categories_json = []\n for category in categories:\n categories_json.append({\n 'id': category.id,\n 'name': category.name,\n 'description': category.description,\n 'tasks_id': [obj for obj in category.tasks.values_list('id', flat=True)],\n })\n\n return JsonResponse(categories_json, safe=False)","sub_path":"project/source/categories/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"237662882","text":"import sublime, sublime_plugin\nimport os, string\nimport re\nimport subprocess\n\nMDE_SEARCH_COMMAND = '/usr/local/bin/rg'\n\nclass ExternalSearch:\n \"\"\"\n Static class to group all external search related functions.\n \"\"\"\n # EXTERNALIZE = '.search_results.zkr' # '' to skip\n\n def __init__(self, search_cmd):\n self.search_cmd=search_cmd\n\n\n def rg_search_in(self, folder, regexp):\n \"\"\"\n Perform an external search for regexp in folder.\n \"\"\"\n print(\"in rg_search_in\")\n print(self.search_cmd)\n args = [self.search_cmd]\n args.extend(['-l', regexp, folder])\n print('args={}'.format(args))\n return self.run(args, folder)\n\n\n def rg_search_for_file(self, folder, glob):\n \"\"\" \n Perform an external search for files matching glob in folder.\n \"\"\"\n print(\"in rg_search_for_file\")\n args = [self.search_cmd]\n args.extend(['-g', glob, '--files', folder])\n print('args={}'.format(args))\n return self.run(args, folder)\n\n\n def run(self, args, folder):\n \"\"\"\n Execute SEARCH_COMMAND to run a search, handle errors & timeouts.\n Return output of stdout as string.\n \"\"\"\n output = b''\n verbose = True\n if verbose or True:\n print('cmd:', ' '.join(args))\n try:\n output = subprocess.check_output(args, shell=False, timeout=10000)\n except subprocess.CalledProcessError as e:\n print('sublime_zk: search unsuccessful:')\n print(e.returncode)\n print(e.cmd)\n for line in e.output.decode('utf-8', errors='ignore').split('\\n'):\n print(' ', line)\n except subprocess.TimeoutExpired:\n print('sublime_zk: search timed out:', ' '.join(args))\n if verbose:\n print(output.decode('utf-8', errors='ignore'))\n return output.decode('utf-8', errors='ignore').replace('\\r', '')","sub_path":"external_search.py","file_name":"external_search.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"591944735","text":"\"\"\" Presets library for artmaker/artmangler scripts \"\"\"\n\nimport random\n\nfrom noisemaker.constants import PointDistribution, ValueDistribution, ValueMask\n\ncircular_dists = PointDistribution.circular_members()\n\ngrid_dists = PointDistribution.grid_members()\n\n\n# Use a lambda to permit re-eval with new seed\nEFFECTS_PRESETS = lambda: {\n \"be-kind-rewind\": {\n \"with_aberration\": random.random() * .02,\n \"with_crt\": True,\n \"with_scan_error\": True,\n \"with_snow\": .625 + random.random() * .125,\n \"with_vhs\": True,\n },\n\n \"bloom\": {\n \"with_bloom\": .333 + random.random() * .333,\n },\n\n \"convolution-feedback\": {\n \"conv_feedback_alpha\": .5,\n \"with_conv_feedback\": 500,\n },\n\n \"corrupt\": {\n \"warp_freq\": [random.randint(4, 7), random.randint(1, 3)],\n \"warp_octaves\": random.randint(3, 5),\n \"warp_range\": .05 + random.random() * .45,\n \"warp_interp\": 0,\n \"with_bloom\": .5 + random.random() * .5,\n \"with_glitch\": random.random() > .125,\n },\n\n \"crt\": {\n \"with_crt\": True,\n \"with_dither\": random.randint(0, 1) * random.random() * .25,\n \"with_scan_error\": random.randint(0, 1),\n \"with_snow\": random.randint(0, 1) * random.random() * .4,\n },\n\n \"density-map\": {\n \"invert\": 1,\n \"with_density_map\": True,\n },\n\n \"erosion-worms\": {\n \"erosion_worms_alpha\": .25 + random.random() * .75,\n \"erosion_worms_contraction\": .5 + random.random() * .5,\n \"erosion_worms_density\": random.randint(25, 100),\n \"erosion_worms_iterations\": random.randint(25, 100),\n \"with_erosion_worms\": True,\n },\n\n \"extract-derivative\": {\n \"deriv\": random.randint(1, 3),\n },\n\n \"falsetto\": {\n \"with_false_color\": True\n },\n\n \"filthy\": {\n \"with_grime\": True,\n \"with_stray_hair\": True,\n },\n\n \"funhouse\": {\n \"warp_freq\": [random.randint(2, 4), random.randint(1, 4)],\n \"warp_octaves\": random.randint(1, 4),\n \"warp_range\": .25 + random.random() * .5,\n },\n\n \"glitchin-out\": {\n \"with_aberration\": random.randint(0, 1) * random.random() * .02,\n \"with_bloom\": random.randint(0, 1) * (.5 + random.random() * .5),\n \"with_crt\": random.random() > .25,\n \"with_dither\": random.randint(0, 1) * random.random() * .25,\n \"with_glitch\": True,\n \"with_scan_error\": random.randint(0, 1),\n },\n\n \"glowing-edges\": {\n \"with_glowing_edges\": 1.0,\n },\n\n \"glyph-map\": {\n \"with_glyph_map\": \"truetype\",\n },\n\n \"light-leak\": {\n \"vignette_brightness\": random.randint(0, 1),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_light_leak\": .5 + random.random() * .5,\n \"with_vignette\": random.randint(0, 1) * (.333 + random.random() * .333),\n },\n\n \"mosaic\": {\n \"point_distrib\": \"random\" if random.randint(0, 1) else [m.value for m in PointDistribution][random.randint(0, len(PointDistribution) - 1)],\n \"point_freq\": 10,\n \"voronoi_alpha\": .75 + random.random() * .25,\n \"with_voronoi\": 5,\n \"with_bloom\": .25 + random.random() * .5,\n },\n\n \"needs-more-jpeg\": {\n \"with_jpeg_decimate\": random.randint(10, 25),\n },\n\n \"noirmaker\": {\n \"post_contrast\": 5,\n \"post_saturation\": 0,\n \"vignette_brightness\": 0,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_dither\": .25 + random.random() * .125,\n \"with_light_leak\": .25 + random.random() * .25,\n \"with_vignette\": .5 + random.random() * .25,\n },\n\n \"normals\": {\n \"with_normal_map\": True,\n },\n\n \"one-art-please\": {\n \"post_contrast\": 1.25,\n \"post_saturation\": .75,\n \"vignette_brightness\": random.random(),\n \"with_bloom\": .333 + random.random() * .333,\n \"with_dither\": .25 + random.random() * .125,\n \"with_light_leak\": .25 + random.random() * .125,\n \"with_vignette\": .25 + random.random() * .125,\n },\n\n \"pop-art\": {\n \"with_pop\": True\n },\n\n \"posterize-outline\": {\n \"posterize_levels\": random.randint(3, 7),\n \"with_outline\": 1,\n },\n\n \"reflect-domain-warp\": {\n \"reflect_range\": .125 + random.random() * 2.5,\n },\n\n \"refract-domain-warp\": {\n \"refract_range\": .125 + random.random() * 2.5,\n },\n\n \"reindex\": {\n \"reindex_range\": .125 + random.random() * 2.5,\n },\n\n \"reverb\": {\n \"reverb_iterations\": random.randint(1, 4),\n \"with_reverb\": random.randint(3, 6),\n },\n\n \"rgb-composite\": {\n \"composite_scale\": [.5, 1, 2, 4][random.randint(0, 3)],\n \"with_composite\": True,\n },\n\n \"ripples\": {\n \"ripple_freq\": random.randint(2, 3),\n \"ripple_kink\": 2.5 + random.random() * 1.25,\n \"ripple_range\": .05 + random.random() * .25,\n },\n\n \"shadows\": {\n \"with_shadow\": .5 + random.random() * .5,\n \"with_vignette\": .5 + random.random() * .5,\n \"vignette_brightness\": 0,\n },\n\n \"shake-it-like\": {\n \"with_frame\": True,\n },\n\n \"snow\": {\n \"with_dither\": .05 + random.random() * .025,\n \"with_snow\": .333 + random.random() * .333,\n },\n\n \"sobel-operator\": {\n \"invert\": random.randint(0, 1),\n \"with_sobel\": random.randint(1, 3),\n },\n\n \"swerve-h\": {\n \"warp_freq\": [random.randint(3, 6), 1],\n \"warp_octaves\": 1,\n \"warp_range\": 1.0 + random.random(),\n },\n\n \"swerve-v\": {\n \"warp_freq\": [1, random.randint(3, 6)],\n \"warp_octaves\": 1,\n \"warp_range\": 1.0 + random.random(),\n },\n\n \"tensor-tone\": {\n \"glyph_map_colorize\": random.randint(0, 1),\n \"with_glyph_map\": \"halftone\",\n },\n\n \"voronoid\": {\n \"point_freq\": random.randint(4, 10),\n \"voronoi_func\": random.randint(1, 3),\n \"voronoi_refract\": .5 + random.random() * .5,\n \"voronoi_nth\": random.randint(0, 3),\n \"with_voronoi\": [1, 3, 6][random.randint(0, 2)]\n },\n\n \"vortex\": {\n \"vortex_range\": random.randint(16, 48),\n },\n\n \"wormhole-xtreme\": {\n \"with_wormhole\": True,\n \"wormhole_stride\": .025 + random.random() * .05,\n \"wormhole_kink\": .5 + random.random(),\n },\n\n \"worms\": {\n \"with_worms\": random.randint(1, 4),\n \"worms_alpha\": .75 + random.random() * .25,\n \"worms_density\": 500,\n \"worms_duration\": 1,\n \"worms_kink\": 2.5,\n \"worms_stride\": 2.5,\n \"worms_stride_deviation\": 2.5,\n },\n\n}\n\n\nPRESETS = lambda: {\n \"2d-chess\": {\n \"corners\": True,\n \"distrib\": \"ones\",\n \"freq\": 8,\n \"mask\": \"chess\",\n \"point_corners\": True,\n \"point_distrib\": \"square\",\n \"point_freq\": 8,\n \"spline_order\": 0,\n \"voronoi_alpha\": 0.5 + random.random() * .5,\n \"voronoi_nth\": random.randint(0, 1) * random.randint(0, 63),\n \"with_voronoi\": 2 if random.randint(0, 1) else random.randint(1, 5),\n },\n\n \"acid-droplets\": {\n \"freq\": random.randint(12, 18),\n \"hue_range\": 0,\n \"invert\": 1,\n \"mask\": \"sparse\",\n \"octaves\": random.randint(2, 3),\n \"post_hue_rotation\": random.random(),\n \"post_saturation\": .25,\n \"reflect_range\": .75 + random.random() * .75,\n \"ridges\": random.randint(0, 1),\n \"saturation\": 1.5,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_density_map\": True,\n \"with_shadow\": 1,\n \"with_dither\": .075 * random.random() * .075,\n },\n\n \"acid-grid\": {\n \"invert\": random.randint(0, 1),\n \"lattice_drift\": random.randint(0, 1),\n \"point_distrib\": [m.value for m in grid_dists][random.randint(0, len(grid_dists) - 1)],\n \"point_freq\": 4,\n \"point_generations\": 2,\n \"voronoi_alpha\": .333 + random.random() * .333,\n \"voronoi_refract\": 0.5,\n \"voronoi_func\": 1,\n \"voronoi_nth\": random.randint(1, 4),\n \"warp_freq\": random.randint(2, 4),\n \"warp_range\": .125 + random.random() * .125,\n \"warp_octaves\": 1,\n \"with_bloom\": 0.5,\n \"with_sobel\": 1,\n \"with_voronoi\": 2,\n },\n\n \"acid-wash\": {\n \"corners\": True,\n \"freq\": 2,\n \"hue_range\": 1,\n \"point_distrib\": ([m.value for m in circular_dists])[random.randint(0, len(circular_dists) - 1)],\n \"point_freq\": random.randint(6, 10),\n \"post_ridges\": True,\n \"ridges\": True,\n \"saturation\": .25,\n \"voronoi_alpha\": .333 + random.random() * .333,\n \"warp_range\": .5,\n \"warp_octaves\": 8,\n \"with_reverb\": 1,\n \"with_shadow\": 1,\n \"with_voronoi\": 2,\n },\n\n \"activation-signal\": {\n \"distrib\": \"ones\",\n \"freq\": 4,\n \"mask\": \"white_bear\",\n \"rgb\": random.randint(0, 1),\n \"spline_order\": 0,\n \"with_aberration\": .005 + random.random() * .005,\n \"with_crt\": True,\n \"with_glitch\": random.randint(0, 1),\n \"with_scan_error\": random.randint(0, 1),\n \"with_snow\": .25 + random.random() * .25,\n \"with_vhs\": random.randint(0, 1),\n },\n\n \"alien-terrain-multires\": {\n \"deriv\": 1,\n \"deriv_alpha\": .333 + random.random() * .333,\n \"freq\": random.randint(4, 8),\n \"invert\": random.randint(0, 1),\n \"lattice_drift\": 1,\n \"octaves\": 10,\n \"post_saturation\": .075 + random.random() * .075,\n \"saturation\": 2,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_shadow\": .75 + random.random() * .25,\n },\n\n \"alien-terrain-worms\": {\n \"deriv\": 1,\n \"deriv_alpha\": 0.25 + random.random() * .125,\n \"erosion_worms_alpha\": .025 + random.random() * .015,\n \"erosion_worms_contraction\": .5 + random.random() * .25,\n \"erosion_worms_density\": random.randint(150, 200),\n \"erosion_worms_iterations\": random.randint(50, 75),\n \"erosion_worms_inverse\": True,\n \"erosion_worms_xy_blend\": .42,\n \"freq\": random.randint(3, 5),\n \"hue_rotation\": .875,\n \"hue_range\": .25 + random.random() * .25,\n \"octaves\": 8,\n \"point_freq\": 10,\n \"post_contrast\": 1.25,\n \"post_saturation\": .25,\n \"ridges\": True,\n \"saturation\": 2,\n \"voronoi_alpha\": 0.125 + random.random() * .125,\n \"voronoi_refract\": 0.25 + random.random() * .25,\n \"with_bloom\": 0.25 + random.random() * .125,\n \"with_dither\": .125 + random.random() * .125,\n \"with_erosion_worms\": True,\n \"with_shadow\": .333,\n \"with_voronoi\": 6,\n },\n\n \"alien-transmission\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(100, 200),\n \"invert\": random.randint(0, 1),\n \"mask\": [m.value for m in ValueMask.procedural_members()][random.randint(0, len(ValueMask.procedural_members()) - 1)],\n \"reindex_range\": .02 + random.random() * .02,\n \"spline_order\": 2,\n \"with_aberration\": .005 + random.random() * .005,\n \"with_crt\": True,\n \"with_glitch\": True,\n \"with_scan_error\": True,\n },\n\n \"analog-glitch\": {\n \"deriv\": 2,\n \"distrib\": \"ones\",\n \"freq\": 13 * random.randint(10, 25),\n \"mask\": [\"hex\", \"lcd\", \"fat_lcd\"][random.randint(0, 2)],\n \"spline_order\": 2,\n },\n\n \"anticounterfeit\": {\n \"freq\": 2,\n \"invert\": 1,\n \"point_freq\": 1,\n \"voronoi_refract\": 1,\n \"with_dither\": .125,\n \"with_fibers\": True,\n \"with_voronoi\": 6,\n \"with_watermark\": True,\n \"with_wormhole\": True,\n \"wormhole_kink\": 6,\n \"wormhole_stride\": .25,\n },\n\n \"are-you-human\": {\n \"distrib\": \"ones\",\n \"freq\": 15,\n \"hue_range\": random.random() * .25,\n \"hue_rotation\": random.random(),\n \"mask\": \"truetype\",\n \"octaves\": 8,\n \"saturation\": random.random() * .125,\n \"spline_order\": 0,\n \"warp_freq\": 2,\n \"warp_interp\": 3,\n \"warp_octaves\": 1,\n \"warp_range\": 1,\n \"with_aberration\": .0075 + random.random() * .0075,\n \"with_density_map\": True,\n \"with_dither\": .25,\n \"with_snow\": .333 + random.random() * .333,\n },\n\n \"aztec-waffles\": {\n \"freq\": 7,\n \"invert\": random.randint(0, 1),\n \"point_freq\": random.randint(2, 4),\n \"point_generations\": 2,\n \"point_distrib\": \"circular\",\n \"posterize_levels\": random.randint(6, 18),\n \"reflect_range\": random.random() * 2,\n \"spline_order\": 0,\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(2, 4),\n \"with_outline\": 3,\n \"with_voronoi\": random.randint(1, 5),\n },\n\n \"band-together\": {\n \"freq\": random.randint(6, 12),\n \"reindex_range\": random.randint(8, 12),\n \"warp_range\": 1,\n \"warp_octaves\": 8,\n \"warp_freq\": 2,\n \"with_shadow\": .25 + random.random() * .25,\n },\n\n \"berkeley\": {\n \"freq\": random.randint(12, 16),\n \"octaves\": 8,\n \"post_ridges\": True,\n \"reindex_range\": .375 + random.random() * .125,\n \"rgb\": random.randint(0, 1),\n \"ridges\": True,\n \"sin\": 2 * random.random() * 2,\n \"with_shadow\": 1,\n },\n\n \"bit-by-bit\": {\n \"distrib\": \"ones\",\n \"freq\": 6 * random.randint(25, 125),\n \"mask\": [\"binary\", \"hex\", \"numeric\"][random.randint(0, 2)],\n \"spline_order\": 1,\n \"with_bloom\": .25 + random.random() * .125,\n \"with_crt\": True,\n \"with_scan_error\": True,\n \"with_shadow\": random.random(),\n },\n\n \"bitmask\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(13, 27),\n \"mask\": [m.value for m in ValueMask.procedural_members()][random.randint(0, len(ValueMask.procedural_members()) - 1)],\n \"octaves\": random.randint(2, 6),\n \"ridges\": True,\n \"spline_order\": 2,\n \"with_bloom\": .25 + random.random() * .25,\n },\n\n \"blacklight-fantasy\": {\n \"invert\": 1,\n \"post_hue_rotation\": -.125,\n \"posterize_levels\": 3,\n \"rgb\": True,\n \"voronoi_func\": random.randint(1, 3),\n \"voronoi_nth\": random.randint(0, 3),\n \"voronoi_refract\": 1.0 + random.random() * 2.5,\n \"warp_octaves\": random.randint(1, 4),\n \"warp_range\": random.randint(0, 1) * random.random() * 2.0,\n \"with_bloom\": .5 + random.random() * .5,\n \"with_dither\": .075 + random.random() * .075,\n \"with_sobel\": 2,\n \"with_voronoi\": random.randint(1, 7),\n },\n\n \"blobby\": {\n \"deriv\": random.randint(1, 3),\n \"distrib\": \"uniform\",\n \"freq\": random.randint(6, 12) * 2,\n \"saturation\": .25 + random.random() * .5,\n \"hue_range\": .25 + random.random() * .5,\n \"hue_rotation\": random.randint(0, 1) * random.random(),\n \"invert\": 1,\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"outline\": 1,\n \"reverb_iterations\": random.randint(2, 4),\n \"spline_order\": random.randint(2, 3),\n \"warp_freq\": random.randint(6, 12),\n \"warp_interp\": random.randint(1, 3),\n \"warp_octaves\": random.randint(2, 4),\n \"warp_range\": .05 + random.random() * .1,\n \"with_reverb\": random.randint(1, 3),\n \"with_shadow\": 1,\n },\n\n \"blockchain-stock-photo-background\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(20, 30) * 15,\n \"mask\": [\"truetype\", \"binary\", \"hex\", \"numeric\"][random.randint(0, 3)],\n \"spline_order\": random.randint(0, 2),\n \"with_aberration\": .01 + random.random() * .01,\n \"with_crt\": True,\n \"with_glitch\": True,\n \"with_scan_error\": True,\n \"with_vignette\": 1.0,\n },\n\n \"branemelt\": {\n \"freq\": random.randint(6, 12),\n \"octaves\": 8,\n \"post_reflect_range\": .075 + random.random() * .025,\n \"sin\": random.randint(32, 64),\n },\n\n \"branewaves\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(16, 24) * 2,\n \"mask\": [m.value for m in ValueMask.grid_members()][random.randint(0, len(ValueMask.grid_members()) - 1)],\n \"ridges\": True,\n \"ripple_freq\": 2,\n \"ripple_kink\": 1.5 + random.random() * 2,\n \"ripple_range\": .075 + random.random() * .075,\n \"with_bloom\": .333 + random.random() * .333,\n },\n\n \"bringing-hexy-back\": {\n \"lattice_drift\": 1,\n \"point_distrib\": \"v_hex\" if random.randint(0, 1) else \"v_hex\",\n \"point_freq\": 10,\n \"post_deriv\": random.randint(0, 1) * random.randint(1, 3),\n \"voronoi_alpha\": 0.5,\n \"voronoi_refract\": random.randint(0, 1) * random.random(),\n \"warp_octaves\": 1,\n \"warp_range\": random.random() * .5,\n \"with_bloom\": 0.5,\n \"with_voronoi\": 5,\n },\n\n \"broken\": {\n \"freq\": random.randint(3, 4),\n \"lattice_drift\": 2,\n \"octaves\": random.randint(3, 4),\n \"post_brightness\": .125,\n \"post_saturation\": .25,\n \"posterize_levels\": 3,\n \"reindex_range\": random.randint(3, 4),\n \"rgb\": True,\n \"with_glowing_edges\": 1,\n \"with_dither\": .125 + random.random() * .075,\n },\n\n \"bubble-machine\": {\n \"corners\": True,\n \"distrib\": \"uniform\",\n \"freq\": random.randint(3, 6) * 2,\n \"invert\": random.randint(0, 1),\n \"mask\": [\"h_hex\", \"v_hex\"][random.randint(0, 1)],\n \"posterize_levels\": random.randint(8, 16),\n \"reverb_iterations\": random.randint(1, 3),\n \"spline_order\": random.randint(1, 3),\n \"with_reverb\": random.randint(3, 5),\n \"with_outline\": 1,\n \"with_wormhole\": True,\n \"wormhole_kink\": 1.0 + random.random() * 5,\n \"wormhole_stride\": .25 + random.random() * .75,\n },\n\n \"bubble-multiverse\": {\n \"point_freq\": 10,\n \"post_hue_rotation\": random.random(),\n \"post_refract_range\": .125 + random.random() * .05,\n \"voronoi_refract\": 1.25 + random.random() * .5,\n \"with_bloom\": .5 * random.random() * .25,\n \"with_density_map\": True,\n \"with_shadow\": 1.0,\n \"with_voronoi\": 6,\n },\n\n \"cell-reflect\": {\n \"invert\": random.randint(0, 1),\n \"point_freq\": random.randint(2, 3),\n \"post_deriv\": random.randint(1, 3),\n \"post_reflect_range\": random.randint(2, 4),\n \"post_saturation\": .5,\n \"voronoi_alpha\": .333 + random.random() * .333,\n \"voronoi_func\": random.randint(1, 3),\n \"voronoi_nth\": random.randint(0, 1),\n \"with_density_map\": True,\n \"with_dither\": .075 + random.random() * .075,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_voronoi\": 2,\n },\n\n \"cell-refract\": {\n \"point_freq\": random.randint(3, 4),\n \"post_ridges\": True,\n \"reindex_range\": 1.0 + random.random() * 1.5,\n \"rgb\": random.randint(0, 1),\n \"ridges\": True,\n \"voronoi_refract\": random.randint(8, 12),\n \"with_voronoi\": 1,\n },\n\n \"cell-refract-2\": {\n \"invert\": 1,\n \"point_freq\": random.randint(2, 3),\n \"post_deriv\": random.randint(0, 3),\n \"post_refract_range\": random.randint(2, 4),\n \"post_saturation\": .5,\n \"voronoi_alpha\": .333 + random.random() * .333,\n \"voronoi_func\": random.randint(1, 3),\n \"voronoi_inverse\": random.randint(0, 1),\n \"voronoi_nth\": random.randint(0, 1),\n \"with_density_map\": True,\n \"with_dither\": .075 + random.random() * .075,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_voronoi\": 2,\n },\n\n \"cell-worms\": {\n \"freq\": random.randint(3, 7),\n \"hue_range\": .125 + random.random() * .875,\n \"invert\": 1,\n \"octaves\": 3,\n \"point_distrib\": random.randint(0, 1) * ([m.value for m in PointDistribution])[random.randint(0, len(PointDistribution) - 1)],\n \"point_freq\": random.randint(2, 4),\n \"post_hue_rotation\": random.random(),\n \"saturation\": .125 + random.random() * .25,\n \"voronoi_alpha\": .75,\n \"voronoi_inverse\": random.randint(0, 1),\n \"voronoi_func\": random.randint(1, 3),\n \"voronoi_nth\": random.randint(0, 3),\n \"with_bloom\": .25 + random.random() * .25,\n \"with_dither\": .125,\n \"with_density_map\": True,\n \"with_shadow\": .75 + random.random() * .25,\n \"with_voronoi\": [1, 2, 4, 5, 6][random.randint(0, 4)],\n \"with_worms\": random.randint(1, 5),\n \"worms_alpha\": .875,\n \"worms_density\": 1500,\n \"worms_kink\": random.randint(16, 32),\n },\n\n \"chiral\": {\n \"corners\": True,\n \"freq\": 2,\n \"invert\": 1,\n \"point_freq\": 1,\n \"post_reindex_range\": .05,\n \"post_refract_range\": random.randint(24, 48),\n \"voronoi_alpha\": .95,\n \"voronoi_func\": random.randint(1, 3),\n \"with_density_map\": True,\n \"with_sobel\": random.randint(1, 3),\n \"with_voronoi\": 6,\n },\n\n \"circulent\": {\n \"corners\": True,\n \"freq\": 2,\n \"invert\": 1,\n \"point_distrib\": ([\"spiral\"] + [m.value for m in circular_dists])[random.randint(0, len(circular_dists))],\n \"point_corners\": True,\n \"point_freq\": random.randint(4, 8),\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"voronoi_nth\": random.randint(1, 4),\n \"with_reverb\": random.randint(1, 3),\n \"with_voronoi\": random.randint(1, 4),\n \"with_wormhole\": True,\n \"wormhole_kink\": random.randint(3, 6),\n \"wormhole_stride\": .05 + random.random() * .05,\n },\n\n \"cloverleaf\": {\n \"corners\": True,\n \"freq\": 2,\n \"point_distrib\": ([m.value for m in PointDistribution])[random.randint(0, len(PointDistribution) - 1)],\n \"point_freq\": random.randint(4, 10),\n \"with_reverb\": random.randint(0, 3),\n \"voronoi_refract\": .25 + random.random() * .375,\n \"with_voronoi\": 7,\n },\n\n \"conference\": {\n \"distrib\": \"ones\",\n \"freq\": 5 * random.randint(15, 30),\n \"invert\": random.randint(0, 1),\n \"mask\": \"halftone\",\n \"spline_order\": 2,\n \"with_sobel\": 1,\n },\n\n \"cool-water\": {\n \"distrib\": \"uniform\",\n \"freq\": 16,\n \"hue_range\": .05 + random.random() * .05,\n \"hue_rotation\": .5125 + random.random() * .025,\n \"lattice_drift\": 1,\n \"octaves\": 4,\n \"reflect_range\": .333 + random.random() * .333,\n \"refract_range\": .5 + random.random() * .25,\n \"ripple_range\": .01 + random.random() * .005,\n \"ripple_kink\": random.randint(2, 4),\n \"ripple_freq\": random.randint(2, 4),\n \"warp_range\": .125 + random.random() * .125,\n \"warp_freq\": random.randint(2, 3),\n \"with_bloom\": .333 + random.random() * .333,\n },\n\n \"corner-case\": {\n \"corners\": True,\n \"freq\": random.randint(2, 4),\n \"lattice_drift\": random.randint(0, 1),\n \"octaves\": 8,\n \"ridges\": True,\n \"saturation\": random.randint(0, 1) * random.random() * .25,\n \"spline_order\": 0,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_density_map\": True,\n \"with_dither\": .25,\n },\n\n \"crop-spirals\": {\n \"distrib\": \"laplace\",\n \"corners\": False,\n \"freq\": random.randint(4, 6) * 2,\n \"hue_range\": 1,\n \"saturation\": .75,\n \"mask\": [\"h_hex\", \"v_hex\"][random.randint(0, 1)],\n \"reindex_range\": .1 + random.random() * .1,\n \"spline_order\": 2,\n \"with_reverb\": random.randint(2, 4),\n \"with_worms\": 3,\n \"worms_alpha\": .9 + random.random() * .1,\n \"worms_density\": 500,\n \"worms_duration\": 1,\n \"worms_kink\": 2 + random.random(),\n \"worms_stride\": .333 + random.random() * .333,\n \"worms_stride_deviation\": .04 + random.random() * .04,\n },\n\n \"cubic\": {\n \"freq\": random.randint(2, 5),\n \"point_distrib\": \"concentric\",\n \"point_freq\": random.randint(3, 5),\n \"voronoi_alpha\": 0.25 + random.random() * .5,\n \"voronoi_nth\": random.randint(2, 8),\n \"with_bloom\": 0.25 + random.random() * .5,\n \"with_outline\": 1,\n \"with_voronoi\": random.randint(1, 2),\n },\n\n \"cyclic-dilation\": {\n \"with_voronoi\": 2,\n \"post_reindex_range\": random.randint(4, 6),\n \"freq\": random.randint(24, 48),\n \"hue_range\": .25 + random.random() * 1.25,\n },\n\n \"deadbeef\": {\n \"distrib\": \"ones\",\n \"freq\": 6 * random.randint(9, 24),\n \"mask\": \"hex\",\n \"spline_order\": 0,\n \"warp_freq\": [random.randint(4, 7), random.randint(1, 3)],\n \"warp_octaves\": random.randint(3, 5),\n \"warp_range\": .05 + random.random() * .45,\n \"with_bloom\": .25 + random.random() * .25,\n },\n\n \"deadlock\": {\n \"hue_range\": random.random(),\n \"hue_rotation\": random.random(),\n \"saturation\": random.random(),\n \"point_corners\": random.randint(0, 1),\n \"point_distrib\": [m.value for m in grid_dists][random.randint(0, len(grid_dists) - 1)],\n \"point_drift\": random.randint(0, 1) * random.random(),\n \"point_freq\": 4,\n \"point_generations\": 2,\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(0, 15),\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"sin\": random.random() * 2,\n \"with_outline\": 3,\n \"with_voronoi\": 1,\n },\n\n \"death-star-plans\": {\n \"channels\": 1,\n \"invert\": 1,\n \"octaves\": 1,\n \"point_freq\": random.randint(2, 4),\n \"post_refract_range\": random.randint(0, 1),\n \"posterize_levels\": random.randint(3, 5),\n \"voronoi_alpha\": 1,\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(1, 3),\n \"with_aberration\": random.random() * .01,\n \"with_crt\": True,\n \"with_scan_error\": True,\n \"with_sobel\": 2,\n \"with_voronoi\": 1,\n },\n\n \"defocus\": {\n \"freq\": 12,\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"octaves\": 5,\n \"sin\": 10,\n \"with_bloom\": 0.5,\n },\n\n \"density-wave\": {\n \"corners\": True,\n \"freq\": random.randint(2, 4),\n \"reflect_range\": random.randint(4, 12),\n \"saturation\": 0,\n \"with_density_map\": True,\n \"with_shadow\": 1,\n },\n\n \"different\": {\n \"freq\": random.randint(8, 12),\n \"octaves\": 8,\n \"reflect_range\": 1.5 + random.random(),\n \"reindex_range\": .25 + random.random() * .25,\n \"sin\": random.randint(15, 25),\n \"warp_range\": .075 * random.random() * .075,\n },\n\n \"diffusion-feedback\": {\n \"corners\": True,\n \"distrib\": \"normal\",\n \"freq\": 8,\n \"dla_padding\": 5,\n \"invert\": 1,\n \"point_distrib\": \"square\",\n \"point_freq\": 1,\n \"saturation\": 0,\n \"with_aberration\": .005 + random.random() * .005,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_conv_feedback\": 125,\n \"with_density_map\": True,\n \"with_dla\": .75,\n \"with_sobel\": 3,\n \"with_vignette\": .75,\n },\n\n \"distance\": {\n \"deriv\": random.randint(1, 3),\n \"distrib\": \"exp\",\n \"lattice_drift\": 1,\n \"octaves\": 8,\n \"saturation\": .06125 + random.random() * .125,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_shadow\": 1,\n },\n\n \"dla-cells\": {\n \"dla_padding\": random.randint(2, 8),\n \"hue_range\": random.random() * 1.5,\n \"point_distrib\": [m.value for m in PointDistribution][random.randint(0, len(PointDistribution) - 1)],\n \"point_freq\": random.randint(2, 8),\n \"voronoi_alpha\": random.random(),\n \"with_bloom\": .25 + random.random() * .25,\n \"with_dla\": .5 + random.random() * .5,\n \"with_voronoi\": random.randint(0, 1) * random.randint(1, 5),\n },\n\n \"dla-forest\": {\n \"dla_padding\": random.randint(2, 8),\n \"reverb_iterations\": random.randint(2, 4),\n \"with_bloom\": .25 + random.random() * .25,\n \"with_dla\": 1,\n \"with_reverb\": random.randint(3, 6),\n },\n\n \"domain-warp\": {\n \"octaves\": 8,\n \"post_refract_range\": .5 + random.random() * .5,\n \"ridges\": True,\n },\n\n \"ears\": {\n \"freq\": 22,\n \"distrib\": \"uniform\",\n \"hue_range\": random.random() * 2.5,\n \"mask\": [m.value for m in ValueMask if m.name != \"chess\"][random.randint(0, len(ValueMask) - 2)],\n \"with_worms\": 3,\n \"worms_alpha\": .875,\n \"worms_density\": 188.07,\n \"worms_duration\": 3.20,\n \"worms_stride\": 0.40,\n \"worms_stride_deviation\": 0.31,\n \"worms_kink\": 6.36,\n },\n\n \"electric-worms\": {\n \"blur\": 1,\n \"freq\": random.randint(3, 6),\n \"invert\": 1,\n \"lattice_drift\": 1,\n \"point_freq\": 10,\n \"voronoi_alpha\": .25 + random.random() * .25,\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(0, 3),\n \"with_bloom\": .125 + random.random() * .125,\n \"with_density_map\": True,\n \"with_glowing_edges\": .75 + random.random() * .25,\n \"with_voronoi\": 2,\n \"with_worms\": 5,\n \"worms_alpha\": .666 + random.random() * .333,\n \"worms_density\": 1000,\n \"worms_duration\": 1,\n \"worms_kink\": random.randint(7, 9),\n \"worms_stride_deviation\": 16,\n },\n\n \"emo\": {\n \"distrib\": \"ones\",\n \"freq\": 13 * random.randint(15, 30),\n \"mask\": \"emoji\",\n \"spline_order\": random.randint(0, 2),\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_refract\": .25 + random.random() * .5,\n \"with_voronoi\": 1,\n },\n\n \"eyes\": {\n \"corners\": True,\n \"distrib\": [\"ones\", \"uniform\"][random.randint(0, 1)],\n \"freq\": 12 * random.randint(1, 2),\n \"hue_range\": random.random(),\n \"invert\": 1,\n \"mask\": [m.value for m in ValueMask if m.name != \"chess\"][random.randint(0, len(ValueMask) - 2)],\n \"ridges\": True,\n \"spline_order\": random.randint(2, 3),\n \"with_outline\": 1,\n \"warp_freq\": 2,\n \"warp_octaves\": 1,\n \"warp_range\": random.randint(1, 4),\n \"with_shadow\": 1,\n },\n\n \"fake-fractal-flame\": {\n \"hue_range\": random.random(),\n \"invert\": 1,\n \"octaves\": random.randint(3, 4),\n \"post_hue_rotation\": random.random(),\n \"post_saturation\": .25 + random.random() * .25,\n \"ridges\": True,\n \"with_aberration\": .0075 + random.random() * .0075,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_density_map\": True,\n \"with_dither\": .075,\n \"with_shadow\": .75 + random.random() * .25,\n \"with_worms\": 5,\n \"worms_alpha\": .975 + random.random() * .025,\n \"worms_density\": 1500,\n \"worms_stride\": random.randint(150, 350),\n },\n\n \"fast-eddies\": {\n \"hue_range\": .25 + random.random() * .75,\n \"hue_rotation\": random.random(),\n \"invert\": 1,\n \"octaves\": random.randint(1, 3),\n \"point_freq\": random.randint(2, 10),\n \"post_contrast\": 1.5,\n \"post_saturation\": .125 + random.random() * .375,\n \"ridges\": random.randint(0, 1),\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"voronoi_refract\": 2.0,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_density_map\": True,\n \"with_dither\": .175 + random.random() * .175,\n \"with_shadow\": .75 + random.random() * .25,\n \"with_voronoi\": 6,\n \"with_worms\": 4,\n \"worms_alpha\": .5 + random.random() * .5,\n \"worms_density\": 1000,\n \"worms_duration\": 6,\n \"worms_kink\": random.randint(125, 375),\n },\n\n \"figments\": {\n \"freq\": 2,\n \"hue_range\": 2,\n \"lattice_drift\": 1,\n \"octaves\": 3,\n \"voronoi_refract\": 1,\n \"warp_freq\": random.randint(2, 4),\n \"warp_range\": 1,\n \"with_wormhole\": True,\n \"with_bloom\": 1,\n \"with_voronoi\": 6,\n \"wormhole_stride\": .05,\n \"wormhole_kink\": 4,\n },\n\n \"financial-district\": {\n \"point_freq\": 2,\n \"voronoi_func\": 2,\n \"voronoi_nth\": random.randint(1, 3),\n \"with_voronoi\": 5,\n },\n\n \"flowbie\": {\n \"freq\": random.randint(2, 4),\n \"octaves\": random.randint(1, 2),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_wormhole\": True,\n \"with_worms\": random.randint(1, 3),\n \"refract_range\": random.randint(0, 3),\n \"wormhole_alpha\": .333 + random.random() * .333,\n \"wormhole_kink\": .25 + random.random() * .25,\n \"wormhole_stride\": random.random() * 2.5,\n \"worms_alpha\": .125 + random.random() * .125,\n \"worms_stride\": .25 + random.random() * .25,\n },\n\n \"fractal-forms\": {\n \"freq\": random.randint(2, 3),\n \"hue_range\": random.random() * 3,\n \"invert\": 1,\n \"octaves\": random.randint(3, 4),\n \"saturation\": .05,\n \"with_bloom\": .75 + random.random() * .25,\n \"with_density_map\": True,\n \"with_dither\": .125,\n \"with_shadow\": .5 + random.random() * .5,\n \"with_worms\": 4,\n \"worms_alpha\": .9 + random.random() * .1,\n \"worms_density\": random.randint(750, 1500),\n \"worms_kink\": random.randint(256, 512),\n },\n\n \"fractal-smoke\": {\n \"freq\": random.randint(2, 4),\n \"hue_range\": random.random() * 3,\n \"invert\": 1,\n \"octaves\": random.randint(2, 4),\n \"saturation\": .05,\n \"with_bloom\": .75 + random.random() * .25,\n \"with_density_map\": True,\n \"with_dither\": .125,\n \"with_shadow\": .5 + random.random() * .5,\n \"with_worms\": 4,\n \"worms_alpha\": .9 + random.random() * .1,\n \"worms_density\": random.randint(750, 1500),\n \"worms_stride\": random.randint(128, 256),\n },\n\n \"fractile\": {\n \"corners\": True,\n \"freq\": 2,\n \"point_distrib\": [m.value for m in grid_dists][random.randint(0, len(grid_dists) - 1)],\n \"point_freq\": random.randint(2, 10),\n \"reverb_iterations\": random.randint(2, 4),\n \"voronoi_alpha\": min(.75 + random.random() * .5, 1),\n \"voronoi_func\": random.randint(1, 3),\n \"voronoi_nth\": random.randint(0, 3),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_reverb\": random.randint(4, 8),\n \"with_voronoi\": random.randint(1, 5),\n },\n\n \"fundamentals\": {\n \"freq\": random.randint(3, 5),\n \"invert\": 1,\n \"point_freq\": random.randint(3, 5),\n \"post_deriv\": random.randint(1, 3),\n \"post_saturation\": .333 + random.random() * .333,\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(3, 5),\n \"voronoi_refract\": .125 + random.random() * .125,\n \"with_density_map\": True,\n \"with_voronoi\": 2,\n \"with_dither\": .175 + random.random() * .175,\n },\n\n \"funky-glyphs\": {\n \"distrib\": [\"ones\", \"uniform\"][random.randint(0, 1)],\n \"freq\": 20 * random.randint(1, 3),\n \"mask\": [\n \"binary\",\n \"numeric\",\n \"hex\",\n \"lcd\",\n \"lcd_binary\",\n \"fat_lcd\",\n \"fat_lcd_binary\",\n \"fat_lcd_numeric\",\n \"fat_lcd_hex\"\n ][random.randint(0, 8)],\n \"octaves\": random.randint(1, 2),\n \"post_refract_range\": .125 + random.random() * .125,\n \"spline_order\": random.randint(1, 3),\n },\n\n \"fuzzy-squares\": {\n \"corners\": True,\n \"distrib\": \"ones\",\n \"freq\": random.randint(6, 24) * 2,\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"post_contrast\": 1.5,\n \"spline_order\": 1,\n \"with_worms\": 5,\n \"worms_alpha\": 1,\n \"worms_density\": 1000,\n \"worms_duration\": 2.0,\n \"worms_stride\": .75 + random.random() * .75,\n \"worms_stride_deviation\": random.random(),\n \"worms_kink\": 1 + random.random() * 5.0,\n },\n\n \"fuzzy-swirls\": {\n \"freq\": random.randint(2, 32),\n \"hue_range\": random.random() * 2,\n \"point_freq\": random.randint(8, 10),\n \"spline_order\": random.randint(1, 3),\n \"voronoi_alpha\": 0.5 * random.random() * .5,\n \"with_voronoi\": 6,\n \"with_worms\": random.randint(1, 4),\n \"worms_density\": 64,\n \"worms_duration\": 1,\n \"worms_kink\": 25,\n },\n\n \"fat-led\": {\n \"distrib\": \"ones\",\n \"freq\": 10 * random.randint(25, 40),\n \"mask\": [\"fat_lcd\", \"fat_lcd_binary\", \"fat_lcd_numeric\", \"fat_lcd_hex\"][random.randint(0, 3)],\n \"spline_order\": random.randint(1, 2),\n \"with_bloom\": .125 + random.random() * .125,\n },\n\n \"fuzzy-thorns\": {\n \"point_freq\": random.randint(2, 4),\n \"point_distrib\": \"waffle\",\n \"point_generations\": 2,\n \"voronoi_inverse\": True,\n \"voronoi_nth\": random.randint(6, 12),\n \"with_voronoi\": 2,\n \"with_worms\": random.randint(1, 3),\n \"worms_density\": 500,\n \"worms_duration\": 1.22,\n \"worms_kink\": 2.89,\n \"worms_stride\": 0.64,\n \"worms_stride_deviation\": 0.11,\n },\n\n \"galalaga\": {\n \"distrib\": [\"ones\", \"uniform\"][random.randint(0, 1)],\n \"freq\": 6 * random.randint(1, 3),\n \"glyph_map_zoom\": 1.0 + random.random() * 10.0,\n \"hue_range\": random.random() * 2.5,\n \"mask\": \"invaders_square\",\n \"posterize_levels\": 6,\n \"spline_order\": 0,\n \"with_crt\": True,\n \"with_glowing_edges\": .125 + random.random() * .125,\n \"with_glyph_map\": \"invaders_square\",\n \"with_scan_error\": True,\n },\n\n \"game-show\": {\n \"distrib\": \"normal\",\n \"freq\": random.randint(8, 16) * 2,\n \"mask\": [\"h_tri\", \"v_tri\"][random.randint(0, 1)],\n \"posterize_levels\": random.randint(2, 5),\n \"spline_order\": 2,\n \"with_crt\": True,\n \"with_snow\": random.random() * .333,\n },\n\n \"glass-onion\": {\n \"point_freq\": random.randint(3, 6),\n \"post_deriv\": random.randint(1, 3),\n \"post_refract_range\": .75 + random.random() * .5,\n \"voronoi_inverse\": random.randint(0, 1),\n \"with_reverb\": random.randint(3, 5),\n \"with_voronoi\": 2,\n },\n\n \"globules\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(6, 12),\n \"hue_range\": .25 + random.random() * .5,\n \"lattice_drift\": 1,\n \"mask\": \"sparse\",\n \"octaves\": random.randint(2, 4),\n \"reflect_range\": 1,\n \"saturation\": .175 + random.random() * .175,\n \"with_density_map\": True,\n \"with_shadow\": 1,\n },\n\n \"glom\": {\n \"freq\": 2,\n \"hue_range\": .25 + random.random() * .25,\n \"lattice_drift\": 1,\n \"octaves\": 2,\n \"post_reflect_range\": random.randint(1, 2),\n \"post_refract_range\": random.randint(1, 2),\n \"reflect_range\": random.randint(1, 2) * .25,\n \"refract_range\": random.randint(1, 2) * .25,\n \"warp_range\": .25 + random.random() * .25,\n \"warp_octaves\": 1,\n \"with_bloom\": .25 + random.random() * .5,\n \"with_shadow\": .75 + random.random() * .25,\n },\n\n \"graph-paper\": {\n \"corners\": True,\n \"distrib\": \"ones\",\n \"freq\": random.randint(4, 12) * 2,\n \"hue_range\": 0,\n \"hue_rotation\": random.random(),\n \"saturation\": 0.27,\n \"invert\": random.randint(0, 1),\n \"mask\": \"chess\",\n \"spline_order\": 0,\n \"voronoi_alpha\": .25 + random.random() * .75,\n \"voronoi_refract\": random.random() * 4,\n \"with_aberration\": random.random() * .02,\n \"with_bloom\": .5,\n \"with_crt\": True,\n \"with_scan_error\": True,\n \"with_sobel\": 2,\n \"with_voronoi\": 6,\n },\n\n \"gravy\": {\n \"distrib\": \"ones\",\n \"freq\": 24 * random.randint(2, 6),\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"post_deriv\": 2,\n \"spline_order\": random.randint(1, 2),\n \"warp_range\": .25 + random.random() * .5,\n \"warp_octaves\": 3,\n \"warp_freq\": random.randint(2, 4),\n \"warp_interp\": 3,\n \"with_bloom\": .25 + random.random() * .5,\n },\n\n \"hairy-diamond\": {\n \"erosion_worms_alpha\": .75 + random.random() * .25,\n \"erosion_worms_contraction\": .5 + random.random(),\n \"erosion_worms_density\": random.randint(25, 50),\n \"erosion_worms_iterations\": random.randint(25, 50),\n \"freq\": random.randint(2, 6),\n \"hue_range\": random.random(),\n \"hue_rotation\": random.random(),\n \"saturation\": random.random(),\n \"point_corners\": True,\n \"point_distrib\": [m.value for m in circular_dists][random.randint(0, len(circular_dists) - 1)],\n \"point_freq\": random.randint(3, 6),\n \"point_generations\": 2,\n \"spline_order\": random.randint(0, 3),\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_inverse\": True,\n \"voronoi_alpha\": .25 + random.random() * .5,\n \"with_erosion_worms\": True,\n \"with_voronoi\": [1, 6][random.randint(0, 1)],\n },\n\n \"halt-catch-fire\": {\n \"freq\": 2,\n \"hue_range\": .05,\n \"lattice_drift\": 1,\n \"octaves\": random.randint(3, 5),\n \"spline_order\": 0,\n \"with_aberration\": .01 + random.random() * .01,\n \"with_crt\": True,\n \"with_glitch\": True,\n \"with_scan_error\": True,\n \"with_snow\": random.random() * .333,\n },\n\n \"hex-machine\": {\n \"corners\": True,\n \"distrib\": \"ones\",\n \"freq\": random.randint(1, 3) * 2,\n \"mask\": \"h_tri\",\n \"octaves\": random.randint(5, 8),\n \"post_deriv\": 3,\n \"sin\": random.randint(-25, 25),\n },\n\n \"hsv-gradient\": {\n \"freq\": random.randint(2, 3),\n \"hue_range\": .125 + random.random() * 2.0,\n \"lattice_drift\": random.random(),\n },\n\n \"hydraulic-flow\": {\n \"deriv\": random.randint(0, 1),\n \"deriv_alpha\": .25 + random.random() * .25,\n \"distrib\": [m.value for m in ValueDistribution if m.name not in (\"ones\", \"mids\")][random.randint(0, len(ValueDistribution) - 3)],\n \"erosion_worms_alpha\": .125 + random.random() * .125,\n \"erosion_worms_contraction\": .75 + random.random() * .5,\n \"erosion_worms_density\": random.randint(5, 250),\n \"erosion_worms_iterations\": random.randint(50, 250),\n \"freq\": random.randint(2, 3),\n \"hue_range\": random.random(),\n \"invert\": random.randint(0, 1),\n \"octaves\": random.randint(4, 8),\n \"refract_range\": random.random() * 2,\n \"ridges\": random.randint(0, 1),\n \"rgb\": random.randint(0, 1),\n \"saturation\": random.random(),\n \"with_bloom\": .25 + random.random() * .25,\n \"with_dither\": .125,\n \"with_erosion_worms\": True,\n \"with_density_map\": True,\n \"with_shadow\": 1,\n },\n\n \"i-dream-of-tweegee\": {\n \"reindex_range\": 2,\n \"point_corners\": True,\n \"point_freq\": 2,\n \"point_distrib\": \"square\",\n \"post_reindex_range\": 2,\n \"rgb\": True,\n \"voronoi_alpha\": .625,\n \"with_voronoi\": 4,\n },\n\n \"inkling\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(4, 8),\n \"invert\": True,\n \"mask\": \"sparse\",\n \"point_freq\": 4,\n \"post_refract_range\": .125 + random.random() * .05,\n \"post_saturation\": 0,\n \"post_contrast\": 10,\n \"ripple_range\": .025 + random.random() * .0125,\n \"voronoi_refract\": .5 + random.random() * .25,\n \"with_density_map\": True,\n \"with_dither\": .175,\n \"with_fibers\": True,\n \"with_grime\": True,\n \"with_voronoi\": 6,\n },\n\n \"interference\": {\n \"corners\": True,\n \"freq\": 2,\n \"sin\": random.randint(250, 500),\n \"with_interference\": True\n },\n\n \"isoform\": {\n \"hue_range\": random.random(),\n \"invert\": random.randint(0, 1),\n \"post_deriv\": random.randint(0, 1) * random.randint(1, 3),\n \"post_refract_range\": .25 + random.random() * .25,\n \"ridges\": random.randint(0, 1),\n \"voronoi_alpha\": .75 + random.random() * .25,\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(0, 1),\n \"with_bloom\": .25 + random.random() * .25,\n \"with_outline\": random.randint(1, 3),\n \"with_voronoi\": random.randint(1, 2),\n },\n\n \"jovian-clouds\": {\n \"point_freq\": 10,\n \"voronoi_refract\": 2,\n \"with_voronoi\": 6,\n \"with_worms\": 4,\n \"worms_density\": 500,\n \"worms_duration\": 0.5,\n \"worms_kink\": 96,\n },\n\n \"just-refracts-maam\": {\n \"corners\": True,\n \"freq\": random.randint(2, 3),\n \"post_refract_range\": random.randint(0, 1),\n \"post_ridges\": random.randint(0, 1),\n \"refract_range\": random.randint(4, 8),\n \"ridges\": random.randint(0, 1),\n \"with_shadow\": random.randint(0, 1),\n },\n\n \"knotty-clouds\": {\n \"point_freq\": random.randint(6, 10),\n \"voronoi_alpha\": .125 + random.random() * .25,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_shadow\": 1,\n \"with_voronoi\": 2,\n \"with_worms\": 1,\n \"worms_alpha\": .666 + random.random() * .333,\n \"worms_density\": 1000,\n \"worms_duration\": 1,\n \"worms_kink\": 4,\n },\n\n \"later\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(8, 16),\n \"mask\": [m.value for m in ValueMask.procedural_members()][random.randint(0, len(ValueMask.procedural_members()) - 1)],\n \"octaves\": random.randint(3, 6),\n \"point_freq\": random.randint(4, 8),\n \"spline_order\": 0,\n \"voronoi_refract\": random.randint(1, 4),\n \"warp_freq\": random.randint(2, 4),\n \"warp_interp\": 3,\n \"warp_octaves\": 2,\n \"warp_range\": .25 + random.random() * .125,\n \"with_glowing_edges\": 1,\n \"with_voronoi\": 6,\n },\n\n \"lattice-noise\": {\n \"deriv\": random.randint(1, 3),\n \"freq\": random.randint(5, 12),\n \"invert\": 1,\n \"octaves\": random.randint(1, 3),\n \"post_deriv\": random.randint(1, 3),\n \"ridges\": random.randint(0, 1),\n \"saturation\": random.random(),\n \"with_density_map\": True,\n \"with_dither\": .125,\n \"with_shadow\": random.random(),\n },\n\n \"lcd\": {\n \"distrib\": \"ones\",\n \"freq\": 40 * random.randint(1, 4),\n \"invert\": 1,\n \"mask\": [\"lcd\", \"lcd_binary\"][random.randint(0, 1)],\n \"saturation\": .05,\n \"spline_order\": random.randint(0, 3),\n \"with_bloom\": .25 + random.random() * .125,\n \"with_shadow\": random.random(),\n },\n\n \"led\": {\n \"distrib\": \"ones\",\n \"freq\": 40 * random.randint(1, 4),\n \"mask\": [\"lcd\", \"lcd_binary\"][random.randint(0, 1)],\n \"spline_order\": random.randint(0, 3),\n \"with_bloom\": .25 + random.random() * .125,\n },\n\n \"lightcycle-derby\": {\n \"freq\": random.randint(16, 32),\n \"rgb\": random.randint(0, 1),\n \"spline_order\": 0,\n \"lattice_drift\": 1,\n \"with_bloom\": .25 + random.random() * .125,\n \"with_erosion_worms\": True,\n },\n\n \"magic-squares\": {\n \"channels\": 3,\n \"distrib\": [m.value for m in ValueDistribution if m.name not in (\"ones\", \"mids\")][random.randint(0, len(ValueDistribution) - 3)],\n \"edges\": .25 + random.random() * .5,\n \"freq\": [9, 12, 15, 18][random.randint(0, 3)],\n \"hue_range\": random.random() * .5,\n \"octaves\": random.randint(3, 5),\n \"point_distrib\": [m.value for m in grid_dists][random.randint(0, len(grid_dists) - 1)],\n \"point_freq\": [3, 6, 9][random.randint(0, 2)],\n \"spline_order\": 0,\n \"voronoi_alpha\": .25,\n \"with_bloom\": random.randint(0, 1) * random.random(),\n \"with_dither\": random.randint(0, 1) * random.random() * .125,\n \"with_voronoi\": random.randint(0, 1) * 4,\n },\n\n \"magic-smoke\": {\n \"freq\": random.randint(2, 4),\n \"octaves\": random.randint(1, 3),\n \"with_worms\": random.randint(1, 2),\n \"worms_alpha\": 1,\n \"worms_density\": 750,\n \"worms_duration\": .25,\n \"worms_kink\": random.randint(1, 3),\n \"worms_stride\": random.randint(64, 256),\n },\n\n \"mcpaint\": {\n \"corners\": True,\n \"distrib\": [\"ones\", \"uniform\", \"normal\"][random.randint(0, 2)],\n \"freq\": random.randint(2, 8),\n \"glyph_map_colorize\": random.randint(0, 1),\n \"glyph_map_zoom\": random.randint(3, 6),\n \"mask\": \"mcpaint\",\n # \"posterize_levels\": 12,\n \"spline_order\": 2,\n \"vortex\": 10,\n \"with_glyph_map\": \"mcpaint\",\n },\n\n \"misaligned\": {\n \"distrib\": [m.value for m in ValueDistribution][random.randint(0, len(ValueDistribution) - 1)],\n \"freq\": random.randint(12, 24),\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"octaves\": random.randint(4, 8),\n \"spline_order\": 0,\n \"with_outline\": 1,\n },\n\n \"moire-than-a-feeling\": {\n \"freq\": random.randint(2, 4),\n \"octaves\": random.randint(1, 2),\n \"point_freq\": random.randint(1, 3),\n \"saturation\": 0,\n \"with_density_map\": True,\n \"with_voronoi\": random.randint(0, 1),\n \"with_wormhole\": True,\n \"wormhole_kink\": 128,\n \"wormhole_stride\": .0005,\n },\n\n \"multires-voronoi-worms\": {\n \"point_freq\": random.randint(8, 10),\n \"reverb_ridges\": False,\n \"with_reverb\": 2,\n \"with_voronoi\": [0, 1, 6][random.randint(0, 2)],\n \"with_worms\": 1,\n \"worms_density\": 1000,\n },\n\n \"muppet-skin\": {\n \"freq\": random.randint(2, 3),\n \"hue_range\": random.random() * .5,\n \"lattice_drift\": random.randint(0, 1) * random.random(),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_worms\": 3 if random.randint(0, 1) else 1,\n \"worms_alpha\": .75 + random.random() * .25,\n \"worms_density\": 500,\n },\n\n \"nerdvana\": {\n \"corners\": True,\n \"freq\": 2,\n \"invert\": 1,\n \"point_distrib\": ([m.value for m in circular_dists])[random.randint(0, len(circular_dists) - 1)],\n \"point_freq\": random.randint(5, 10),\n \"reverb_ridges\": False,\n \"with_bloom\": 0.25 + random.random() * .5,\n \"with_density_map\": True,\n \"with_voronoi\": 2,\n \"with_reverb\": 2,\n \"voronoi_nth\": 1,\n },\n\n \"neon-cambrian\": {\n \"hue_range\": 1,\n \"invert\": 1,\n \"posterize_levels\": 24,\n \"with_aberration\": 0.01,\n \"with_bloom\": .25 + random.random() * .5,\n \"with_sobel\": 1,\n \"with_voronoi\": 6,\n \"with_wormhole\": True,\n \"wormhole_kink\": 1,\n \"wormhole_stride\": 0.25,\n },\n\n \"neon-plasma\": {\n \"channels\": 3,\n \"freq\": random.randint(2, 5),\n \"lattice_drift\": random.randint(0, 1),\n \"octaves\": random.randint(3, 6),\n \"ridges\": True,\n },\n\n \"noise-blaster\": {\n \"freq\": random.randint(3, 4),\n \"lattice_drift\": 1,\n \"octaves\": 6,\n \"post_reindex_range\": 2,\n \"reindex_range\": 4,\n \"with_shadow\": .25 + random.random() * .25,\n },\n\n \"now\": {\n \"channels\": 3,\n \"freq\": random.randint(3, 10),\n \"hue_range\": random.random(),\n \"saturation\": .5 + random.random() * .5,\n \"lattice_drift\": random.randint(0, 1),\n \"octaves\": random.randint(2, 4),\n \"reverb_iterations\": random.randint(1, 2),\n \"point_freq\": random.randint(3, 10),\n \"reverb_ridges\": False,\n \"spline_order\": 0,\n \"voronoi_refract\": random.randint(1, 4),\n \"warp_freq\": random.randint(2, 4),\n \"warp_interp\": 3,\n \"warp_octaves\": 1,\n \"warp_range\": .075 + random.random() * .075,\n \"with_outline\": 1,\n \"with_reverb\": random.randint(0, 1),\n \"with_voronoi\": 6,\n },\n\n \"numberwang\": {\n \"distrib\": \"ones\",\n \"freq\": 6 * random.randint(15, 30),\n \"mask\": \"numeric\",\n \"spline_order\": random.randint(0, 2),\n \"warp_range\": .5 + random.random() * 1.5,\n \"warp_freq\": random.randint(2, 4),\n \"warp_interp\": 3,\n \"warp_octaves\": 1,\n \"with_bloom\": .25 + random.random() * .125,\n \"with_false_color\": True\n },\n\n \"octave-rings\": {\n \"corners\": True,\n \"distrib\": \"ones\",\n \"freq\": random.randint(1, 3) * 2,\n \"invert\": 1,\n \"mask\": \"waffle\",\n \"octaves\": random.randint(1, 2),\n \"post_reflect_range\": random.randint(0, 2),\n \"reverb_ridges\": False,\n \"with_reverb\": random.randint(4, 8),\n \"with_sobel\": 2,\n },\n\n \"oldschool\": {\n \"corners\": True,\n \"distrib\": \"ones\",\n \"freq\": random.randint(2, 5) * 2,\n \"mask\": \"chess\",\n \"rgb\": True,\n \"spline_order\": 0,\n \"point_distrib\": [m.value for m in PointDistribution][random.randint(0, len(PointDistribution) - 1)],\n \"point_freq\": random.randint(4, 8),\n \"voronoi_refract\": random.randint(8, 12),\n \"with_voronoi\": 6,\n },\n\n \"oracle\": {\n \"corners\": True,\n \"freq\": [14, 8],\n \"invert\": random.randint(0, 1),\n \"distrib\": \"ones\",\n \"mask\": \"iching\",\n \"spline_order\": 0,\n \"with_dither\": .075 + random.random() * .077,\n \"with_snow\": .25 + random.random() * .25,\n },\n\n \"outer-limits\": {\n \"freq\": 2,\n \"corners\": True,\n \"reindex_range\": random.randint(8, 16),\n \"saturation\": 0,\n \"with_crt\": True,\n \"with_dither\": .075 + random.random() * .077,\n \"with_scan_error\": random.randint(0, 1),\n \"with_vhs\": random.randint(0, 1),\n \"with_snow\": .25 + random.random() * .25,\n },\n\n \"pearlescent\": {\n \"hue_range\": random.randint(3, 5),\n \"octaves\": random.randint(1, 8),\n \"point_freq\": random.randint(6, 10),\n \"ridges\": random.randint(0, 1),\n \"saturation\": .175 + random.random() * .25,\n \"voronoi_alpha\": .333 + random.random() * .333,\n \"voronoi_refract\": 1.5 + random.random(),\n \"with_bloom\": .333 + random.random() * .333,\n \"with_shadow\": .333 + random.random() * .333,\n \"with_voronoi\": 6,\n },\n\n \"plaid\": {\n \"deriv\": 3,\n \"distrib\": \"ones\",\n \"hue_range\": random.random() * .5,\n \"freq\": random.randint(3, 6) * 2,\n \"mask\": \"chess\",\n \"octaves\": random.randint(2, 5),\n \"spline_order\": random.randint(1, 3),\n \"warp_freq\": random.randint(2, 3),\n \"warp_range\": random.random() * .25,\n \"warp_octaves\": 1,\n \"with_dither\": random.random() * 0.25,\n },\n\n \"pluto\": {\n \"freq\": random.randint(4, 8),\n \"deriv\": random.randint(1, 3),\n \"deriv_alpha\": .333 + random.random() * .333,\n \"hue_rotation\": .575,\n \"octaves\": 10,\n \"point_freq\": random.randint(6, 8),\n \"refract_range\": .075 + random.random() * .075,\n \"ridges\": True,\n \"saturation\": .125 + random.random() * .075,\n \"voronoi_alpha\": .75,\n \"voronoi_nth\": random.randint(1, 3),\n \"with_bloom\": .25 + random.random() * .25,\n \"with_dither\": .075 + random.random() * .075,\n \"with_shadow\": .75 + random.random() * .25,\n \"with_voronoi\": 2,\n },\n\n \"political-map\": {\n \"freq\": 5,\n \"saturation\": 0.35,\n \"lattice_drift\": 1,\n \"octaves\": 2,\n \"posterize_levels\": 4,\n \"warp_octaves\": 8,\n \"warp_range\": 1,\n \"with_bloom\": .5 + random.random() * .5,\n \"with_dither\": 0.25,\n \"with_outline\": 1,\n },\n\n \"precision-error\": {\n \"corners\": True,\n \"freq\": 2,\n \"invert\": 1,\n \"deriv\": random.randint(1, 3),\n \"post_deriv\": random.randint(1, 3),\n \"reflect_range\": .125 + random.random() * 4.0,\n \"with_density_map\": True,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_shadow\": 1,\n },\n\n \"procedural-mask\": {\n \"distrib\": \"ones\",\n \"freq\": 24 * random.randint(1, 8),\n \"mask\": [m.value for m in ValueMask.procedural_members()][random.randint(0, len(ValueMask.procedural_members()) - 1)],\n \"spline_order\": 0,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_crt\": True,\n \"with_scan_error\": True,\n },\n\n \"procedural-muck\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(100, 250),\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"saturation\": 0,\n \"spline_order\": 0,\n \"warp_freq\": random.randint(2, 5),\n \"warp_interp\": 2,\n \"warp_range\": .5 + random.random(),\n },\n\n \"prophesy\": {\n \"distrib\": \"ones\",\n \"emboss\": .5 + random.random() * .5,\n \"freq\": 48,\n \"invert\": random.randint(0, 1),\n \"mask\": \"invaders_square\",\n \"octaves\": 2,\n \"refract_range\": .5,\n \"saturation\": .125 + random.random() * .075,\n \"spline_order\": random.randint(1, 2),\n \"posterize_levels\": random.randint(4, 8),\n \"with_shadow\": .5,\n },\n\n \"quilty\": {\n \"freq\": random.randint(2, 6),\n \"saturation\": random.random() * .5,\n \"point_distrib\": [m.value for m in grid_dists][random.randint(0, len(grid_dists) - 1)],\n \"point_freq\": random.randint(3, 8),\n \"spline_order\": 0,\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(0, 4),\n \"voronoi_refract\": random.randint(1, 3),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_dither\": random.random() * .5,\n \"with_voronoi\": random.randint(1, 2),\n },\n\n \"rasteroids\": {\n \"distrib\": [\"uniform\", \"ones\"][random.randint(0, 1)],\n \"freq\": 6 * random.randint(2, 3),\n \"invert\": 1,\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"spline_order\": 0,\n \"warp_freq\": random.randint(3, 5),\n \"warp_octaves\": random.randint(3, 5),\n \"warp_range\": .25 + random.random() * .125,\n \"with_bloom\": .125 + random.random() * .125,\n \"with_crt\": True,\n \"with_scan_error\": True,\n \"with_snow\": .25 + random.random() * .125,\n \"with_sobel\": random.randint(1, 3),\n },\n\n \"redmond\": {\n \"corners\": True,\n \"distrib\": \"uniform\",\n \"freq\": 8,\n \"hue_range\": random.random() * 4.0,\n \"invert\": random.randint(0, 1),\n \"mask\": \"square\",\n \"point_generations\": 2,\n \"point_freq\": 2,\n \"point_distrib\": [\"chess\", \"square\"][random.randint(0, 1)],\n \"point_corners\": True,\n \"reverb_iterations\": random.randint(1, 3),\n \"spline_order\": 0,\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"voronoi_inverse\": random.randint(0, 1),\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(0, 3),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_reverb\": random.randint(3, 6),\n \"with_voronoi\": random.randint(1, 7),\n \"with_dither\": 0.13,\n \"with_snow\": 0.25,\n },\n\n \"refractal\": {\n \"invert\": 1,\n \"lattice_drift\": 1,\n \"octaves\": random.randint(1, 3),\n \"point_freq\": random.randint(8, 10),\n \"post_reflect_range\": random.randint(96, 192),\n \"sin\": random.random() * 10.0,\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"with_voronoi\": 6,\n },\n\n \"remember-logo\": {\n \"corners\": True,\n \"freq\": 2,\n \"invert\": True,\n \"point_distrib\": ([m.value for m in circular_dists])[random.randint(0, len(circular_dists) - 1)],\n \"point_freq\": random.randint(3, 7),\n \"voronoi_alpha\": 1.0,\n \"voronoi_nth\": random.randint(0, 4),\n \"with_density_map\": True,\n \"post_deriv\": 2,\n \"with_aberration\": .005 + random.random() * .005,\n \"with_crt\": True,\n \"with_scan_error\": True,\n \"with_snow\": .25 + random.random() * .125,\n \"with_vignette\": .25 + random.random() * .25,\n \"with_voronoi\": 3,\n },\n\n \"rgb-shadows\": {\n \"brightness_distrib\": \"mids\",\n \"distrib\": \"uniform\",\n \"freq\": random.randint(6, 16),\n \"hue_range\": random.randint(1, 4),\n \"lattice_drift\": random.random(),\n \"saturation_distrib\": \"ones\",\n \"with_shadow\": 1,\n },\n\n \"ridged-bubbles\": {\n \"corners\": True,\n \"freq\": 2,\n \"invert\": True,\n \"point_distrib\": [m.value for m in PointDistribution][random.randint(0, len(PointDistribution) - 1)],\n \"point_freq\": random.randint(4, 10),\n \"post_ridges\": True,\n \"reverb_iterations\": random.randint(1, 4),\n \"rgb\": random.randint(0, 1),\n \"voronoi_alpha\": .333 + random.random() * .333,\n \"with_density_map\": random.randint(0, 1),\n \"with_reverb\": random.randint(2, 4),\n \"with_voronoi\": 2,\n },\n\n \"ridged-ridges\": {\n \"freq\": random.randint(2, 8),\n \"lattice-drift\": random.randint(0, 1),\n \"octaves\": random.randint(3, 6),\n \"post_ridges\": True,\n \"rgb\": random.randint(0, 1),\n \"ridges\": True,\n },\n\n \"ripple-effect\": {\n \"freq\": random.randint(2, 5),\n \"invert\": 1,\n \"lattice_drift\": 1,\n \"ridges\": random.randint(0, 1),\n \"ripple_freq\": random.randint(2, 3),\n \"ripple_kink\": random.randint(3, 18),\n \"ripple_range\": .05 + random.random() * .2,\n \"sin\": 3,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_shadow\": .5 + random.random() * .25,\n },\n\n \"runes-of-arecibo\": {\n \"distrib\": \"ones\",\n \"freq\": 30 * random.randint(3, 6),\n \"mask\": ['arecibo_num', 'arecibo_bignum'][random.randint(0, 1)],\n \"spline_order\": random.randint(0, 2),\n },\n\n \"sands-of-time\": {\n \"freq\": random.randint(3, 5),\n \"octaves\": random.randint(1, 3),\n \"with_worms\": random.randint(3, 4),\n \"worms_alpha\": 1,\n \"worms_density\": 750,\n \"worms_duration\": .25,\n \"worms-kink\": random.randint(1, 2),\n \"worms_stride\": random.randint(128, 256),\n },\n\n \"satori\": {\n \"freq\": random.randint(3, 8),\n \"hue_range\": random.random(),\n \"lattice_drift\": 1,\n \"point_distrib\": ([\"random\"] + [m.value for m in circular_dists])[random.randint(0, len(circular_dists))],\n \"point_freq\": random.randint(2, 8),\n \"post_ridges\": random.randint(0, 1),\n \"rgb\": random.randint(0, 1),\n \"ridges\": True,\n \"sin\": random.random() * 2.5,\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"voronoi_refract\": random.randint(6, 12),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_shadow\": 1.0,\n \"with_voronoi\": 6,\n },\n\n \"scribbles\": {\n \"deriv\": random.randint(1, 3),\n \"freq\": random.randint(4, 8),\n \"lattice_drift\": random.random(),\n \"octaves\": 2,\n \"post_contrast\": 5,\n \"post_deriv\": random.randint(1, 3),\n \"post_saturation\": 0,\n \"ridges\": True,\n \"with_density_map\": True,\n \"with_dither\": .25,\n \"with_fibers\": True,\n \"with_grime\": True,\n \"with_vignette\": .075 + random.random() * .05,\n \"with_shadow\": random.random(),\n \"with_sobel\": random.randint(1, 3),\n },\n\n \"seether-reflect\": {\n \"corners\": True,\n \"freq\": 2,\n \"hue_range\": 1.0 + random.random(),\n \"invert\": True,\n \"point_distrib\": ([m.value for m in circular_dists])[random.randint(0, len(circular_dists) - 1)],\n \"point_freq\": random.randint(4, 6),\n \"post_reflect_range\": random.randint(8, 12),\n \"post_ridges\": True,\n \"ridges\": True,\n \"voronoi_alpha\": .25 + random.random() * .25,\n \"warp_range\": .5,\n \"warp_octaves\": 6,\n \"with_glowing_edges\": 1,\n \"with_reverb\": 1,\n \"with_shadow\": 1,\n \"with_voronoi\": 2,\n },\n\n \"seether-refract\": {\n \"corners\": True,\n \"freq\": 2,\n \"hue_range\": 1.0 + random.random(),\n \"invert\": True,\n \"point_distrib\": ([m.value for m in circular_dists])[random.randint(0, len(circular_dists) - 1)],\n \"point_freq\": random.randint(4, 6),\n \"post_refract_range\": random.randint(4, 8),\n \"post_ridges\": True,\n \"ridges\": True,\n \"voronoi_alpha\": .25 + random.random() * .25,\n \"warp_range\": .5,\n \"warp_octaves\": 6,\n \"with_glowing_edges\": 1,\n \"with_reverb\": 1,\n \"with_shadow\": 1,\n \"with_voronoi\": 2,\n },\n\n \"shatter\": {\n \"freq\": random.randint(2, 4),\n \"invert\": random.randint(0, 1),\n \"point_freq\": random.randint(3, 6),\n \"post_refract_range\": random.randint(3, 5),\n \"posterize_levels\": random.randint(4, 6),\n \"rgb\": random.randint(0, 1),\n \"voronoi_func\": [1, 3][random.randint(0, 1)],\n \"voronoi_inverse\": random.randint(0, 1),\n \"with_outline\": random.randint(1, 3),\n \"with_voronoi\": 5,\n },\n\n \"shmoo\": {\n \"freq\": random.randint(4, 6),\n \"hue_range\": 2 + random.random(),\n \"invert\": 1,\n \"posterize_levels\": random.randint(3, 5),\n \"rgb\": random.randint(0, 1),\n \"with_outline\": 1,\n },\n\n \"shmootype\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(4, 6) * 150,\n \"mask\": \"truetype\",\n \"spline_order\": random.randint(0, 2),\n \"warp_freq\": 3,\n \"warp_interp\": 3,\n \"warp_octaves\": 1,\n \"warp_range\": 2,\n },\n\n \"sideways\": {\n \"freq\": random.randint(6, 12),\n \"distrib\": \"ones\",\n \"mask\": \"script\",\n \"octaves\": random.randint(3, 5),\n \"reflect_range\": 1,\n \"saturation\": .06125 + random.random() * .125,\n \"sin\": random.random() * 4,\n \"spline_order\": random.randint(1, 3),\n \"with_aberration\": .005 + random.random() * .01,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_crt\": True,\n \"with_scan_error\": True,\n \"with_shadow\": .5 + random.random() * .5,\n },\n\n \"sine-here-please\": {\n \"freq\": random.randint(2, 4),\n \"octaves\": 8,\n \"sin\": 25 + random.random() * 200,\n \"with_shadow\": 1,\n },\n\n \"sined-multifractal\": {\n \"distrib\": \"uniform\",\n \"freq\": random.randint(2, 12),\n \"hue_range\": random.random(),\n \"hue_rotation\": random.random(),\n \"lattice_drift\": .75,\n \"octaves\": 7,\n \"ridges\": True,\n \"sin\": -3,\n \"with_bloom\": .25 + random.random() * .25,\n },\n\n \"skeletal-lace\": {\n \"lattice_drift\": 1,\n \"point_freq\": 3,\n \"voronoi_nth\": 1,\n \"voronoi_refract\": 25,\n \"with_voronoi\": 6,\n \"with_wormhole\": True,\n \"wormhole_stride\": 0.01,\n },\n\n \"slimer\": {\n \"freq\": random.randint(3, 4),\n \"hue_range\": .5,\n \"point_freq\": random.randint(1, 3),\n \"post_reindex_range\": .25 + random.random() * .333,\n \"reindex_range\": .5 + random.random() * .666,\n \"ripple_range\": .025 + random.random() * .0333,\n \"voronoi_alpha\": .5 + random.random() * .333,\n \"voronoi_refract\": random.randint(3, 5),\n \"warp_range\": .075 + random.random() * .075,\n \"with_voronoi\": 2,\n },\n\n \"soft-cells\": {\n \"point_distrib\": [m.value for m in PointDistribution][random.randint(0, len(PointDistribution) - 1)],\n \"point_freq\": random.randint(4, 8),\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"with_bloom\": .5 + random.random() * .5,\n \"with_voronoi\": 5,\n },\n\n \"soften\": {\n \"freq\": 2,\n \"hue_range\": .25 + random.random() * .25,\n \"hue_rotation\": random.random(),\n \"lattice_drift\": 1,\n \"octaves\": random.randint(1, 4),\n \"rgb\": random.randint(0, 1),\n \"with_bloom\": .25 + random.random() * .5,\n },\n\n \"solar\": {\n \"freq\": random.randint(20, 28),\n \"hue_range\": .225 + random.random() * .05,\n \"hue_rotation\": .975,\n \"octaves\": random.randint(4, 8),\n \"reflect_range\": .666 + random.random() * .333,\n \"refract_range\": .666 + random.random() * .333,\n \"saturation\": 4 + random.random() * 2.5,\n \"sin\": 3,\n \"warp_range\": .2 + random.random() * .1,\n \"warp_freq\": 2,\n \"with_bloom\": .5 + random.random() * .25,\n },\n\n \"soup\": {\n \"invert\": 1,\n \"point_freq\": random.randint(2, 4),\n \"post_refract_range\": random.randint(8, 12),\n \"voronoi_inverse\": True,\n \"with_bloom\": .5 * random.random() * .25,\n \"with_density_map\": True,\n \"with_shadow\": 1.0,\n \"with_voronoi\": 6,\n \"with_worms\": 5,\n \"worms_alpha\": .5 + random.random() * .45,\n \"worms_density\": 500,\n \"worms_kink\": 4.0 + random.random() * 2.0,\n },\n\n \"spaghettification\": {\n \"invert\": 1,\n \"octaves\": random.randint(2, 5),\n \"point_freq\": 1,\n \"voronoi_func\": random.randint(1, 3),\n \"voronoi_inverse\": True,\n \"with_aberration\": .0075 + random.random() * .0075,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_density_map\": True,\n \"with_shadow\": .75 + random.random() * .25,\n \"with_voronoi\": 6,\n \"with_worms\": 4,\n \"worms_alpha\": .75,\n \"worms_density\": 1500,\n \"worms_stride\": random.randint(150, 350),\n },\n\n \"spiral-clouds\": {\n \"freq\": random.randint(2, 4),\n \"lattice_drift\": 1.0,\n \"octaves\": random.randint(4, 8),\n \"saturation-distrib\": \"ones\",\n \"shadow\": 1,\n \"with_wormhole\": True,\n \"wormhole_alpha\": .333 + random.random() * .333,\n \"wormhole_stride\": .001 + random.random() * .0005,\n \"wormhole_kink\": random.randint(40, 50),\n },\n\n \"spiral-in-spiral\": {\n \"point_distrib\": \"spiral\" if random.randint(0, 1) else \"rotating\",\n \"point_freq\": 10,\n \"reverb_iterations\": random.randint(1, 4),\n \"with_reverb\": random.randint(0, 6),\n \"with_voronoi\": random.randint(1, 2),\n \"with_worms\": random.randint(1, 4),\n \"worms_density\": 500,\n \"worms_duration\": 1,\n \"worms_kink\": random.randint(5, 25),\n },\n\n \"spiraltown\": {\n \"freq\": 2,\n \"hue_range\": 1,\n \"reflect_range\": random.randint(3, 6),\n \"spline_order\": random.randint(1, 3),\n \"with_wormhole\": True,\n \"wormhole_kink\": random.randint(5, 20),\n \"wormhole_stride\": random.random() * .05,\n },\n\n \"square-stripes\": {\n \"hue_range\": random.random(),\n \"point_distrib\": [m.value for m in grid_dists][random.randint(0, len(grid_dists) - 1)],\n \"point_freq\": 2,\n \"point_generations\": random.randint(2, 3),\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(1, 3),\n \"voronoi_refract\": 1.46,\n \"with_voronoi\": 2,\n },\n\n \"star-cloud\": {\n \"deriv\": 1,\n \"freq\": 2,\n \"hue_range\": random.random() * 2.0,\n \"invert\": 1,\n \"point_freq\": 10,\n \"reflect_range\": random.random() + .5,\n \"reverb_iterations\": random.randint(1, 4),\n \"spline_order\": 2,\n \"voronoi_refract\": random.randint(2, 4),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_reverb\": random.randint(0, 3),\n \"with_sobel\": 1,\n \"with_voronoi\": 6,\n },\n\n \"stepper\": {\n \"hue_range\": random.random(),\n \"saturation\": random.random(),\n \"point_corners\": random.randint(0, 1),\n \"point_distrib\": [m.value for m in circular_dists][random.randint(0, len(circular_dists) - 1)],\n \"point_freq\": random.randint(7, 10),\n \"voronoi_func\": random.randint(2, 3),\n \"voronoi_nth\": random.randint(0, 48),\n \"with_outline\": 3,\n \"with_voronoi\": random.randint(1, 5),\n },\n\n \"teh-matrex-haz-u\": {\n \"distrib\": \"exp\",\n \"freq\": (random.randint(2, 4), random.randint(48, 96)),\n \"glyph_map_zoom\": random.randint(2, 5),\n \"hue_rotation\": .4 + random.random() * .2,\n \"hue_range\": .25,\n \"lattice_drift\": 1,\n \"mask\": \"sparse\",\n \"octaves\": 2,\n \"post_saturation\": 2,\n \"spline_order\": 1,\n \"with_bloom\": .333 + random.random() * .333,\n \"with_crt\": True,\n \"with_glyph_map\": [\n [\"binary\", \"numeric\", \"hex\"][random.randint(0, 2)],\n \"truetype\",\n \"ideogram\",\n \"invaders_square\",\n \"fat_lcd\",\n \"fat_lcd_binary\",\n \"fat_lcd_numeric\",\n \"fat_lcd_hex\"\n ][random.randint(0, 7)],\n \"with_scan_error\": True,\n },\n\n \"tensorflower\": {\n \"corners\": True,\n \"hue_range\": random.random(),\n \"freq\": 2,\n \"point_corners\": True,\n \"point_distrib\": [\"square\", \"h_hex\", \"v_hex\"][random.randint(0, 2)],\n \"point_freq\": 2,\n \"rgb\": random.randint(0, 1),\n \"spline_order\": 0,\n \"vortex_range\": random.randint(8, 25),\n \"with_bloom\": .25 + random.random() * .5,\n \"with_voronoi\": 5,\n },\n\n \"the-arecibo-response\": {\n \"distrib\": \"ones\",\n \"freq\": random.randint(42, 210),\n \"mask\": 'arecibo',\n \"spline_order\": random.randint(0, 2),\n \"with_snow\": random.random() * .333,\n },\n\n \"the-data-must-flow\": {\n \"freq\": 2,\n \"hue_range\": random.random() * 2.5,\n \"invert\": 1,\n \"with_bloom\": .25 + random.random() * .5,\n \"with_sobel\": 1,\n \"with_worms\": 1,\n \"worms_alpha\": .9 + random.random() * .1,\n \"worms_density\": 1.5 + random.random(),\n \"worms_duration\": 1,\n \"worms_stride\": 8,\n \"worms_stride_deviation\": 6,\n },\n\n \"the-inward-spiral\": {\n \"point_freq\": 1,\n \"voronoi_func\": random.randint(1, 3),\n \"with_voronoi\": 2,\n \"with_worms\": random.randint(1, 5),\n \"worms_alpha\": 1,\n \"worms_duration\": random.randint(1, 4),\n \"worms_density\": 500,\n \"worms_kink\": random.randint(6, 24),\n },\n\n \"time-to-reflect\": {\n \"corners\": True,\n \"freq\": 2,\n \"post_reflect_range\": random.randint(0, 1),\n \"post_ridges\": random.randint(0, 1),\n \"reflect_range\": random.randint(7, 14),\n \"ridges\": random.randint(0, 1),\n \"with_shadow\": random.randint(0, 1),\n },\n\n \"timeworms\": {\n \"freq\": random.randint(8, 36),\n \"hue_range\": 0,\n \"invert\": 1,\n \"mask\": \"sparse\",\n \"octaves\": random.randint(1, 3),\n \"reflect_range\": random.randint(0, 1) * random.random() * 4,\n \"spline_order\": random.randint(1, 3),\n \"with_bloom\": .25 + random.random() * .25,\n \"with_density_map\": True,\n \"with_worms\": 1,\n \"worms_alpha\": 1,\n \"worms_density\": .25,\n \"worms_duration\": 10,\n \"worms_stride\": 2,\n \"worms_kink\": .25 + random.random() * 2.5,\n },\n\n \"traceroute\": {\n \"corners\": True,\n \"distrib\": \"ones\",\n \"freq\": random.randint(2, 6),\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"octaves\": 8,\n \"with_worms\": random.randint(1, 3),\n \"worms_density\": 500,\n \"worms_kink\": random.randint(5, 25),\n },\n\n \"triangular\": {\n \"corners\": True,\n \"distrib\": [\"ones\", \"uniform\"][random.randint(0, 1)],\n \"freq\": random.randint(1, 4) * 2,\n \"invert\": random.randint(0, 1),\n \"mask\": [\"h_tri\", \"v_tri\"][random.randint(0, 1)],\n \"octaves\": random.randint(4, 8),\n \"with_sobel\": random.randint(0, 1),\n },\n\n \"tribbles\": {\n \"freq\": random.randint(4, 10),\n \"hue_rotation\": random.random() if random.randint(0, 1) else 0.375 + random.random() * .15,\n \"hue_range\": random.random() * 2.5 if random.randint(0, 1) else 0.125 + random.random() * .125,\n \"saturation\": .375 + random.random() * .15,\n \"invert\": 1,\n \"octaves\": 3,\n \"point_distrib\": \"h_hex\",\n \"point_freq\": random.randint(2, 5) * 2,\n \"ridges\": True,\n \"voronoi_alpha\": 0.5 + random.random() * .25,\n \"warp_freq\": random.randint(2, 4),\n \"warp_octaves\": random.randint(2, 4),\n \"warp_range\": 0.05 + random.random() * .01,\n \"with_bloom\": 0.25 + random.random() * .5,\n \"with_voronoi\": 5,\n \"with_worms\": 3,\n \"worms_alpha\": .75 + random.random() * .25,\n \"worms_density\": 750,\n \"worms_duration\": .5,\n \"worms_stride_deviation\": .5,\n },\n\n \"triblets\": {\n \"distrib\": \"uniform\",\n \"freq\": random.randint(3, 15) * 2,\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"hue_rotation\": 0.875 + random.random() * .15,\n \"saturation\": .375 + random.random() * .15,\n \"octaves\": random.randint(3, 6),\n \"warp_octaves\": random.randint(1, 2),\n \"warp_freq\": random.randint(2, 3),\n \"warp_range\": 0.05 + random.random() * .1,\n \"with_bloom\": 0.25 + random.random() * .5,\n \"with_worms\": 3,\n \"worms_alpha\": .875 + random.random() * .125,\n \"worms_density\": 750,\n \"worms_duration\": .5,\n \"worms_stride\": .5,\n \"worms_stride_deviation\": .25,\n },\n\n \"trominos\": {\n \"distrib\": \"ones\",\n \"freq\": 4 * random.randint(25, 50),\n \"invert\": 1,\n \"mask\": \"tromino\",\n \"spline_order\": 0,\n \"with_bloom\": .25 + random.random() * .125,\n \"with_crt\": True,\n \"with_scan_error\": True,\n \"with_sobel\": random.randint(1, 3),\n },\n\n \"truchet-maze\": {\n \"distrib\": \"ones\",\n \"freq\": 6 * random.randint(50, 100),\n \"mask\": \"truchet_maze\",\n \"spline_order\": random.randint(0, 3),\n },\n\n \"turf\": {\n \"freq\": random.randint(6, 12),\n \"hue_rotation\": .25 + random.random() * .05,\n \"lattice_drift\": 1,\n \"octaves\": 8,\n \"saturation\": .625 + random.random() * .25,\n \"with_dither\": .1 + random.random() * .05,\n \"with_worms\": 4,\n \"worms_alpha\": .9,\n \"worms_density\": 50 + random.random() * 25,\n \"worms_duration\": 1.125,\n \"worms_stride\": .875,\n \"worms_stride_deviation\": .125,\n \"worms_kink\": .125 + random.random() * .5,\n },\n\n \"twister\": {\n \"freq\": random.randint(12, 24),\n \"octaves\": 2,\n \"with_wormhole\": True,\n \"wormhole_kink\": 1 + random.random() * 3,\n \"wormhole_stride\": .0333 + random.random() * .0333,\n },\n\n \"unicorn-puddle\": {\n \"distrib\": \"uniform\",\n \"freq\": random.randint(8, 12),\n \"hue_range\": 2.5,\n \"invert\": .5 * random.random() * .5,\n \"lattice_drift\": 1,\n \"octaves\": random.randint(4, 6),\n \"post_contrast\": 1.5,\n \"post_hue_rotation\": random.random(),\n \"reflect_range\": .25 + random.random() * .125,\n \"ripple_freq\": [random.randint(12, 64), random.randint(12, 64)],\n \"ripple_kink\": .5 + random.random() * .25,\n \"ripple_range\": .25 + random.random() * .125,\n \"with_bloom\": .25 + random.random() * .25,\n \"with_light_leak\": .5 + random.random() * .25,\n \"with_shadow\": 1,\n },\n\n \"vectoroids\": {\n \"freq\": 25,\n \"distrib\": \"ones\",\n \"mask\": \"sparse\",\n \"point_freq\": 10,\n \"point_drift\": .25 + random.random() * .75,\n \"post_deriv\": 1,\n \"spline_order\": 0,\n \"with_aberration\": .0025 + random.random() * .0075,\n \"with_crt\": True,\n \"with_snow\": .25 + random.random() * .125,\n \"with_scan_error\": True,\n \"with_voronoi\": 4,\n },\n\n \"velcro\": {\n \"freq\": 2,\n \"hue_range\": random.randint(0, 3),\n \"octaves\": random.randint(1, 2),\n \"reflect_range\": random.randint(6, 8),\n \"spline_order\": random.randint(2, 3),\n \"with_wormhole\": True,\n \"wormhole_stride\": random.random() * .0125,\n },\n\n \"vortex-checkers\": {\n \"freq\": random.randint(4, 10) * 2,\n \"distrib\": [\"ones\", \"uniform\", \"laplace\"][random.randint(0, 2)],\n \"mask\": \"chess\",\n \"hue_range\": random.random(),\n \"saturation\": random.random(),\n \"outline\": 3,\n \"posterize\": random.randint(10, 15),\n \"reverb_iterations\": random.randint(2, 4),\n \"sin\": .5 + random.random(),\n \"spline_order\": 0,\n \"vortex_range\": 2.5 + random.random() * 5,\n \"with_reverb\": random.randint(3, 5),\n },\n\n \"warped-cells\": {\n \"invert\": 1,\n \"point_distrib\": ([m.value for m in PointDistribution])[random.randint(0, len(PointDistribution) - 1)],\n \"point_freq\": random.randint(6, 10),\n \"post_ridges\": True,\n \"voronoi_alpha\": .333 + random.random() * .333,\n \"warp_range\": .5 + random.random() * .5,\n \"with_voronoi\": 2,\n },\n\n \"warped-grid\": {\n \"corners\": True,\n \"distrib\": \"ones\",\n \"freq\": random.randint(4, 48) * 2,\n \"hue_range\": 3,\n \"saturation\": 0.27,\n \"invert\": 1,\n \"mask\": [m.value for m in ValueMask][random.randint(0, len(ValueMask) - 1)],\n \"posterize_levels\": 12,\n \"spline_order\": 0,\n \"warp_interp\": random.randint(1, 3),\n \"warp_freq\": random.randint(2, 4),\n \"warp_range\": .25 + random.random() * .75,\n \"warp_octaves\": 1,\n \"with_aberration\": random.random() * .125,\n \"with_bloom\": random.randint(0, 1) * .5,\n \"with_sobel\": 2,\n },\n\n \"whatami\": {\n \"freq\": random.randint(7, 9),\n \"hue_range\": 3,\n \"invert\": 1,\n \"post_reindex_range\": 2,\n \"reindex_range\": 2,\n \"voronoi_alpha\": .75 + random.random() * .125,\n \"with_voronoi\": 2,\n },\n\n \"wireframe\": {\n \"freq\": random.randint(2, 5),\n \"hue_range\": random.random(),\n \"saturation\": random.random(),\n \"invert\": 1,\n \"lattice_drift\": random.random(),\n \"octaves\": 2,\n \"point_distrib\": [m.value for m in grid_dists][random.randint(0, len(grid_dists) - 1)],\n \"point_freq\": random.randint(7, 10),\n \"voronoi_alpha\": 0.25 + random.random() * .5,\n \"voronoi_nth\": random.randint(1, 5),\n \"warp_octaves\": random.randint(1, 3),\n \"warp_range\": random.randint(0, 1) * random.random() * .5,\n \"with_bloom\": 0.25 + random.random() * .5,\n \"with_sobel\": 1,\n \"with_voronoi\": 5,\n },\n\n \"wild-kingdom\": {\n \"freq\": 25,\n \"invert\": random.randint(0, 1),\n \"lattice_drift\": 1,\n \"mask\": \"sparse\",\n \"post_hue_rotation\": random.random(),\n \"posterize_levels\": 3,\n \"rgb\": True,\n \"ridges\": True,\n \"with_bloom\": 2.0,\n \"warp_octaves\": 2,\n \"warp_range\": .05,\n \"with_outline\": 2,\n },\n\n \"woahdude-voronoi-refract\": {\n \"freq\": 4,\n \"hue_range\": 2,\n \"lattice_drift\": 1,\n \"point_freq\": 8,\n \"sin\": 100,\n \"voronoi_alpha\": 0.875,\n \"voronoi_refract\": 1,\n \"with_voronoi\": 1,\n },\n\n \"woahdude-octave-warp\": {\n \"freq\": random.randint(2, 3),\n \"hue_range\": random.random() * 3.0,\n \"sin\": random.randint(5, 15),\n \"warp_range\": random.randint(3, 5),\n \"warp_octaves\": 3,\n \"with_bloom\": .25 + random.random() * .5,\n \"with_shadow\": random.random(),\n },\n\n \"wooly-bully\": {\n \"hue_range\": random.random() * 1.5,\n \"point_corners\": True,\n \"point_distrib\": [m.value for m in circular_dists][random.randint(0, len(circular_dists) - 1)],\n \"point_freq\": random.randint(2, 3),\n \"point_generations\": 2,\n \"reverb_iterations\": random.randint(1, 2),\n \"refract_range\": random.randint(0, 2),\n \"voronoi_func\": 3,\n \"voronoi_nth\": random.randint(1, 3),\n \"voronoi_alpha\": .5 + random.random() * .5,\n \"with_reverb\": random.randint(0, 2),\n \"with_voronoi\": 2,\n \"with_worms\": 4,\n \"worms_alpha\": .75 + random.random() * .25,\n \"worms_density\": 250 + random.random() * 250,\n \"worms_duration\": 1 + random.random() * 1.5,\n \"worms_kink\": 5 + random.random() * 2.0,\n \"worms_stride\": 2.5,\n \"worms_stride_deviation\": 1.25,\n },\n\n \"wormstep\": {\n \"corners\": True,\n \"freq\": random.randint(2, 4),\n \"lattice_drift\": random.randint(0, 1),\n \"octaves\": random.randint(1, 3),\n \"with_bloom\": .25 + random.random() * .25,\n \"with_worms\": 4,\n \"worms_alpha\": .5 + random.random() * .5,\n \"worms_density\": 500,\n \"worms_kink\": 1.0 + random.random() * 4.0,\n \"worms_stride\": 8.0 + random.random() * 4.0,\n },\n\n}\n\n\ndef load(preset_name, preset_set=None):\n \"\"\"\n Load a named preset. Specify \"random\" for a random preset.\n\n Returns a tuple of (dict, dict, str): `generators.multires` keyword args, `recipes.post_process` keyword args, and preset name.\n\n See the `artmaker` script for an example of how these values are used.\n\n :param str preset_name: Name of the preset. If \"random\" is given, a random preset is returned.\n :param dict|None preset_set: Use a provided preset set. Defaults to `presets.PRESETS`.\n :return: tuple(dict, dict, str)\n \"\"\"\n\n if preset_set is None:\n preset_set = PRESETS()\n\n if preset_name == \"random\":\n preset_name = sorted(preset_set)[random.randint(0, len(preset_set) - 1)]\n\n preset = preset_set.get(preset_name)\n\n else:\n preset = preset_set.get(preset_name, {})\n\n return preset, preset_name\n","sub_path":"noisemaker/presets.py","file_name":"presets.py","file_ext":"py","file_size_in_byte":85695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"32940238","text":"import sys, os, pickle, gym, cv2\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nfrom pg import Policy\r\nfrom multiprocessing import Process, Manager\r\n\r\n\r\n\r\n\r\ndef plot_graph(average_score_list):\r\n\tplt.figure(1)\r\n\tplt.clf()\r\n\tplt.ylim(-21, 21)\r\n\tplt.xlim(0, 10000)\r\n\tplt.plot(average_score_list, c='b')\r\n\tplt.savefig('./Graph.png')\r\n\r\n\r\ndef discount_rewards(r, gamma):\r\n\t'''Take float array of rewards and compute discounted reward'''\r\n\tdiscounted_r = np.zeros_like(r)\r\n\trunning_add = 0\r\n\tfor t in reversed(range(0, r.size)):\r\n\t\t# if r[t] != 0: running_add = 0 # reset the sum, since this was a game boundary (pong specific!)\r\n\t\trunning_add = running_add * gamma + r[t]\r\n\t\tdiscounted_r[t] = running_add\r\n\t\t\r\n\tdiscounted_r -= np.mean(discounted_r)\r\n\tdiscounted_r /= np.std(discounted_r)\r\n\r\n\treturn discounted_r\r\n\r\n\r\ndef preprocess(img, image_dim):\r\n\timg = img[30:]\r\n\tresized = cv2.resize(img, image_dim, interpolation = cv2.INTER_AREA)\r\n\tresized = cv2.cvtColor(resized, cv2.COLOR_RGB2GRAY)\r\n\tresized = np.divide(resized, 255)\r\n\t# cv2.imshow('image',img)\r\n\t# cv2.waitKey(0)\r\n\treturn resized\r\n\r\n\r\n\r\ndef main():\r\n\tprint('Continue?(Y,n)', end=' ')\r\n\tsettings = {\r\n\t\t'game': \"Pong-v0\",\r\n\t\t'image_dim': (64, 64),\r\n\t\t'average_score_list': [],\r\n\t\t'curr_episode': 1,\r\n\t\t'running_reward': None\r\n\t}\r\n\tload_model = True if input().lower() == 'y' else False\r\n\tlearning_rate = 0.00025\r\n\taction_size = 3\r\n\tupdate_num = 512\r\n\tgame_step = 0\r\n\tstates, actions, rewards, vals, gaes, temp_states, temp_rewards, temp_vals = [], [], [], [], [], [], [], []\r\n\ttransitions = []\r\n\r\n\r\n\t\r\n\tpolicy = Policy(input_size=settings['image_dim'], action_size=action_size, learning_rate=learning_rate)\r\n\r\n\tif load_model == True:\r\n\t\tpolicy.saver.restore(policy.sess, './saves/')\r\n\t\tsettings = pickle.load(open('./saves/info.continue', 'rb'))\r\n\t\tsettings['curr_episode']+=1\r\n\t\t\r\n\t\r\n\tenv = gym.make(settings['game'])\r\n\r\n\t# while episode_number<num_of_games:\r\n\tfor episode_number in range(settings['curr_episode'], 10000):\r\n\t\t\r\n\t\t# policy.sess.run(policy.assign_ops)\r\n\t\tobservation = env.reset()\r\n\t\treward_sum = 0\r\n\t\tdone = False\r\n\r\n\t\t# create a difference image as starting image\r\n\t\tcur_x = preprocess(observation, settings['image_dim'])\r\n\t\tstate = cur_x - np.zeros(cur_x.shape)\r\n\t\tprev_x = cur_x\r\n\r\n\t\twhile not done:\r\n\t\t\tif True: env.render()\r\n\r\n\t\t\tgame_step+=1\r\n\r\n\t\t\t# sample an action from the policy\r\n\t\t\taction, value = policy.predict([state])\r\n\r\n\t\t\t# execute the action\r\n\t\t\tpong_action = { 0: 0, 1: 2, 2: 3 }\r\n\t\t\tobservation, reward, done, info = env.step(pong_action[action])\r\n\r\n\t\t\tlast_state = state\r\n\r\n\t\t\t# create a difference image as network input\r\n\t\t\tcur_x = preprocess(observation, settings['image_dim'])\r\n\t\t\tstate = cur_x - prev_x \r\n\t\t\tprev_x = cur_x\r\n\r\n\r\n\t\t\t# append the step to the episode lists\r\n\t\t\tstates.append(last_state)\r\n\t\t\tactions.append(action)\r\n\t\t\trewards.append(reward)\r\n\t\t\tvals.append(value)\r\n\t\t\ttemp_states.append(last_state)\r\n\t\t\ttemp_rewards.append(reward)\r\n\t\t\ttemp_vals.append(value)\r\n\t\t\t\r\n\r\n\t\t\treward_sum += reward\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t# perform parameter update every update_num episodes\r\n\t\t\tif (game_step % update_num == 0 and game_step != 0):\r\n\t\t\t\tsettings['curr_episode'] = episode_number\r\n\t\t\t\tnext_vals = vals[1:] + policy.get_vals([state])\r\n\t\t\t\ttemp_next_vals = temp_vals[1:] + policy.get_vals([state])\r\n\t\t\t\tgaes = gaes + policy.get_gaes(temp_rewards, temp_vals, temp_next_vals).tolist()\r\n\t\t\t\tgaes = np.array(gaes)\r\n\t\t\t\tgaes = (gaes - gaes.mean()) / gaes.std()\r\n\t\t\t\tpolicy.train(list(zip(states, actions, rewards, next_vals, gaes)), epochs=3, batch_size=128, verbose=False)\r\n\t\t\t\tstates, actions, rewards, vals, gaes, temp_states, temp_rewards, temp_vals, = [], [], [], [], [], [], [], []\r\n\r\n\r\n\r\n\r\n\t\t# When episode is done\r\n\t\t# book-keeping\r\n\t\tsettings['running_reward'] = reward_sum if settings['running_reward'] is None else settings['running_reward'] * 0.99 + reward_sum * 0.01\r\n\t\tprint('\\nPPO4\\nepisode %d: episode_reward=%f mean_reward=%f \\n' % (episode_number, reward_sum, settings['running_reward']))\r\n\t\tsettings['average_score_list'].append(settings['running_reward'])\r\n\r\n\t\ttemp_next_vals = temp_vals[1:] + policy.get_vals([state])\r\n\t\tgaes = gaes + policy.get_gaes(temp_rewards, temp_vals, temp_next_vals).tolist()\r\n\t\ttemp_states, temp_rewards, temp_vals, = [], [], []\r\n\t\t# gaes = policy.get_gaes(rewards, vals, next_vals)\r\n\t\t\r\n\t\t# print('\\nUpdate policy')\r\n\t\tsettings['curr_episode'] = episode_number\r\n\t\t# policy.train(list(zip(states, actions, rewards, next_vals, gaes)), epochs=4, batch_size=64)\r\n\t\ttry:\r\n\t\t\tos.mkdir('./saves/')\r\n\t\texcept: pass\r\n\t\tpolicy.saver.save(policy.sess, './saves/')\r\n\t\tpickle.dump(settings, open('./saves/info.continue', 'wb'))\r\n\t\tplot_graph(settings['average_score_list'])\r\n\t\ttransitions = []\r\n\t\t# states, actions, rewards, vals = [], [], [], []\r\n\t\r\n\t\tprint()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()","sub_path":"ProximalPolicyOptimization/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"307948867","text":"'''\nWhat day of the week did hitler get elected on?\n\nWhat day of the week did the Normans invade Britain on?\n\nWhat day of the week did Jesus die on?\n\nWhat day of the week did MacDonald get founded on?\n\nToday we're gonna find out\n\nFor todays challenge you are allowed to use your languages\nbuilt in Calender functions/classes.\n\nBut it's more interesting if you do the calculation yourself :)\nHint\n\nIt's leap-year if the year is divisible by 4\n\nIgnore leap-year if the year is divisible by 100\n\nIgnore previous rule if the year is divisible by 400\nInput example\n\nThe input will be 3 integers as such:\n\nYEAR MONTH DATE\n\nLimits for the 3 integers:\n\n8000 > YEAR > 0\n\n13 > MONTH > 0\n\n32 > DATE > 0\n\nSorry to anyone starting at 0.\n\nJanuary is 1 and December is 12\n\nAssume all dates to be correct (i.e. no 31th of february)\n\nInput will look like:\n\n2017 10 30\n\nOutput example\n\nOutput is simply the day of the week of the given date,\nfor above it would be:\n\nMonday\n\nChallenge input\n\n2017 10 30\n2016 2 29\n2015 2 28\n29 4 12\n570 11 30\n1066 9 25\n1776 7 4\n1933 1 30\n1953 3 6\n2100 1 9\n2202 12 15\n7032 3 26\n\n'''\nimport datetime\nfrom datetime import date\nimport calendar\nimport re\n\ndef year_type(y):\n \"\"\" int -> str\n leap year check\"\"\"\n leap = True\n if (y % 100 == 0 or y % 4 == 0) and not (y % 400 == 0):\n return leap\n return False\n\n\ndef same_month(a, b):\n \"\"\" num, num -> num\n calculate days elapsed in the same month \"\"\"\n days_elapsed = (a - b)\n return days_elapsed\n\n\ndef months_elapsed_zero(a, b):\n days_elapsed = - a + b + 1\n return days_elapsed\n\n\ndef years_to_days(a, b):\n \"\"\"str, str -> int\n Calculate years elapsed and convert into days\"\"\"\n\n years_elapsed = (a - b) - 1\n # store elapsed years\n year_store = []\n for x in range(1, years_elapsed + 1):\n elapsed_year = yr_now - x\n year_store.append(elapsed_year)\n # convert elapsed years into days\n total = 0\n for y in year_store:\n year_info = year_type(y)\n if year_info:\n total += 366\n months[2] = 29\n else:\n total += 365\n months[2] = 28\n return total\n\n\ndef months_elapsed_this_year(a, y):\n \"\"\" calculate days in elapsed months \"\"\"\n day_total = 0\n months_elapsed = a - 1\n\n for x in range(1, a):\n year_info = year_type(y)\n if x == 2:\n if year_info:\n months[2] = 29\n else:\n months[2] = 28\n day_total += months[x]\n else:\n day_total += months[x]\n return day_total\n\n\n\n\ndates = \"\"\"2017 10 30\n2016 2 29\n2015 2 28\n29 4 12\n570 11 30\n1066 9 25\n1776 7 4\n1933 1 30\n1953 3 6\n2100 1 9\n2202 12 15\n7032 3 26\"\"\"\n\ndates = dates.splitlines()\n\na_year = 365\nleap_year = 366\nday_accumulator = 0\n\n\n\nmonths = {1: 31,\n 2: 28,\n 3: 31,\n 4: 30,\n 5: 31,\n 6: 30,\n 7: 31,\n 8: 31,\n 9: 30,\n 10: 31,\n 11: 30,\n 12: 31}\n\nday_of_week = {0: 'Monday',\n 1: 'Tuesday',\n 2: 'Wednesday',\n 3: 'Thursday',\n 4: 'Friday',\n 5: 'Saturday',\n 6: 'Sunday'}\n\n\n\n#-- program ---------------------------------\n\nfor candidate_date in dates:\n candidate_yr = int((re.findall('^\\d+', candidate_date))[0])\n candidate_month = int((re.findall('\\s(\\d+)?', candidate_date))[0])\n candidate_day = int((re.findall('\\d+$', candidate_date))[0])\n day_accumulator = 0\n\n date_now = str(datetime.date.today())\n # weekday\n weekday = datetime.datetime.today().weekday()\n weekday = day_of_week[weekday]\n print(\"today's weekday: \", weekday)\n targetval = weekday\n for key in day_of_week.keys():\n if day_of_week[key] == targetval:\n print(\"found\", targetval, \"at key\", key)\n break\n this_day_number = key\n print('this_days number: ', this_day_number)\n yr_now = int(date_now[:4])\n #print('yr_now: ', yr_now)\n month_now = int(date_now[5:7])\n #print('month_now: ', month_now)\n day_now = int(date_now[8:10])\n #print('day_now: ', day_now)\n my_date = date.today()\n today_is = calendar.day_name[my_date.weekday()]\n #================================ << ok\n\n\n\n years_elapsed = years_to_days(yr_now, candidate_yr)\n day_accumulator -= years_elapsed\n print('days(years): ', years_elapsed) #====================================<< ok\n\n # days left in candidate month + 1\n if (candidate_month != month_now) and (candidate_yr == yr_now):\n candidate_days_left_of_month = months[candidate_month] - candidate_day + 1\n print('candidate month days left: ', candidate_days_left_of_month)\n day_accumulator += candidate_days_left_of_month\n\n days_used_this_month = day_now - 1\n day_accumulator += days_used_this_month\n\n days_used_this_month = day_now - 1\n day_accumulator += days_used_this_month\n\n # months elapsed plus convert into days\n days_in_months_elapsed = 0\n if years_elapsed <= 0:\n # months elapsed to days elapsed\n months_elapsed = months_elapsed_this_year(month_now, yr_now)\n\n # process candidate months left\n for x in range(candidate_month +1, 13):\n months_left_in_cand_year = months[x]\n day_accumulator -= months_left_in_cand_year\n\n year_info = year_type(yr_now)\n if year_info:\n months[2] = 29\n else:\n months[2] = 28\n # process year now months consumed\n for x in range(1, month_now - 1):\n days_in_months_elapsed += months[x]\n day_accumulator -= days_in_months_elapsed\n #================================<< or\n\n if months_elapsed <= 0 and candidate_month == month_now:\n days_elapsed = same_month(candidate_day, day_now)\n day_accumulator -= days_elapsed #===============================<<\n else:\n # months gone to date\n for x in range(1, month_now):\n days_in_month = months[x]\n day_accumulator -= days_in_month #===============================<< this\n\n for x in range(candidate_month +1, 13):\n months_left_in_cand_year = months[x]\n day_accumulator -= months_left_in_cand_year\n\n #=======================<<\n\n print(day_accumulator)\n\n\n # -2 to convert to weekday\n # add 1 for calc\n\n candidate_day_of_week = ((this_day_number - day_accumulator % 7) + 7) % 7\n candidate_day_of_week = day_of_week[candidate_day_of_week]\n\n print('candidate_day_of_week: ', candidate_day_of_week, candidate_date)\n print(day_accumulator)\n print()\n\n\n\n","sub_path":"338test120718.py","file_name":"338test120718.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"221613949","text":"from chatbot import register_call\nfrom requests import get as get_api\nfrom requests import post as post_api\nfrom requests import put as put_api\nfrom whatsappbot.services.validate_users import *\nfrom whatsappbot.db import lista_produtos, cadastros_novos, enderecos_novos, limpar_lista_produtor\nimport ast\nfrom flask import current_app\nfrom whatsappbot.services.eat_time import EatTime\nfrom whatsappbot.extensions.alert_people import AlertPeople\nfrom fuzzywuzzy import process, fuzz\nfrom .register import cadastrar_venda\n\nalert_people = AlertPeople()\n\n@register_call(\"verificar_resposta_pedir_mais_alguma_coisa\")\ndef verificar_resposta_pedir_mais_alguma_coisa(session, query):\n if process.extractOne(query, ['sim','isso','s','si','y','ye','yes','yep','yeah', 'quero'], scorer=fuzz.token_sort_ratio, score_cutoff=75):\n return \"O que você deseja?\"\n remedios_pedidos = [p['remedio'] for p in lista_produtos]\n precos = [p['preco_total'] for p in lista_produtos]\n preco_total = sum(precos)\n resposta = '🛒 Seu pedido foi finalizado e possui os seguintes produtos: \\n💊 ' + \\\n ', '.join(remedios_pedidos) + \\\n '\\n🪙 Totalizando em R$ '+ str(round(preco_total, 2)) +\"\\n\" \\\n 'Seu pagamento será feito em dinheiro, crédito ou débito?'\n return resposta\n\n@register_call(\"verificar_resposta_forma_pagamento\")\ndef verificar_resposta_forma_pagamento(session, query):\n \n numero, forma_pagamento = query.split(\",\")\n numero, forma_pagamento = [numero.strip(), forma_pagamento.strip()]\n numero = format_number(numero)\n venda = ultima_venda_cliente(numero)\n print(lista_produtos)\n for p in lista_produtos:\n item_venda = {'produtoId': p['id'], 'quantidade': p['quantidade'], 'vendaId': venda['id']}\n status = post_api('https://marcia-api.herokuapp.com/item-venda', json=item_venda).status_code\n print(\"Status item venda: \", status)\n venda['obs'] = \"Forma de pagamento será em: \"+forma_pagamento\n status = put_api('https://marcia-api.herokuapp.com/venda/{}'.format(venda['id']), json=venda).status_code\n print(\"Status put Venda: \", status)\n limpar_lista_produtor()\n return \"Seu pedido está finalizado e em breve chegará em sua residência!\\n\\nAh, mais uma coisa, você gostaria que avisássemos o horário que você deve tomar seu remédio?\"\n\n\n@register_call(\"verificar_cpf\")\ndef verificar_cpf(session, query):\n resposta = get_api('https://marcia-api.herokuapp.com/cliente/cpf/{}'.format(query)).status_code\n return \"Deseja adicionar esse número em seu cadastro?\" if query in fake_cpfs else \"Não encontramos seu CPF, deseja cadastrar?\"\n\n@register_call(\"verificar_numero\")\ndef verificar_numero(session, query):\n number = format_number(query)\n url = 'https://marcia-api.herokuapp.com/cliente/numero/{}'.format(number)\n resposta = get_api(url)\n marcia_resposta = \"\"\n \n if resposta.status_code == 404:\n marcia_resposta = \"Olá, tudo bem? Vimos que seu número não está cadastrado, você já possui cadastro?\"\n else:\n nome = GET_NAME.search(resposta.json()['nome']).group()\n nome = nome.capitalize()\n session.memory['nome']=nome\n marcia_resposta = \"Olá, {}, tudo bem? O que você deseja?\".format(nome)\n return marcia_resposta\n\n@register_call(\"verificar_produto\")\ndef verificar_produto(session, query):\n \n medicine, quantidade, numero = query.split(',')\n medicine, quantidade, numero = [medicine.strip(), quantidade.strip(), numero.strip()]\n numero = format_number(numero)\n remedios = get_api('https://marcia-api.herokuapp.com/produto').json()\n remedios_nomes = [p['nome'].lower() for p in remedios]\n remedio_encontrado = process.extractOne(medicine, remedios_nomes, scorer=fuzz.token_sort_ratio, score_cutoff=75)\n remedio_encontrado = remedio_encontrado[0] if remedio_encontrado is not None else None\n \n if remedio_encontrado:\n if not verificar_cliente_possui_venda(numero):\n cliente = get_api('https://marcia-api.herokuapp.com/cliente/numero/{}'.format(numero)).json()\n print(\"Status cadastro venda: \", cadastrar_venda(cliente['clienteId']))\n preco = [p['preco'] for p in remedios if p['nome'].lower() == remedio_encontrado][0]\n id_remedio = [p['id'] for p in remedios if p['nome'].lower() == remedio_encontrado][0]\n preco = preco*int(quantidade)\n lista_produtos.append({'remedio': remedio_encontrado , 'quantidade': quantidade, 'preco_total': preco, 'id': id_remedio})\n return 'Você gostaria de comprar {} {}?'.format(quantidade, remedio_encontrado)\n return \"Desculpe, mas não encontramos nenhum remédio com este nome: {}\".format(medicine)\n\ndef verificar_cliente_possui_venda(numero):\n \n cliente = get_api('https://marcia-api.herokuapp.com/cliente/numero/{}'.format(numero)).json()\n vendas = get_api('https://marcia-api.herokuapp.com/venda')\n vendas_status = vendas.status_code\n vendas = vendas.json()\n venda_cliente = []\n if len(vendas) > 0 and vendas_status == 200:\n venda_cliente = [v for v in vendas if v['clienteId'] == cliente['clienteId']]\n if len(venda_cliente) > 0:\n return True\n return False\n\ndef ultima_venda_cliente(numero):\n cliente = get_api('https://marcia-api.herokuapp.com/cliente/numero/{}'.format(numero)).json()\n vendas = get_api('https://marcia-api.herokuapp.com/venda').json()\n venda_cliente = [v for v in vendas if v['clienteId'] == cliente['clienteId']]\n if len(venda_cliente) > 0:\n return venda_cliente[-1]\n return None\n\n\n","sub_path":"whatsappbot/events/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":5563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354496060","text":"import math\nimport pandas\nimport time\nimport csv\nimport os\nimport zipfile\nimport shutil\nimport glob\nimport sys\nfrom osgeo import gdal\n\n\n\n\ndef extract_img_data(image_file):\n print(image_file)\n zip_ref = zipfile.ZipFile(image_file, 'r')\n zip_ref.extractall('temp_dir2')\n zip_ref.close()\n print(\"zip extracted\")\n\n file = glob.glob('temp_dir2/*.img')[0]\n shutil.copy(file,\"output2.img\")\n print(\"img extracted\")\n\n shutil.rmtree('temp_dir2')\n print(\"temp files deleted\")\n\n\n\ndef get_elevation_array():\n img=gdal.Open(\"output2.img\")\n inputArray=img.ReadAsArray()\n print(\"array extracted\")\n return inputArray\n\n\ndef get_elevation_in_meters(elevation_array, lat, lng, boundingBox):\n #print(boundingBox)\n #print(lat)\n #print(lng)\n array_length = len(elevation_array)\n #print(array_length)\n\n y_range = boundingBox['maxY'] - boundingBox['minY']\n y_stop_length = y_range/array_length\n y_diff = boundingBox['maxY'] - (lat)\n y_stops = y_diff/y_stop_length\n\n x_range = boundingBox['maxX'] - boundingBox['minX']\n x_stop_length = x_range/array_length\n x_diff = lng - boundingBox['minX']\n x_stops = x_diff/x_stop_length\n if y_stops >= 0 and x_stops >= 0 and y_stops < array_length and x_stops < array_length:\n elevation = elevation_array[int(y_stops)][int(x_stops)]\n if elevation == -3.4028234663852886e+38:\n elevation = None\n else:\n elevation = None\n return elevation\n\ndef process_grid_square(image_file,road_file,bounding_box_string):\n\n\n boundingBox = {}\n for x in (bounding_box_string[1:-2].split(\",\")):\n boundingBox[x.split(\":\")[0]] = float(x.split(\":\")[1])\n\n print(boundingBox)\n extract_img_data(image_file)\n elevation_array = get_elevation_array()\n\n print(get_elevation_in_meters(elevation_array, 33, -85, boundingBox))\n\n pandas.options.mode.chained_assignment = None\n df = pandas.read_csv(road_file,\n header=0,\n names=['id','name','something','code','latitude','longitude','state','county'])\n #print(df)\n max_lat = (math.ceil(df['latitude'].max()))\n min_lat = (math.floor(df['latitude'].min()))\n max_lng = (math.ceil(df['longitude'].max()))\n min_lng = (math.floor(df['longitude'].min()))\n\n if abs(min_lng) < 100:\n zero_pad = \"0\"\n else:\n zero_pad = \"\"\n\n print(max_lat)\n print(min_lat)\n print(max_lng)\n print(min_lng)\n\n print(\"grid n%sw%s%s\" % (int(max_lat),zero_pad,int(abs(min_lng))))\n print(df.state.unique())\n #print(df[df.state == 'GA'].sort_values(['a', 'b'], ascending=[True, False]))\n\n def get_elevation(row):\n return get_elevation_in_meters(elevation_array, row['latitude'], row['longitude'], boundingBox)\n\n #print(df.apply(get_elevation,axis=1))\n df['height'] = df.apply(get_elevation,axis=1)\n df['road_file'] = road_file.split(\"/\")[-1]\n df['image_file'] = image_file.split(\"/\")[-1]\n for state in df.state.unique():\n sorted = df[df.state == state].sort_values(['height'],ascending=[False])\n cols = ['height']\n #sorted[cols] = df[df[cols] > 0][cols]\n sorted = sorted.dropna(subset=cols)\n #print(sorted)\n #sorted.head(100).to_csv(\"final/%s_high.csv\" % (state), mode='a', header=False)\n sorted.to_csv(\"finalwy/%s_full_grid_to_check.csv\" % (state), mode='a', header=False)\n print(sorted.tail(1).values)\ndef single_test():\n elevation_array = get_elevation_array()\n\n bounding_box_string = \"{minY:32.99944444444,minX:-85.00055555556,maxY:34.00055555556,maxX:-83.99944444444}\"\n boundingBox = {}\n for x in (bounding_box_string[1:-2].split(\",\")):\n boundingBox[x.split(\":\")[0]] = float(x.split(\":\")[1])\n\n lat = 33.977315999889825\n lng = -84.57929766694424\n\n print(get_elevation_in_meters(elevation_array, lat, lng, boundingBox))\n\n\nmaster_df = pandas.read_csv(\"wyomingidaho.csv\",\n header=0)\n\nfor row in master_df.itertuples(index=True, name='Pandas'):\n bounding_box_string = getattr(row, \"boundingbox\")\n image_file = \"/home/ed/Downloads/%s\" % (getattr(row, \"image_file\"))\n road_file = \"grids/%s\" % getattr(row, \"road_file\")\n try:\n process_grid_square(image_file,road_file,bounding_box_string)\n\n except:\n continue\n","sub_path":"grid_scan_test_single_output.py","file_name":"grid_scan_test_single_output.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"604118526","text":"import os\nimport gym\nimport torch\nimport pprint\nimport argparse\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom tianshou.policy import SACMUTRIRB2BPolicy\nfrom tianshou.trainer import offpolicy_exact_trainer\nfrom tianshou.data import Collector, ReplayBufferTriple\nfrom tianshou.env import VectorEnv, SubprocVectorEnv\nfrom tianshou.utils.net.common import Net\nfrom tianshou.utils.net.continuous import ActorProb_RLKIT as ActorProb, Critic_RLKIT as Critic\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--task', type=str, default='HalfCheetah-v2')\n parser.add_argument('--seed', type=int, default=0)\n parser.add_argument('--buffer-size', type=int, default=int(1e6))\n parser.add_argument('--actor-lr', type=float, default=3e-4)\n parser.add_argument('--alpha-lr', type=float, default=3e-4)\n parser.add_argument('--critic-lr', type=float, default=3e-4)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--tau', type=float, default=0.005)\n parser.add_argument('--alpha', type=float, default=0.2)\n parser.add_argument('--epoch', type=int, default=1000)\n parser.add_argument('--step-per-epoch', type=int, default=1000)\n parser.add_argument('--collect-per-step', type=int, default=1)\n parser.add_argument('--batch-size', type=int, default=256)\n parser.add_argument('--hidden_size', type=int, default=256)\n parser.add_argument('--layer-num', type=int, default=2)\n parser.add_argument('--training-num', type=int, default=1)\n parser.add_argument('--test-num', type=int, default=10)\n parser.add_argument('--logdir', type=str, default='log')\n parser.add_argument('--render', type=float, default=0.)\n parser.add_argument('--auto_alpha', type=bool, default=True)\n parser.add_argument('--device', type=str, default='cpu')\n parser.add_argument('--tor_diff', type=float, default=0.1)\n parser.add_argument('--shared', type=bool, default=False)\n args = parser.parse_known_args()[0]\n return args\n\ndef process_tri(batch, rng, beta=1):\n \"\"\"\n We contrust continuous transition here\n Note that: done_bk is the original done signal from the environment, indicating whether the episode is finished,\n while done is processed to indicate whether the game is failed. The reason while we need done_bk is we\n don't want the second transition is not from the same episode. Therefore, if done_bk is true, which means\n the episode is finished at the first transition, we don't construct continuous transition\n \"\"\"\n\n # beta distribution for sampling the interpolation ratio, where beta is the temperature\n blend_ratio = rng.beta(beta, beta, *batch.rew.shape) * (1 - batch.done_bk)\n\n # construct continuous transition\n obs = batch.obs + blend_ratio[:, None] * (batch.obs_next - batch.obs)\n obs_next = batch.obs_next + blend_ratio[:, None] * (batch.obs_next_next - batch.obs_next)\n act = batch.act + blend_ratio[:, None] * (batch.act_next - batch.act)\n rew = batch.rew + blend_ratio * (batch.rew_next - batch.rew)\n done = batch.done + blend_ratio * (batch.done_next * 1. - batch.done)\n\n # replace the original discrete transition\n batch.obs = obs\n batch.obs_next = obs_next\n batch.rew = rew\n batch.act = act\n batch.done = done\n batch.blend = blend_ratio[:, None]\n\n return batch\n\ndef test_sac(args=get_args()):\n # initialize environment\n env = gym.make(args.task)\n args.state_shape = env.observation_space.shape or env.observation_space.n\n args.action_shape = env.action_space.shape or env.action_space.n\n args.max_action = env.action_space.high[0]\n train_envs = VectorEnv(\n [lambda: gym.make(args.task) for _ in range(args.training_num)])\n test_envs = SubprocVectorEnv(\n [lambda: gym.make(args.task) for _ in range(args.test_num)])\n # seed\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n train_envs.seed(args.seed)\n test_envs.seed(args.seed)\n # model\n actor = ActorProb(\n args.layer_num, args.state_shape, args.action_shape,\n args.max_action, args.device, hidden_layer_size=args.hidden_size\n ).to(args.device)\n actor_optim = torch.optim.Adam(actor.parameters(), lr=args.actor_lr)\n critic1 = Critic(\n args.layer_num, args.state_shape, args.action_shape, args.device, hidden_layer_size=args.hidden_size\n ).to(args.device)\n critic1_optim = torch.optim.Adam(critic1.parameters(), lr=args.critic_lr)\n critic2 = Critic(\n args.layer_num, args.state_shape, args.action_shape, args.device, hidden_layer_size=args.hidden_size\n ).to(args.device)\n critic2_optim = torch.optim.Adam(critic2.parameters(), lr=args.critic_lr)\n # energy-based discriminator\n disc = Critic(\n args.layer_num, np.prod(args.state_shape)+np.prod(args.action_shape), 0, args.device, hidden_layer_size=args.hidden_size,\n output_dim=np.prod(args.state_shape)+1,\n ).to(args.device)\n disc_optim = torch.optim.Adam(disc.parameters(), lr=args.critic_lr)\n # tunable temperature\n beta = torch.ones(1, requires_grad=True, device=args.device)\n beta_optim = torch.optim.Adam([beta], lr=args.critic_lr)\n\n if args.auto_alpha:\n target_entropy = -np.prod(env.action_space.shape)\n log_alpha = torch.zeros(1, requires_grad=True, device=args.device)\n alpha_optim = torch.optim.Adam([log_alpha], lr=args.alpha_lr)\n alpha = (target_entropy, log_alpha, alpha_optim)\n else:\n alpha = args.alpha\n\n rng = np.random.RandomState(seed=args.seed)\n\n policy = SACMUTRIRB2BPolicy(\n actor, actor_optim, critic1, critic1_optim, critic2, critic2_optim,\n args.tau, args.gamma, alpha,\n [env.action_space.low[0], env.action_space.high[0]],\n reward_normalization=False, ignore_done=False, norm_diff=False, use_diff=False,\n process_tri=(lambda x, beta: process_tri(x, rng=rng, beta=beta)), # continuous transition construction\n beta=(beta, beta_optim), # the tunable temperature\n discriminator=(disc, disc_optim), # the energy-based discriminator\n tor_diff=args.tor_diff # the tolerance of distance\n )\n # collector\n if args.training_num == 0:\n max_episode_steps = train_envs._max_episode_steps\n else:\n max_episode_steps = train_envs.envs[0]._max_episode_steps\n train_collector = Collector(\n policy, train_envs, ReplayBufferTriple(args.buffer_size, max_ep_len=max_episode_steps))\n test_collector = Collector(policy, test_envs, mode='test')\n # log\n log_path = os.path.join(args.logdir, args.task, 'sac_ct', str(args.seed))\n writer = SummaryWriter(log_path)\n\n def save_fn(policy, name='policy.pth'):\n torch.save(policy.state_dict(), os.path.join(log_path, name))\n\n env.spec.reward_threshold = 100000\n\n def stop_fn(x):\n return x >= env.spec.reward_threshold\n\n # trainer\n result = offpolicy_exact_trainer(\n policy, train_collector, test_collector, args.epoch,\n args.step_per_epoch, args.collect_per_step, args.test_num,\n args.batch_size, stop_fn=stop_fn, save_fn=save_fn, writer=writer, epochs_to_save=[1, 50, 100, 150, 200])\n assert stop_fn(result['best_reward'])\n train_collector.close()\n test_collector.close()\n if __name__ == '__main__':\n pprint.pprint(result)\n # Let's watch its performance!\n env = gym.make(args.task)\n collector = Collector(policy, env)\n result = collector.collect(n_episode=1, render=args.render)\n print(f'Final reward: {result[\"rew\"]}, length: {result[\"len\"]}')\n collector.close()\n\n\nif __name__ == '__main__':\n test_sac()\n","sub_path":"tianshou_icra/examples/mujoco_sac_ct.py","file_name":"mujoco_sac_ct.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"429605157","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport smtplib\r\nfrom variables import email, password, user_agent, email_from, email_to, stipulated_price, url\r\nimport time\r\nimport pandas as pd\r\nfrom datetime import datetime\r\n\r\n\r\nclass AmazonTracker:\r\n\r\n def __init__(self, url, headers):\r\n page = requests.get(url, headers=headers)\r\n soup = BeautifulSoup(page.content, 'html.parser',)\r\n # Gets the product's Name by it's id\r\n product_title = str(soup.find(id=\"productTitle\").getText().strip())\r\n print('Product:', product_title)\r\n # Gets the product's Price by it's id\r\n self.product_price = str(soup.find(id=\"priceblock_ourprice\").getText())\r\n print('Price:', self.product_price)\r\n\r\n def check_price(self, stipulated_price):\r\n # List of Prices\r\n price_list = []\r\n # List of times when prices were save\r\n time_list = []\r\n\r\n # Clean product_price variable\r\n product_price = self.product_price.replace('£', '')\r\n converted_price = float(product_price)\r\n\r\n # While loop checks if product price is bellow the price stipulated\r\n while converted_price > stipulated_price:\r\n # Gets time when price was saved and adds it to the time_list\r\n now = datetime.now()\r\n date_time = now.strftime(\"%d/%m/%Y %H:%M:%S\")\r\n time_list.append(date_time)\r\n print('Time: ', time_list)\r\n\r\n # Gets price and adds it to the price_list\r\n price_list.append(converted_price)\r\n print('Price', price_list)\r\n\r\n # Generate dataframe from list and write to xlsx.\r\n df = pd.DataFrame({'Time': time_list, 'Price': price_list})\r\n writer = pd.ExcelWriter('amazon_price_list.xlsx', engine='xlsxwriter')\r\n df.to_excel(writer, sheet_name='Sheet1')\r\n writer.save()\r\n\r\n # Frequence of price check\r\n time.sleep(5)\r\n\r\n # If price drops bellow stipulated price calls method send_email()\r\n self.send_email()\r\n\r\n\r\n def send_email(self):\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo() #command sent by email to identify itself when connecting to another email\r\n server.starttls() #incript connection\r\n server.ehlo()\r\n server.login(email, password)\r\n\r\n # Email composition\r\n subject = 'Price Alert!'\r\n body = ('Price Feel Down! \\n\\nClick link to check: ' + url)\r\n msg = f\"Subject: {subject}\\n\\n{body}\"\r\n\r\n # Send Email\r\n server.sendmail(email_from, #from\r\n email_to, #to\r\n msg) #email\r\n print('Email sent!')\r\n # Shuts server\r\n server.quit()\r\n\r\n\r\nheaders = {\"User-Agent\": user_agent}\r\namazon_tracker = AmazonTracker(url, headers)\r\namazon_tracker.check_price(stipulated_price)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"258712155","text":"import cv2\nimport numpy as np\nimport dlib\n\n\ndetector = dlib.get_frontal_face_detector()\ndef 人脸定位(img):\n dets = detector(img, 0)\n if not dets:\n return None\n return max(dets, key=lambda det: (det.right() - det.left()) * (det.bottom() - det.top()))\n\n\npredictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\ndef 提取关键点(img, 脸位置):\n landmark_shape = predictor(img, 脸位置)\n 关键点 = []\n for i in range(68):\n pos = landmark_shape.part(i)\n 关键点.append(np.array([pos.x, pos.y], dtype=np.float32))\n return 关键点\n\n\ndef 生成构造点(关键点):\n 左眉 = [19, 20, 21]\n 右眉 = [22, 23, 24]\n 下巴 = [6, 7, 8, 9, 10]\n 鼻子 = [29, 30]\n\n 眉中心 = sum([关键点[i] for i in 左眉 + 右眉]) / 6\n 下巴中心 = sum([关键点[i] for i in 下巴]) / 5\n 鼻子中心 = sum([关键点[i] for i in 鼻子]) / 2\n\n return 眉中心, 下巴中心, 鼻子中心\n\n\ndef 生成特征(构造点):\n 眉中心, 下巴中心, 鼻子中心 = 构造点\n 中线 = 眉中心 - 下巴中心\n 斜边 = 眉中心 - 鼻子中心\n 旋转量 = np.cross(中线, 斜边) / np.linalg.norm(中线)**2\n return 旋转量\n\n\ndef 画图(旋转量):\n img = np.ones([512, 512], dtype=np.float32)\n 脸长 = 200\n 中心 = 256, 256\n 左眼 = int(220 - 旋转量 * 脸长), 249\n 右眼 = int(292 - 旋转量 * 脸长), 249\n 嘴 = int(256 - 旋转量 * 脸长 * 0.5), 310\n cv2.circle(img, 中心, 100, 0, 1)\n cv2.circle(img, 左眼, 15, 0, 1)\n cv2.circle(img, 右眼, 15, 0, 1)\n cv2.circle(img, 嘴, 5, 0, 1)\n return img\n\n\nif __name__ == '__main__':\n cap = cv2.VideoCapture(0)\n # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)\n # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)\n while True:\n ret, img = cap.read()\n img = cv2.flip(img, 1)\n 脸位置 = 人脸定位(img)\n if not 脸位置:\n cv2.imshow('self', img)\n cv2.waitKey(1)\n continue\n 关键点 = 提取关键点(img, 脸位置)\n # for i, (px, py) in enumerate(关键点):\n # cv2.putText(img, str(i), (int(px),int(py)), cv2.FONT_HERSHEY_COMPLEX, 0.25, (255, 255, 255))\n 构造点 = 生成构造点(关键点)\n # for i, (px, py) in enumerate(构造点):\n # cv2.putText(img, str(i), (int(px),int(py)), cv2.FONT_HERSHEY_COMPLEX, 0.25, (255, 255, 255))\n 旋转量 = 生成特征(构造点)\n # cv2.putText(img, '%.3f' % 旋转量,\n # (int(构造点[-1][0]), int(构造点[-1][1])), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))\n cv2.imshow('self', img)\n cv2.imshow('Vtuber', 画图(旋转量))\n cv2.waitKey(1)\n","sub_path":"1/龙.py","file_name":"龙.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"466598048","text":"class Solution:\n def rangeBitwiseAnd(self, m: int, n: int) -> int:\n shift = 0 \n # 找到公共前缀\n while m < n:\n m = m >> 1\n n = n >> 1\n shift += 1\n return m << shift\n\n# 作者:LeetCode-Solution\n# 链接:https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/solution/shu-zi-fan-wei-an-wei-yu-by-leetcode-solution/\n# 来源:力扣(LeetCode)\n# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n\n# 「Brian Kernighan 算法」清除二进制串中最右边的 1。\n# ! 布赖恩·克尼根: \n# 1. 是否可以像人类直观的计数比特为 1 的位数,跳过两个 1 之间的 0。例如:10001000。\n# 2. 抹去'最右'边的 1\n# while x:\n# x = x & (x-1)\nclass Solution:\n def rangeBitwiseAnd(self, m: int, n: int) -> int:\n while m < n:\n # 抹去最右边的 1\n n = n & (n - 1)\n return n\n","sub_path":"bits/201_数字范围按位与.py","file_name":"201_数字范围按位与.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68203513","text":"import warnings\n\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom classets import NN, ANN, CNN, ECG, TorchvisionDatasetWrapper\n\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom torchvision import transforms\nfrom tqdm import tqdm\n\nfrom time import time as t\n\nfrom bindsnet.encoding import PoissonEncoder\nfrom bindsnet.network import load\nfrom bindsnet.network.monitors import Monitor\nfrom bindsnet.utils import get_square_weights, get_square_assignments\nfrom bindsnet.evaluation import (\n all_activity,\n proportion_weighting,\n assign_labels,\n)\n\nfrom sklearn.svm import SVR\n\ninterV\t= 128 * 4 # * 4\ntrainN\t= 60000 # 600 # 60000 # 2000\ntestN\t= 7938 # 240 # 7938 # 340\nneuronN = 6144\ntimeT = 600\nbatch_size = 64\ninterval = 1\n\nTR = 'training_fft_slide_3.pt' # './training_fft_slide_3.pt # './training_fft_2n2.pt' # './training_fft_1r.pt' # './training_fft_slide_1.pt'\nTE = 'test_fft_slide_3.pt' # './test_fft_slide_3.pt' tr# './test_fft_2n2.pt' # './test_fft_1r.pt' # './test_fft_slide_1.pt'\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--seed\", type=int, default=0)\nparser.add_argument(\"--n_neurons\", type=int, default=neuronN)\nparser.add_argument(\"--n_epochs\", type=int, default=1)\nparser.add_argument(\"--n_test\", type=int, default=testN)\nparser.add_argument(\"--n_train\", type=int, default=trainN)\nparser.add_argument(\"--n_workers\", type=int, default=-1)\nparser.add_argument(\"--exc\", type=float, default=22.5)\nparser.add_argument(\"--inh\", type=float, default=120)\nparser.add_argument(\"--theta_plus\", type=float, default=0.05)\nparser.add_argument(\"--time\", type=int, default=timeT)\nparser.add_argument(\"--dt\", type=int, default=1.0)\nparser.add_argument(\"--intensity\", type=float, default=128)\nparser.add_argument(\"--progress_interval\", type=int, default=10)\nparser.add_argument(\"--update_interval\", type=int, default=50)\nparser.add_argument(\"--train\", dest=\"train\", action=\"store_true\")\nparser.add_argument(\"--test\", dest=\"train\", action=\"store_false\")\nparser.add_argument(\"--plot\", dest=\"plot\", action=\"store_true\")\nparser.add_argument(\"--gpu\", dest=\"gpu\", action=\"store_true\")\nparser.set_defaults(plot=False, gpu=True)\n\nargs = parser.parse_args()\n\nseed = args.seed\nn_neurons = args.n_neurons\nn_epochs = args.n_epochs\nn_test = args.n_test\nn_train = args.n_train\nn_workers = args.n_workers\nexc = args.exc\ninh = args.inh\ntheta_plus = args.theta_plus\ntime = args.time\ndt = args.dt\nintensity = args.intensity\nprogress_interval = args.progress_interval\nupdate_interval = args.update_interval\ntrain = args.train\nplot = args.plot\ngpu = args.gpu\n\n# Sets up Gpu use\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nif gpu and torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\nelse:\n torch.manual_seed(seed)\n device = \"cpu\"\n if gpu:\n gpu = False\n\ntorch.set_num_threads(os.cpu_count() - 1)\nprint(\"Running on Device = \", device)\n\n# Determines number of workers to use\nif n_workers == -1:\n n_workers = gpu * 4 * torch.cuda.device_count()\n\nnetwork = load(f\"network_N{neuronN}_T{timeT}_{TR}\")\n\n# Directs network to GPU\nif gpu:\n network.to(\"cuda\")\n\n# Load MNIST data.\ntrain_dataset = TorchvisionDatasetWrapper(\n PoissonEncoder(time=time, dt=dt),\n None,\n root=os.path.join(\"..\", \"..\", \"data\", \"ECG\"),\n TR=TR,\n TE=TE,\n download=True,\n train=True,\n transform=transforms.Compose(\n [transforms.ToTensor()]\n ),\n)\n\n\n# Record spikes during the simulation.\nspike_record = torch.zeros((update_interval, int(time / dt), n_neurons), device=device)\n\n# Sequence of accuracy estimates.\naccuracy = {\"all\": [], \"proportion\": []}\n\n# Voltage recording for excitatory and inhibitory layers.\nexc_voltage_monitor = Monitor(\n network.layers[\"Ae\"], [\"v\"], time=int(time / dt), device=device\n)\n\n#inh_voltage_monitor = Monitor(\n# network.layers[\"Ai\"], [\"v\"], time=int(time / dt), device=device\n#)\nnetwork.add_monitor(exc_voltage_monitor, name=\"exc_voltage\")\n#network.add_monitor(inh_voltage_monitor, name=\"inh_voltage\")\n\n# Set up monitors for spikes and voltages\nspikes = {}\nfor layer in set(network.layers):\n spikes[layer] = Monitor(\n network.layers[layer], state_vars=[\"s\"], time=int(time / dt), device=device\n )\n network.add_monitor(spikes[layer], name=\"%s_spikes\" % layer)\n\nvoltages = {}\nfor layer in set(network.layers) - {\"X\"}:\n voltages[layer] = Monitor(\n network.layers[layer], state_vars=[\"v\"], time=int(time / dt), device=device\n )\n network.add_monitor(voltages[layer], name=\"%s_voltages\" % layer)\n\n\n# Inference optimizing the network\nprint(\"\\nInference caculating.\\n\") \nnetwork.train(mode=False)\n\nstart = t()\n\nX_data = np.zeros((trainN, neuronN))\nlabels = np.zeros((trainN))\n\nfor epoch in range(1):\n print(\"infer:\", epoch+1)\n if epoch % progress_interval == 0:\n print(\"Progress: %d / %d (%.4f seconds)\" % (epoch, n_epochs, t() - start))\n start = t()\n\n # Create a dataloader to iterate and batch data\n dataloader = torch.utils.data.DataLoader(\n train_dataset, batch_size=batch_size, shuffle=True, num_workers=n_workers, pin_memory=gpu\n )\n\n for step, batch in enumerate(tqdm(dataloader)):\n if step > n_train:\n break\n # Get next input sample.\n inputs = {\"X\": batch[\"encoded_image\"].permute(1, 0, 2).unsqueeze(dim=2)}\n if gpu:\n inputs = {k: v.cuda() for k, v in inputs.items()}\n #print(inputs[\"X\"].sum())\n Y = batch[\"label\"]\n \n # Run the network on the input.\n network.run(inputs=inputs, time=time, input_time_dim=1)\n\n # Add to spikes recording.\n X = spikes[\"Ae\"].get(\"s\").permute(1, 0, 2).sum(dim=1)\n \n index = (step+1) * batch_size\n X_data[index - batch_size:index if index < trainN else trainN] = X.cpu().numpy()\n labels[index - batch_size:index if index < trainN else trainN] = Y.cpu().numpy()\n\n network.reset_state_variables() # Reset state variables.\n\n\nprint(\"Progress: %d / %d (%.4f seconds)\" % (epoch + 1, n_epochs, t() - start))\nprint(\"Caculating complete.\\n\")\n\nprint(X_data.shape)\nprint(labels.shape)\n\nmodel = SVR()\n#X_data = np.concatenate((X_data, X_data), axis=0)\n#labels = np.concatenate((labels, labels), axis=0)\nmodel.fit(X_data, labels)\nrelation_square = model.score(X_data, labels)\n\n# Load MNIST data.\ntest_dataset = TorchvisionDatasetWrapper(\n PoissonEncoder(time=time, dt=dt),\n None,\n root=os.path.join(\"..\", \"..\", \"data\", \"ECG\"),\n TR=TR,\n TE=TE,\n download=True,\n train=False,\n transform=transforms.Compose(\n [transforms.ToTensor()]#, transforms.Lambda(lambda x: x * intensity)]\n ),\n)\n\n# Sequence of accuracy estimates.\nmse = 0\nmae = 0\nmape = 0\n\n# Record spikes during the simulation.\nspike_record = torch.zeros((1, int(time / dt), n_neurons), device=device)\n\n# Train the network.\nprint(\"\\nBegin testing\\n\")\nstart = t()\n\nwith torch.no_grad():\n\n # Create a dataloader to iterate and batch data\n dataloader = torch.utils.data.DataLoader(\n test_dataset, batch_size=batch_size, shuffle=True, num_workers=n_workers, pin_memory=gpu\n )\n\n\n for step, batch in enumerate(tqdm(dataloader)):\n if step > n_test:\n break\n # Get next input sample.\n inputs = {\"X\": batch[\"encoded_image\"].permute(1, 0, 2).unsqueeze(dim=2)}\n if gpu:\n inputs = {k: v.cuda() for k, v in inputs.items()}\n\n # Run the network on the input.\n network.run(inputs=inputs, time=time, input_time_dim=1)\n\n # Add to spikes recording.\n X = spikes[\"Ae\"].get(\"s\").permute(1, 0, 2).sum(dim=1).cpu().numpy()\n Y = batch[\"label\"].cpu().numpy()\n \n hypothesis = model.predict(X)\n mse += np.power(hypothesis - Y, 2).sum()\n mae += np.abs(hypothesis - Y).sum()\n mape += (np.abs(hypothesis - Y) / Y).sum()\n\n network.reset_state_variables() # Reset state variables.\n #pbar.set_description_str(\"Test progress: \")\n #pbar.update()\n\nmse /= testN\nmae /= testN\nmape /= testN\nmape *= 100\n\nprint(\"\\nMSE: %.4f\" % (mse))\nprint(\"\\nRMSE: %.4f\" % (np.sqrt(mse)))\nprint(\"\\nMAE: %.4f\" % (mae))\nprint(\"\\nMAPE: %.4f\" % (mape))\nprint(\"\\nR: %.4f\" % (relation_square)) \n\nprint(\"Progress: %d / %d (%.4f seconds)\" % (epoch + 1, n_epochs, t() - start))\nprint(\"Testing complete.\\n\")\n\n","sub_path":"optimize_svr.py","file_name":"optimize_svr.py","file_ext":"py","file_size_in_byte":8393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"249219843","text":"# encoding: utf-8\n\nclass Table(object):\n def config_db(self,pkg):\n tbl=pkg.table('answer', pkey='id', name_long='!![en]Answer', \n name_plural='!![en]Answers',\n caption_field='description')\n self.sysFields(tbl)\n tbl.column('question_id',size='22', group='_', name_long='!![en]Question'\n ).relation('question.id', relation_name='answers',\n mode='foreignkey', \n onDelete='cascade')\n tbl.column('description', name_long='!![en]Description')\n tbl.column('html_description', name_long='!![en]Html Description')","sub_path":"packages/lrn/model/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"60968065","text":"import os\nimport sys, getopt\ndef main(argv):\n inputfile = 'c:/oracle/accessi_db.txt'\n base_path = os.sep+'ORACLE'+os.sep+'connessionisqlcl'\n putty_path = os.sep+'Users'+os.sep+'ccudizio'+os.sep+'utils'\n opts, args = getopt.getopt(argv,\"hi:o:\",[\"ifile=\"]) \n for opt, arg in opts:\n if opt == '-h':\n print(sys.argv[0]+' -i <inputfile>')\n sys.exit()\n elif opt in (\"-i\", \"--ifile\"):\n if arg!='':\n inputfile = arg\n if opt == '-o':\n conn_string = arg\n print('Input file is \"', inputfile)\n #inputfile='c:/oracle/accessi_db.txt'\n flist = open(inputfile,'r')\n flist_readed_lines = flist.readlines()\n flist.close()\n for line in flist_readed_lines: \n if not line.strip().startswith('#'):\n #parse line to get info:\n line_items = line.strip().split('/')\n cmd_file_name = base_path+os.sep+line_items[0]+'_'+line_items[1]+'.cmd'\n cmd_putty_file_name = base_path+os.sep+'putty'+os.sep+line_items[0]+'.cmd'\n cmd_file_handle =open(cmd_file_name,'w+')\n cmd_file_handle.write('call '+base_path+os.sep+'env.cmd \\n')\n cmd_file_handle.write('start sql ')\n cmd_file_handle.write(line_items[1]+'/'+line_items[2]+'@'+line_items[0])\n cmd_file_handle.write(' \\n')\n cmd_file_handle.close()\n #cmd_putty_file_name = base_path+os.sep+'putty'+os.sep+line_items[0]+'.cmd'\n #cmd_putty_file_handle =open(cmd_putty_file_name,'w+')\n #cmd_putty_file_handle.write(putty_path+os.sep+'PUTTY.EXE ')\n #cmd_putty_file_handle.write('ae48915@'+line_items[3]+' -pw Eneluser13$')\n #os.system('sqlplus '+line_items[0]+'/'+line_items[1]+'@'+line_items[2]) \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"test-python/genera_cmd_sqlcl.py","file_name":"genera_cmd_sqlcl.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"382617081","text":"\n# coding: utf-8\n\n# In[71]:\n\n#dynamic programming\ndef max_sub_array(nums):\n #for storing bigger sum for i between max(i,sum(i-1)+i)\n additional_sum = nums[0] + nums[1]\n #select max for i between maxim(i-1) and sum(i)\n maxim = nums[0] + nums[1]\n for i in range(2,len(nums)):\n additional_sum = max(nums[i]+nums[i-1],nums[i]+additional_sum) \n maxim = max(additional_sum,maxim)\n return maxim\n\n\n# In[72]:\n\nmax_sub_array([-2,-1,-3,-4,-1])\n\n\n# In[73]:\n\nmax_sub_array([10,-2,3,-7,8,-4,-2,5])\n\n\n# In[ ]:\n\n\n\n","sub_path":"old/other/max_sub_array_for2.py","file_name":"max_sub_array_for2.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83780446","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\n\nclass XiciPipeline(object):\n def process_item(self, item, spider):\n proxies = item[\"http\"] + \"://\" + item[\"ip\"] + \":\" + item[\"port\"] + \" \"\n print(proxies)\n with open('proxies.txt','a') as f:\n f.write(proxies)\n\n return item\n","sub_path":"xici/xici/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623893593","text":"import os\nfrom pathlib import Path\nfrom wand.image import Image\nfrom tests.test_sarscov2_consensus_acceptance import FileTestCase\nfrom qc.samtools_depth_plots import make_plots\n\n\nclass SamtoolsDepthPlotsTest(FileTestCase):\n def test_make_plots(self):\n expected_depth_lines_fp = f\"{self.gs_qc_dir}/2021-02-08-ARTIC-depth_lineplot.pdf\"\n expected_depth_violin_fp = f\"{self.gs_qc_dir}/2021-02-08-ARTIC-depth_violin.pdf\"\n\n depth_fps = [str(p) for p in Path(self.test_samples_dir).rglob('*.depth.txt')]\n out_depth_lines_fp = f\"{self.test_temp_dir}/temp_test_depth_lines.pdf\"\n out_depth_violin_fp = f\"{self.test_temp_dir}/temp_test_depth_violin.pdf\"\n arg_list = [\"samtools_depth_plots.py\",\n out_depth_lines_fp, out_depth_violin_fp]\n arg_list.extend(depth_fps)\n\n try:\n make_plots(arg_list)\n\n # PDFs are vectorial, so we need to set a resolution when\n # converting to an image\n actual_lines = Image(filename=out_depth_lines_fp, resolution=150)\n with Image(filename=expected_depth_lines_fp,\n resolution=150) as expected_line:\n diff_lines = actual_lines.compare(\n expected_line, metric='root_mean_square')\n self.assertLess(diff_lines[1], 0.01)\n\n actual_violin = Image(filename=out_depth_violin_fp, resolution=150)\n with Image(filename=expected_depth_violin_fp,\n resolution=150) as expected_violin:\n diff_violin = actual_violin.compare(\n expected_violin, metric='root_mean_square')\n self.assertLess(diff_violin[1], 0.01)\n finally:\n for out_fp in [out_depth_lines_fp, out_depth_violin_fp]:\n try:\n os.remove(out_fp)\n except OSError:\n pass\n","sub_path":"tests/test_samtools_depth_plots.py","file_name":"test_samtools_depth_plots.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467543656","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 18 13:41:22 2014\n@author: Kyle Ellefsen\n\nThis file can open a Flika excel file and delete duplicate puffs. Duplicate puffs are considered those with the same time point and within 1 pixel of each other.\nUncomment the last lines to save and close the workbook\nThis site has a guide for manipulating excel sheets with win32com: http://pythonexcels.com/python-excel-mini-cookbook/\n\"\"\"\n\nfrom __future__ import (absolute_import, division,print_function, unicode_literals)\nfrom future.builtins import (bytes, dict, int, list, object, range, str, ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)\nimport numpy as np\nimport win32com.client\nfrom win32com.client import constants\nfrom pyqtgraph import plot, show\n\n\n##############################################################################\n####### THESE ARE THE VARIABLES YOU CAN SET ###########\n##############################################################################\n\nfilename=\"C:\\\\Users\\\\George\\\\Desktop\\\\Regrouped_puffs\\\\110826_SY5Y_1uMIP3_1uMFluo4_5uMEGTA_200msFlash_FullPower_22C_003.xlsx\"\n\n##############################################################################\n\nexcel = win32com.client.Dispatch(\"Excel.Application\")\nexcel.Visible = True\nworkbook = excel.Workbooks.Open(filename)\nsheet = workbook.Worksheets('Puff Data radius 3')\n\nheader=np.array(sheet.Rows(1).Value[0])\nnCols=np.max(np.argwhere(header.astype(np.bool)))+1\nnPuffs=np.max(np.argwhere(np.array(sheet.Columns(1).Value).astype(np.bool)))\nheader=header[:nCols]\npuff_info=[]\nfor row in np.arange(nPuffs)+2:\n puff=np.array(sheet.Rows(int(row)).Value[0][:nCols])\n puff_info.append(dict(zip(header,puff)))\n \nmarked_for_deletion=[]\nx0,y0,t0=[0,0,0]\nfor i,puff in enumerate(puff_info):\n x1,y1,t1=puff['x'],puff['y'],puff['t_peak']\n if np.sqrt((x1-x0)**2+(y1-y0)**2)<1 and t1==t0:\n marked_for_deletion.append(i+1)\n x0,y0,t0=x1,y1,t1\nmarked_for_deletion.reverse()\nfor i in marked_for_deletion:\n sheet.Rows(i).Delete()\n","sub_path":"2014.10.20 Remove Duplicate Puffs.py","file_name":"2014.10.20 Remove Duplicate Puffs.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"163713054","text":"class Solution:\n def minFallingPathSum(self, A: List[List[int]]) -> int:\n nrow = len(A)\n paths = [[0 for i in range(nrow)] for j in range(nrow)]\n min_path = 10**6\n for i in range(nrow):\n for j in range(nrow):\n if i == 0:\n paths[i][j] = A[i][j]\n else:\n j_ = max(j-1,0)\n j__= min(j+1,nrow-1)\n min_ = min(paths[i-1][j],paths[i-1][j_])\n min_ = min(min_,paths[i-1][j__])\n paths[i][j] = A[i][j] + min_\n if i == nrow-1:\n min_path = min(min_path,paths[i][j])\n \n return min_path\n \n","sub_path":"leetcode/medium/minimum-falling-path-sum.py","file_name":"minimum-falling-path-sum.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542843276","text":"import requests\n\nurl = \"https://www.youtube.com/?gl=TW&hl=zh-TW\"\n\npayload = {}\nheaders = {\n 'Cookie': 'YSC=7b1NZQ8FSTU; GPS=1; VISITOR_INFO1_LIVE=gxlNMPVIW0A; s_gl=ca02b225c88e6fda0cbe664706f57e38cwIAAABUVw=='\n}\n\nresponse = requests.request(\"GET\", url, headers=headers, data = payload)\n\nprint(response.text.encode('utf8'))\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433925658","text":"from comar.service import *\nimport os\n\nserviceType = \"local\"\nserviceDesc = \"Git\"\nserviceDefault = \"off\"\n\ndef start():\n try:\n options = os.env[\"GITDAEMON_OPTS\"]\n except:\n options = \"\"\n ret = run(\"/sbin/start-stop-daemon --start -q --background --exec /usr/bin/git-daemon -- %s\" % options)\n if ret == 0:\n notify(\"System.Service.changed\", \"started\")\n else:\n fail(\"Unable to start service\")\n\ndef stop():\n ret = run(\"/sbin/start-stop-daemon --stop -q --exec /usr/bin/git-daemon\")\n if ret == 0:\n notify(\"System.Service.changed\", \"stopped\")\n else:\n fail(\"Unable to stop service\")\n","sub_path":"pardus/tags/2007/programming/tools/git/comar/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"652568098","text":"import tetris.tetris as tetris\nimport copy\n\n# #\n# UTILITIES FOR POINTS #\n# #\n\n# return: start point rotated around pivot point (clockwise)\n# params: start point, pivot point\ndef rotate(point, pivot):\n return (point[1] - pivot[1] + pivot[0], pivot[0] - point[0] + pivot[1], (point[2] + 1) % 4)\n\ndef rotateReverse(point, pivot):\n return (pivot[0] + pivot[1] - point[1], point[0] + pivot[1] - pivot[0], (point[2] - 1) % 4)\n\n# checks if a point is in bounds\ndef isOutOfBounds(board, point):\n return point[0] < 0 or point[1] < 0 or point[0] >= len(board) or point[1] >= len(board[0])\n\n# return: position of active piece\n# params: game board\ndef getActivePosition(board, pivot):\n position = []\n if pivot != (-1, -1):\n position.append((pivot[0], pivot[1], 0))\n for i in range(len(board)):\n for j in range(len(board[i])):\n if not (i == pivot[0] and j == pivot[1]): # make sure it isn't pivot\n if board[i][j].state == 2: position.append((i, j, 0))\n # position[2] is the rotation, which is default, so 0\n return position\n\n# #\n# FINDING POSITIONS #\n# #\n\n# return: list of valid end positions\n# params: game board, if the piece is rotatable\ndef findPositions(board, tiles, rotatable):\n # find every translation and rotation of the initial position:\n arrangements = []\n for i in range(-tiles[0][0], -tiles[0][0] + len(board)):\n for j in range(-tiles[0][1], -tiles[0][1] + len(board[i])):\n # rotation is communitive, any pivot can be used\n arrangement = []\n for k in range(len(tiles)):\n point = (i + tiles[k][0], j + tiles[k][1], 0)\n arrangement.append(point)\n arrangements.append(arrangement)\n if rotatable: # is rotatable\n for r in range(1, 4): # for each rotation\n arrangement = copy.copy(arrangements[-1])\n pivot = arrangement[0]\n for k in range(len(arrangement)):\n arrangement[k] = rotate(arrangement[k], pivot)\n arrangements.append(arrangement)\n # prune arrangements if they are invalid:\n # meaning that they must be\n # 1) within the bounds of the board\n # 2) unable to be moved downwards (I.E. on the bottom)\n # 3) not a duplicate of another valid arrangement\n pruned = []\n for arrangement in arrangements:\n valid = True\n for point in arrangement:\n if isOutOfBounds(board, point) or board[point[0]][point[1]].isInactive():\n valid = False; break\n if valid: # if it is still valid\n for point in arrangement:\n # test if point is on bottom:\n if point[0] == len(board) - 1 or board[point[0] + 1][point[1]].isInactive():\n # check to see if arrangement is a duplicate:\n #pruned.append(arrangement)\n isDuplicate = False\n for prune in pruned:\n sameAsPrune = True\n rotation = prune[0][2] # get rotation number\n for point in arrangement:\n if (point[0], point[1], rotation) not in prune:\n #print(\"This:\", (point[0], point[1], rotation))\n #print(\"not in this:\", prune)\n #print(\"so add this:\", arrangement)\n sameAsPrune = False; break\n if sameAsPrune:\n isDuplicate = True; break\n if not isDuplicate:\n pruned.append(arrangement); break\n return pruned\n\n# #\n# UTILITIES FOR POSITIONS #\n# #\n\n# return if the positions are the same\ndef comparePosition(position, prime):\n for p in range(len(position)):\n if position[p][0] != prime[p][0] or position[p][1] != prime[p][1]:\n return False\n return True\n\ndef validPosition(board, position, target):\n for point in target:\n if point[0] < 0 or point[1] < 0 or point[0] >= len(board) or point[1] >= len(board[0]):\n return False\n if board[point[0]][point[1]].isInactive():\n return False\n if target[0][0] < position[0][0]: # if the target is above the position\n return False\n return True\n\ndef translateUp(position):\n prime = []\n for point in position:\n prime.append((point[0] - 1, point[1], point[2]))\n return prime\n\ndef translateLeft(position):\n prime = []\n for point in position:\n prime.append((point[0], point[1] - 1, point[2]))\n return prime\n\ndef translateRight(position):\n prime = []\n for point in position:\n prime.append((point[0], point[1] + 1, point[2]))\n return prime\n\ndef rotateRight(position, pivot):\n prime = []\n for point in position:\n prime.append(rotateReverse(point, pivot))\n return prime\n\ndef rotateLeft(position, pivot):\n pass # STUB: maybe implemented later?","sub_path":"ai/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29899208","text":"from typing import List, Tuple\n\nimport numpy as np\nfrom numpy.random import choice as np_choice\nfrom pandas import DataFrame\nfrom sklearn import linear_model\nimport math\n\n\nclass BinaryFeatureSelectionAntColony:\n\n def __init__(self, n_ants: int, n_iterations: int, decay: float, data_set: DataFrame, score_weight=1,\n count_weight=1):\n \"\"\"\n Args:\n data_set (DataFrame): DataFrame representing input set of features, last column are Y values\n n_ants (int): Number of ants running per iteration\n n_best (int): Number of best ants who deposit pheromone\n n_iteration (int): Number of iterations\n decay (float): Rate it which pheromone decays. The pheromone value is multiplied by decay, so 0.95 will lead to decay, 0.5 to much faster decay.\n count_weight (int or float): exponent on count of features\n score_weight (int or float): exponent on score by linear reg\n \"\"\"\n self.n_ants = n_ants\n self.n_iterations = n_iterations\n self.decay = decay\n self.score_weight = score_weight\n self.count_weight = count_weight\n self.data_set = data_set\n self.current_iteration: int = 1\n self.times_taken: np.ndarray = np.ones((2, len(self.data_set.columns) - 1))\n self.pheromone: np.ndarray = np.ones((2, len(self.data_set.columns) - 1))\n self.construction_matrix: np.ndarray = np.zeros([2, len(self.data_set.columns) - 1])\n for i in range(len(self.construction_matrix[1])):\n self.construction_matrix[1][i] = 1\n\n def run(self):\n all_time_shortest_path = (\"placeholder\", 0)\n for i in range(self.n_iterations):\n all_paths = self.gen_all_paths()\n self.spread_pheronome(all_paths)\n shortest_path = max(all_paths, key=lambda x: x[1])\n print(shortest_path)\n if shortest_path[1] > all_time_shortest_path[1] or (\n shortest_path[1] == all_time_shortest_path[1] and self.calculate_feature_amount(shortest_path[0]) <\n self.calculate_feature_amount(all_time_shortest_path[0])):\n all_time_shortest_path = shortest_path\n print(self.current_iteration)\n self.current_iteration += 1\n return all_time_shortest_path\n\n def calculate_feature_amount(self, path: List[Tuple[int, int]]) -> int:\n return len(list(filter(lambda x: x == 1, map(lambda x: x[1], path))))\n\n def spread_pheronome(self, all_paths: List[Tuple[List[Tuple[int, int]], float]]):\n for path, score in all_paths:\n count = self.calculate_feature_amount(path)\n for i, chosen in path:\n if count == 0:\n continue\n # TODO: what to do with negative scores?\n self.pheromone[chosen][i] = (1 - self.decay) * self.pheromone[chosen][i] + (\n score / count ** self.count_weight) * self.score_weight\n self.times_taken[chosen][i] += 1\n\n def gen_all_paths(self) -> List[Tuple[List[Tuple[int, int]], float]]:\n all_paths = []\n for i in range(self.n_ants):\n path = self.gen_path()\n all_paths.append((path, self.calculate_svm(path)))\n return all_paths\n\n def gen_path(self) -> List[Tuple[int, int]]:\n path = []\n for i in range(len(self.construction_matrix[0])):\n if self.pheromone[0][i] < 0 or self.pheromone[1][i] < 0:\n print(self.pheromone[0][i], self.pheromone[1][i])\n move: int = self.pick_move(self.pheromone[0][i], self.pheromone[1][i], i)\n path.append((i, move))\n return path\n\n def pick_move(self, pheromone_exclude: np.ndarray, pheromone_include: np.ndarray, i: int) -> int:\n\n excluded = pheromone_exclude * (self.times_taken[0][i] / (self.n_ants * self.current_iteration))\n included = pheromone_include * (self.times_taken[1][i] / (self.n_ants * self.current_iteration))\n\n rows = np.array([excluded, included]) / (excluded + included)\n\n move = np_choice([0, 1], 1, p=rows)[0]\n return move\n\n def calculate_svm(self, path: List[Tuple[int, int]]) -> float:\n chosen_features = []\n for i, chosen in path:\n if chosen:\n chosen_features.append(i)\n xs_train = []\n xs_test = []\n ds_length = len(self.data_set)\n mid = math.floor(ds_length / 2)\n for i in range(len(self.data_set.iloc[:, 0])):\n temp = []\n for f_id in chosen_features:\n temp.append(self.data_set.iloc[i, f_id])\n if i < mid:\n xs_train.append(temp)\n else:\n xs_test.append(temp)\n xs_train = np.asarray(xs_train)\n xs_test = np.asarray(xs_test)\n ys_train = self.data_set.iloc[:mid, len(self.data_set.iloc[0, :]) - 1].values\n ys_test = self.data_set.iloc[mid:, len(self.data_set.iloc[0, :]) - 1].values\n regr = linear_model.LinearRegression()\n try:\n regr.fit(xs_train, ys_train)\n return regr.score(xs_test, ys_test)\n except Exception as e:\n print(e)\n return 0\n","sub_path":"aco/ant_colony.py","file_name":"ant_colony.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266592866","text":"import urllib\nimport time\nurl = \"http://www.rays-counter.com/d321_f6_007/56166a49f009f/\"\ni = 0\nwhile(True):\n i += 1\n try:\n urllib.urlopen(url)\n print(\"ok\" + str(i))\n except:\n print(\"error\")\n time.sleep(5)\n","sub_path":"tes.py","file_name":"tes.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"445242982","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/3/28 8:33\n# @Author : Sugare\n# @Site : 30733705@qq.com\n# @File : app.py\n# @Software: PyCharm\n\n\n# system\nimport io\nimport os.path\nimport json\nimport hashlib\n\n# tornado\nimport tornado.ioloop\nimport tornado.web\nimport tornado.httpserver\nimport tornado.options\nimport tornado.escape\n\n# sqlalchemy\nfrom sqlalchemy import and_, or_\n\n# lib\nfrom models.tables import UserInfo, Articles, Comment, MySession, Type, ScrapyNewsData, Scrapy51Data\nfrom lib.others import sendEmail, buildTree, commentTree, randomCode\nfrom lib.session.session import SessionFactory\nfrom lib.form.form import BaseResponse, LoginForm, ValidateEmailForm, ArticleForm, RegisterForm, CommentForm\nfrom lib.checkcode.checkcode import createValidateCode\n\nfrom tornado.options import define, options\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n # url\n handlers = [\n (r'/?', IndexHandler),\n (r'/sendcode', SendCodeHandler),\n (r'/register', RegisterHandler),\n (r'/comment', CommentHandler),\n (r'/articles/?(.*)', ArticleHandler),\n (r'/publish/(.*)/(.*)', PublishHandler),\n (r'/home/?(.*)', HomeHandler),\n (r'/editor/?(.*)', EditorHandler),\n (r'/fileload', FileHandler),\n (r'/login', LoginHandler),\n (r'/logout', LogoutHandler),\n (r'/check_code', CheckCodeHandler),\n (r'/.*', ErrorHandler),\n\n ]\n settings = dict(\n static_path=os.path.join(os.path.dirname(__file__), 'static'),\n template_path=os.path.join(os.path.dirname(__file__), 'template'),\n # xsrf_cookies=True,\n login_url=\"/\",\n # debug=True,\n )\n super(Application, self).__init__(handlers, **settings)\n\n# BaseHandler\nclass BaseHandler(tornado.web.RequestHandler):\n def initialize(self):\n self.session = SessionFactory.get_session_obj(self)\n self.conn = MySession()\n\n # 用户验证装饰器\n def get_current_user(self):\n if not self.session['is_login']:\n rep = BaseResponse()\n rep.summary = 'auth failed'\n return None\n else:\n conn = MySession()\n user = self.session['login_username']\n u = conn.query(UserInfo).filter(UserInfo.username == user).first()\n return u\n\n# 主页面显示\nclass IndexHandler(BaseHandler):\n def get(self):\n type_list = self.conn.query(Type).all()\n scrapy_51_data = self.conn.query(Scrapy51Data).order_by(Scrapy51Data.nid.desc())[0:5]\n scrapy_news_data = self.conn.query(ScrapyNewsData).order_by(ScrapyNewsData.nid.desc())[0:5]\n self.render('index.html',type_list=type_list, scrapy_51_data=scrapy_51_data, scrapy_news_data=scrapy_news_data)\n\nclass ErrorHandler(BaseHandler):\n def get(self):\n self.write_error(404)\n\n# 发布文章\nclass PublishHandler(BaseHandler):\n def get(self,status='not',nid=None):\n art = self.conn.query(Articles).filter(Articles.nid == int(nid)).first()\n\n if status == 'n':\n art.status = 1\n self.conn.add(art)\n self.conn.commit()\n try:\n self.redirect('/articles/%s' % nid)\n except:\n self.write_error(403)\n else:\n art.status = 0\n self.conn.add(art)\n self.conn.commit()\n try:\n self.redirect('/home/%s' % self.get_current_user().username)\n except:\n self.write_error(403)\n\n# 用户家目录\nclass HomeHandler(BaseHandler):\n @tornado.web.authenticated\n def get(self, user=None):\n\n userinfo = self.conn.query(UserInfo).filter(UserInfo.username == user).first()\n if user == self.get_current_user().username:\n # userinfo = self.conn.query(UserInfo).filter(UserInfo.username==user).first()\n self.render('home.html', userinfo = userinfo)\n else:\n self.write_error(403)\n\n# 新建、编辑页面\nclass EditorHandler(BaseHandler):\n @tornado.web.authenticated\n def get(self, nid=None):\n\n user_obj = self.get_current_user()\n if user_obj.status == 1:\n type_list = self.conn.query(Type).all()\n cata_img = os.path.join(os.path.dirname(__file__), 'static', 'cataimg')\n img_list = os.listdir(cata_img) # 列出文件夹下所有的目录与文件\n\n art_list = []\n for i in user_obj.art:\n art_list.append(i.nid)\n\n if nid:\n if int(nid) in art_list:\n article = self.conn.query(Articles).filter(Articles.nid == int(nid)).first()\n else:\n self.write_error(403)\n else:\n article = ''\n self.render('editor.html', art=article, img_list=img_list, type_list=type_list)\n else:\n self.write_error(403)\n @tornado.web.authenticated\n def post(self, nid=None):\n form = ArticleForm()\n\n if form.valid(self):\n if nid:\n update_art = self.conn.query(Articles).filter(Articles.nid == int(nid)).first()\n update_art.title = form._value_dict['title']\n update_art.content = form._value_dict['content']\n update_art.type_id = int(form._value_dict['type_id'])\n update_art.cataimg = form._value_dict['cataimg']\n self.conn.add(update_art)\n\n else:\n art = Articles(title=form._value_dict['title'],\n content=form._value_dict['content'],\n type_id=int(form._value_dict['type_id']),\n user_info_id=self.get_current_user().nid,\n cataimg = form._value_dict['cataimg'])\n\n self.conn.add(art)\n self.conn.commit()\n\n self.redirect('/home/%s' % (self.get_current_user().username))\n\n# 文件上传,图片\nclass FileHandler(BaseHandler):\n def post(self, *args, **kwargs):\n file_metas = self.request.files['myFileName']\n\n for meta in file_metas:\n file_name = meta['filename']\n with open(os.path.join('static', 'img', file_name), 'wb') as up:\n up.write(meta['body'])\n\n self.set_header('ContentType', 'text/html')\n self.set_header('Charset', 'utf-8')\n imgUrl = '/static/img/%s' % file_name\n self.write(imgUrl)\n\n# 邮箱发送验证码\nclass SendCodeHandler(BaseHandler):\n def post(self):\n rep = BaseResponse()\n form = ValidateEmailForm()\n\n if form.valid(self):\n validateEmail = self.conn.query(UserInfo).filter(or_(UserInfo.email == form._value_dict['register_email'],\n UserInfo.username == form._value_dict['register_username'])).first()\n if not validateEmail:\n rep.status = True\n register_email = form._value_dict['register_email']\n code = randomCode()\n rep.data = code\n self.session['RegisterCode'] = code\n sendEmail([register_email,], code)\n else:\n rep.message['register_error'] = '该邮箱或用户名已经被注册过!'\n else:\n rep.message = form._error_dict\n\n self.write(json.dumps(rep.__dict__))\n\n# 用户注册\nclass RegisterHandler(BaseHandler):\n def post(self):\n rep = BaseResponse()\n form = RegisterForm()\n\n if form.valid(self):\n try:\n if form._value_dict['register_code'].upper() == self.session['RegisterCode'].upper():\n rep.status = True\n self.session['is_login'] = True\n\n self.session['login_username'] = form._value_dict['register_username']\n\n password_r = form._value_dict['register_password'].encode()\n userinfo = UserInfo(username=form._value_dict['register_username'],\n password=hashlib.md5(password_r).hexdigest(),\n email=form._value_dict['register_email'])\n\n self.conn.add(userinfo)\n self.conn.commit()\n else:\n rep.message['register_code'] ='验证码错误,啵啵!'\n except:\n rep.message['timeout'] = '验证超时,请重新验证!'\n\n else:\n rep.message = form._error_dict\n\n self.write(json.dumps(rep.__dict__))\n\n# 用户登录\nclass LoginHandler(BaseHandler):\n def post(self):\n rep = BaseResponse()\n form = LoginForm()\n\n if form.valid(self):\n password_r = form._value_dict['login_password'].encode()\n\n r = self.conn.query(UserInfo).filter(and_(or_(UserInfo.email == form._value_dict['login_username'], UserInfo.username == form._value_dict['login_username']),\n UserInfo.password == hashlib.md5(password_r).hexdigest())).first()\n if form._value_dict['login_code'].upper() == self.session['CheckCode'].upper():\n\n if r and r.status != 2:\n rep.status = True\n self.session['is_login'] = True\n self.session['login_username'] = r.username\n else:\n if not self.conn.query(UserInfo).filter(UserInfo.username == form._value_dict['login_username']).first():\n rep.message['login_username'] = '您输入的用户名有误!'\n elif not self.conn.query(UserInfo).filter(UserInfo.password == hashlib.md5(password_r).hexdigest()).first():\n rep.message['login_password'] = '您输入的密码有误!'\n elif r.status == 2:\n rep.message['warning'] = '您的账号已被封,如要解封,请联系管理员!'\n else:\n rep.message['login_username'] = '您输入的用户名有误!'\n rep.message['login_password'] = '您输入的密码有误!'\n\n else:\n rep.message['login_code'] = '验证码错误,啵啵!'\n else:\n rep.message = form._error_dict\n self.write(json.dumps(rep.__dict__))\n\n# 用户退出\nclass LogoutHandler(BaseHandler):\n def get(self, *args, **kwargs):\n del self.session['is_login']\n del self.session['login_username']\n self.redirect('/')\n\n# 文章显示\nclass ArticleHandler(BaseHandler):\n def get(self, aid=None):\n if aid:\n art_id = int(aid)\n last_pag = self.conn.query(Articles).order_by(Articles.nid.desc()).limit(1).first()\n article = self.conn.query(Articles).filter(Articles.nid == art_id).first()\n comment = self.conn.query(Comment).filter(Comment.article_id == art_id).all()\n comment_list = []\n for i in comment:\n if self.get_current_user():\n user_info_id = self.get_current_user().nid\n else:\n user_info_id = 0\n a = (i.user.username, i.content, i.reply_id, str(user_info_id), i.ctime, i.nid, i.article_id)\n comment_list.append(a)\n c = buildTree(comment_list)\n self.render('article.html', article=article, te = commentTree(c), last_pag=last_pag)\n else:\n self.write_error(403)\n\n# 用户评论\nclass CommentHandler(BaseHandler):\n @tornado.web.authenticated\n def post(self, *args, **kwargs):\n rep = BaseResponse()\n form = CommentForm()\n\n if form.valid(self):\n rep.status = True\n if int(form._value_dict['reply_id']) == 0:\n form._value_dict['reply_id'] = None\n else:\n form._value_dict['reply_id'] = int(form._value_dict['reply_id'])\n\n comm = Comment(user_info_id=int(form._value_dict['user_info_id']),\n reply_id=form._value_dict['reply_id'],\n content=form._value_dict['content'],\n article_id=int(form._value_dict['article_id']))\n self.conn.add(comm)\n self.conn.commit()\n\n else:\n rep.message = form._error_dict\n\n self.write(json.dumps(rep.__dict__))\n\n# 图片验证码\nclass CheckCodeHandler(BaseHandler):\n def get(self):\n mstream = io.BytesIO()\n img, code = createValidateCode()\n img.save(mstream, \"gif\")\n print(code)\n self.session['CheckCode'] = code\n self.write(mstream.getvalue())\n\ndef main():\n tornado.options.parse_command_line()\n http_server = tornado.httpserver.HTTPServer(Application())\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.current().start()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"377179696","text":"from django.urls import path\nfrom App_Blog import views\n\n\napp_name='App_Blog'\n\nurlpatterns = [\n path('', views.BlogList.as_view() , name='blogList'),\n path('new-blog/', views.CreateBlog.as_view(), name='createBlog'),\n path('blog-details/<slug:slug>', views.blog_details, name='blogDetails'),\n path('like/<pk>/', views.liked, name='like'),\n path('unlike/<pk>/', views.unliked, name='unlike'),\n path('my-blog/', views.MyBlog.as_view(), name='myblog'),\n path('my-blog-edit/<slug:slug>/', views.UpdateBlog.as_view(), name='editBlog'),\n]\n","sub_path":"App_Blog/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":"498036920","text":"\"\"\"\nThis script runs through the Dental Elite scraper.\nDefault url: \"https://www.dentalelite.co.uk/jobs/\"\n\nrun is as:\nnohup python3 scrape_dental_elite_job_data.py filepath_job_url > ../data/$(date \"+%Y-%m-%d-%H-%M-%S-\")nohup-dental-elite.out\n\n\"\"\"\n\nfrom selenium import webdriver\nimport pandas as pd\nimport time\nimport datetime\nimport random\nimport os\nimport sys\nfrom utils import config_webdriver as cw\nfrom utils import standard_formatter as sf\n# from utils import change_ip as cp\n \n\n\n# Get all job details\ndef get_all_jobs(job_urls, driver):\n cols = ['Job URL', 'Ref', 'Title', 'Position Type', 'Location', 'posted', 'Salary', 'Description']\n jobs_dataframe = pd.DataFrame(columns=cols)\n\n for i in range(len(job_urls)):\n try:\n job_url = job_urls[i]\n job_details_dictionary = dict()\n\n job_details_dictionary['Job URL'] = [job_url]\n\n driver.switch_to.window(driver.window_handles[-1])\n driver.get(job_url)\n\n selector = driver.find_element_by_css_selector('div[class=\"job-details\"]')\n job_details_dictionary['Ref'] = [\n selector.find_element_by_css_selector('div[class=\"ref\"]').text.split(' ', 1)[1]]\n\n job_details_dictionary['Title'] = [selector.find_element_by_css_selector('div[class=\"title\"]').text]\n\n info_row = selector.find_element_by_css_selector('div[class=\"info-row\"]').find_elements_by_tag_name('div')\n\n for i in info_row:\n info = i.text.split(':')\n job_details_dictionary[info[0].strip()] = [info[1].strip()]\n\n job_details_dictionary['Description'] = [selector.find_element_by_css_selector('div[class=\"details\"]').text]\n\n job_details_dictionary['Salary'] = [\n selector.find_element_by_css_selector('div[class=\"value\"]').text.strip()]\n\n df = pd.DataFrame(job_details_dictionary)\n\n jobs_dataframe = jobs_dataframe.append(df)\n time.sleep(random.randint(1, 4))\n\n except Exception as e:\n print(str(e))\n time.sleep(random.randint(1, 4))\n\n return jobs_dataframe\n\n\ndef main():\n program_start_time = time.time()\n driver = cw.configure_webdriver()\n sys_argv = sys.argv\n\n try:\n parent_url = 'https://www.dentalelite.co.uk/jobs/'\n driver.get(parent_url)\n\n # Get all job urls\n filepath_job_url = sys_argv[1]\n print(filepath_job_url)\n job_urls = pd.read_csv(filepath_job_url).iloc[:,0]\n\n print('Total jobs:', len(job_urls))\n print('Total unique jobs:', len(set(job_urls)))\n job_urls = list(set(job_urls))\n\n if len(job_urls) != 0:\n # Get jobs dataframe\n data = get_all_jobs(job_urls, driver)\n file_name = '../data/{}-dental-elite-jobs.csv'\n file_name = sf.format_filename(file_name)\n data.to_csv(file_name, index=False)\n\n else:\n print('No jobs found')\n\n except Exception as e:\n print(str(e))\n\n finally:\n driver.close() \n \n seconds = round(time.time() - program_start_time)\n minutes = round(seconds/60, 1)\n hours = round(minutes/60, 1)\n print('DONE! ')\n print(\"\\n\\nRun time = {} seconds; {} minutes; {} hours\".format(seconds, minutes, hours)) \n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/scrapers/scrape_dental_elite_job_data.py","file_name":"scrape_dental_elite_job_data.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"194336825","text":"__author__ = 'Patrick Gorman'\nfrom flask_sqlalchemy import *\n\nfrom database import db_session\nfrom models import Video\n\n\ndef save_videos(video_data):\n Session._model_changes = {}\n for x in video_data:\n new_video = Video(x, video_data[x])\n db_session.add(new_video)\n db_session.commit()\n\n\ndef load_videos():\n return Video.query.all()\n\n\n\n\n","sub_path":"SQL.py","file_name":"SQL.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"236138910","text":"'''\r\nCreated on Feb 11, 2019\r\n\r\n@author: StevensUser\r\n'''\r\n\r\nfrom cs115 import map, reduce\r\n\r\ndef powerset(lst):\r\n ''' returns the power set of the list, that is, the set of all subsets \r\n of the list'''\r\n if lst == []:\r\n return [[]]\r\n lose_it = powerset(lst[1:])\r\n # lose it means to take first element out of list and recurse on the rest. it is solution for removing\r\n # the first element\r\n use_it = map(lambda subset: [lst[0]] + subset, lose_it)\r\n return lose_it + use_it\r\n\r\nprint(powerset([1,2,3]))\r\n\r\ndef subset(target, lst):\r\n ''' determines whether or not it is possible to create the target sum using the \r\n values in the list. Values in the list can be positive, negative, or 0. '''\r\n if target == 0:\r\n return True\r\n if lst == []:\r\n return False\r\n lose_it = subset(target, lst[1:])\r\n use_it = subset(target - lst[0], lst[1:])\r\n return use_it or lose_it\r\n\r\nprint(subset(11, [5,4,2]))\r\n\r\n\r\ndef LCS(s1, s2):\r\n ''' takes two strings - s1 and s2 - and returns the length of the longest\r\n common subsequence'''\r\n if s1 == '' or s2 == '':\r\n return 0\r\n if s1[0] == s2[0]:\r\n return 1 + LCS(s1[1:], s2[1:])\r\n return max(LCS(s1, s2[1:]), LCS(s1[1:], s2))\r\n\r\ndef subset_with_values(target, lst):\r\n ''' determines whether or not is is possible to create the target sum using the values in the list. \r\n values in the list can be positive, negative, or zero. the function returns a tuple of exactly\r\n two items. The first is a boolean that indicates True if the sum is possible and false if the sum is not. \r\n the second element in the tuple is a list of all the value that add up to make the target sum. '''\r\n if target == 0:\r\n return (True, [])\r\n if lst == []:\r\n return (False, [])\r\n use_it = subset_with_values(target - lst[0], lst[1:])\r\n if use_it[0]: #already a boolean so this implies that its true\r\n return(True, [lst[0]] + use_it[1])\r\n return subset_with_values(target, lst[1:])\r\n\r\nprint(subset_with_values(7, [5,1,2]))\r\n\r\ndef LCS_with_values(s1, s2):\r\n ''' returns a tuple containing the length of the LCS as well as the string itself'''\r\n if s1 == '' or s2 == '':\r\n return (0, '')\r\n if s1[0] == s2[0]:\r\n result = LCS_with_values(s1[1:], s2[1:])\r\n return (1 + result[0], s1[0] + result[1])\r\n use_s1 = LCS_with_values(s1, s2[1:])\r\n use_s2 = LCS_with_values(s1[1:], s2)\r\n if use_s1[0] > use_s2[0]:\r\n return use_s1\r\n return use_s2 \r\n\r\nprint(LCS_with_values('sam', 'spam'))\r\n ","sub_path":"useit_or_loseit.py","file_name":"useit_or_loseit.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"521431162","text":"import random\nimport time\n\nclass Bear:\n def __init__(self):\n self.posX = random.randint(0, base_x)\n self.posY = random.randint(0, base_y)\n\n while True:\n if river[self.posY][self.posX] != \"B\" and river[self.posY-1][self.posX] != \"B\" and river[self.posY+1][self.posX] != \"B\" and river[self.posY][self.posX-1] != \"B\" and river[self.posY][self.posX+1] != \"B\" and river[self.posY][self.posX] != \"F\" and river[self.posY-1][self.posX] != \"F\" and river[self.posY+1][self.posX] != \"F\" and river[self.posY][self.posX-1] != \"F\" and river[self.posY][self.posX+1] != \"F\":\n river[self.posY][self.posX] = \"B\"\n break\n self.posX = random.randint(0, base_x)\n self.posY = random.randint(0, base_y)\n\n\n def update(self, rand):\n river[self.posY][self.posX] = basic_sign\n\n if rand == 1: #Go left\n if self.posX == 0:\n self.posX += 1\n else:\n self.posX -= 1\n elif rand == 2: #Go right\n if self.posX == base_x+1:\n self.posX -= 1\n else:\n self.posX += 1\n elif rand == 3: #Go top\n if self.posY == 0:\n self.posY += 1\n else:\n self.posY -= 1\n elif rand == 4: #Go bot\n if self.posY == base_y+1:\n self.posY -= 1\n else:\n self.posY += 1\n\n if river[self.posY][self.posX] == \"B\":\n bears.append(Bear())\n print(\"NEW BEAR!!! on location\", self.posX, self.posY)\n return\n\n river[self.posY][self.posX] = \"B\"\n\nclass Fish:\n def __init__(self):\n self.posX = random.randint(0, base_x)\n self.posY = random.randint(0, base_y)\n\n while True:\n if river[self.posY][self.posX] != \"B\" and river[self.posY-1][self.posX] != \"B\" and river[self.posY+1][self.posX] != \"B\" and river[self.posY][self.posX-1] != \"B\" and river[self.posY][self.posX+1] != \"B\" and river[self.posY][self.posX] != \"F\" and river[self.posY-1][self.posX] != \"F\" and river[self.posY+1][self.posX] != \"F\" and river[self.posY][self.posX-1] != \"F\" and river[self.posY][self.posX+1] != \"F\":\n river[self.posY][self.posX] = \"F\"\n break\n self.posX = random.randint(0, base_x)\n self.posY = random.randint(0, base_y)\n\n\n def __del__(self):\n self.posX = None\n self.posY = None\n \n\n def update(self, rand):\n river[self.posY][self.posX] = basic_sign\n\n old_x = self.posX\n old_y = self.posY\n\n if rand == 1: #Go left\n if self.posX == 0:\n #river[self.posY][self.posX] = \">\"\n self.posX +=1\n else:\n #river[self.posY][self.posX] = \"<\"\n self.posX -= 1\n elif rand == 2: #Go right\n if self.posX == base_x+1:\n self.posX -=1\n else:\n self.posX += 1\n elif rand == 3: #Go top\n if self.posY == 0:\n self.posY +=1\n else:\n self.posY -= 1\n elif rand == 4: #Go bot\n if self.posY == base_y+1:\n self.posY -=1\n else:\n self.posY += 1\n\n if river[self.posY][self.posX] == \"F\":\n fishes.append(Fish())\n print(\"Fishes had sex on location\", self.posX, self.posY)\n return\n elif river[self.posY][self.posX] == \"B\":\n river[old_y][old_x] = basic_sign\n print(\"FISH EATEN!!! on location\", old_x+1, old_y)\n fishes.remove(self)\n del self\n return\n\n river[self.posY][self.posX] = \"F\"\n\n\n\ndef print_river():\n for i in range(0, base_x+3):\n print(str(i) + \" \", end=\"\")\n for number, line in enumerate(river):\n print()\n print(str(number), \"\", end=\"\")\n for x in line:\n print(str(x) + \" \", end=\"\")\n\n print()\n\n\ndef clear_screen():\n print(\"\\n\" * 10)\n\n\ndef new_fish(arr):\n for i in range(fish_spawn_count):\n arr.append(Fish())\n return arr\n\n\ndef new_bear(arr):\n for i in range(bear_spawn_count):\n arr.append(Bear())\n return arr\n\n\ndef update_board():\n for bear in bears:\n rand = random.randint(1, 4)\n bear.update(rand)\n\n for fish in fishes:\n rand = random.randint(1, 4)\n fish.update(rand)\n print_river()\n time.sleep(.5)\n\n\nbasic_sign = \"-\"\nbase_x = 8\nbase_y = 5\nfish_spawn_count = 1\nbear_spawn_count = 10\n\nriver = [[basic_sign]*10, [basic_sign]*10, [basic_sign]*10, [basic_sign]*10, [basic_sign]*10, [basic_sign]*10, [basic_sign]*10]\n\nbears = []\nbears = new_bear(bears)\n\nfishes = []\nfishes = new_fish(fishes)\n\nprint_river()\n\nupdate_board()\nupdate_board()\nupdate_board()\nupdate_board()\nupdate_board()\nupdate_board()\nupdate_board()\n\nwhile not fishes == []:\n update_board()\n\nprint(\"BEARS HAVE CONQUERED THE BOARD!!!\") \n\n","sub_path":"data_struct_book/ecosystem.py","file_name":"ecosystem.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"408338376","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import AgglomerativeClustering\nfrom scipy.cluster.hierarchy import dendrogram, linkage\nfrom sklearn.cluster import KMeans\nfrom scipy.spatial.distance import cdist\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom os import path\nfrom scipy.cluster.vq import vq\nimport os\n\nnp.random.seed(3217)\n\ndata = pd.read_csv(\"employement.txt\", header=0, sep=\"\\t\", index_col=\"Country\") # read in the data\nprint(\"Data is of the shape \" + str(np.shape(data))) # The shape of data\nhere = path.abspath(path.dirname(__file__))\n\nDATA_PATH = os.path.join(here, \"HMP_Dataset\")\n\n###############################################################################################\n# Problem 1 part 1\n###############################################################################################\n\nmodel = linkage(data, 'single') # Create a linkage matrix with single link\ndendrogram(model, labels=data.index) # plot the dendogram with countries as labels\nplt.title('European employment Dendogram with Single link') # Set the title of plot\nplt.xticks(rotation='vertical') # Select the orientation of plot\nplt.gcf().subplots_adjust(bottom=0.30) # set some boundary space\nplt.xlabel(\"Countries\") # label x axis\nplt.ylabel(\"Distance\") # label y axis\nplt.savefig('single_link.png') # save the plot\nplt.close() # close the plot\n\nmodel = linkage(data, 'complete') # Create a linkage matrix with complete link\ndendrogram(model, labels=data.index) # plot the dendogram with countries as labels\nplt.title('European employment Dendogram with Complete link') # Set the title of plot\nplt.xticks(rotation='vertical') # Select the orientation of plot\nplt.gcf().subplots_adjust(bottom=0.30) # set some boundary space\nplt.xlabel(\"Countries\") # label x axis\nplt.ylabel(\"Distance\") # label y axis\nplt.savefig('complete_link.png') # save the plot\nplt.close() # close the plot\n\nmodel = linkage(data, 'average') # Create a linkage matrix with average link\ndendrogram(model, labels=data.index) # plot the dendogram with countries as labels\nplt.title('European employment Dendogram with Group average') # Set the title of plot\nplt.xticks(rotation='vertical') # Select the orientation of plot\nplt.gcf().subplots_adjust(bottom=0.30) # set some boundary space\nplt.xlabel(\"Countries\") # label x axis\nplt.ylabel(\"Distance\") # label y axis\nplt.savefig('group_average.png') # save the plot\nplt.close() # close the plot\n\n###############################################################################################\n# Problem 1 part 2\n###############################################################################################\n\n\ndistorsions = []\nK = range(2, 14)\nfor k in K:\n k_means = KMeans(n_clusters=k, random_state=6).fit(data) # fit the data on different values of k\n distorsions.append(k_means.inertia_) # store the inertia in a list for each k\n\nplt.plot(K, distorsions, marker=\"o\") # plot the inertia against k\nplt.xlabel('k') # label x axis\nplt.ylabel('Distortion') # label y axis\nplt.title('Elbow plot showing the value of k') # set the plot title\nplt.grid(True) # set grid on\nplt.savefig('elbow_plot.png') # save the plot\nplt.close() # close the plot\n#\n\nprint(\"Problem 1 completed\")\n\n###############################################################################################\n# Problem 2\n###############################################################################################\nn_cluster = 480 # set the no of cluster\ntime_unit = 32 # set the segment length\nprint(\"Problem 2 started with no of cluster = \" + str(480) + \" and segment length = \" + str(32))\nindex_list = [os.path.join(DATA_PATH, 'Brush_teeth'), os.path.join(DATA_PATH, 'Climb_stairs'),\n os.path.join(DATA_PATH, 'Comb_hair')\n , os.path.join(DATA_PATH, 'Descend_stairs'), os.path.join(DATA_PATH, 'Drink_glass'),\n os.path.join(DATA_PATH, 'Eat_meat'),\n os.path.join(DATA_PATH, 'Eat_soup'), os.path.join(DATA_PATH, 'Getup_bed'),\n os.path.join(DATA_PATH, 'Liedown_bed'), os.path.join(DATA_PATH, 'Pour_water'),\n os.path.join(DATA_PATH, 'Sitdown_chair'), os.path.join(DATA_PATH, 'Standup_chair'),\n os.path.join(DATA_PATH, 'Use_telephone'),\n os.path.join(DATA_PATH, 'Walk')] # create an index of adl activity\n\n\ndef generate_segments(data, n_cluster, time_unit):\n no_of_rows = np.shape(data)[0] # get no of rows from the passed data\n mod = no_of_rows % time_unit # get the extra segments from the data\n if mod != 0:\n data_to_segment = np.array(data)[:-mod, :] # remove the extra segments\n else:\n data_to_segment = np.array(data)\n vector_segment = data_to_segment.reshape(int(no_of_rows / time_unit),\n time_unit * 3) # reshape to have a segment represented by a single vector\n return pd.DataFrame(vector_segment)\n\n\ndef read_attribute_from_all_file(dir, n_cluster, time_unit):\n files = os.listdir(dir) # get all the files in the given dir\n train_per = int(0.8 * len(files)) # get 80% of the files\n test_per = int(0.2 * len(files)) # get 20% of the files for the testing data\n full_data_train = pd.DataFrame() # initialize a empty train data frame\n full_data_test = pd.DataFrame() # initialize a empty test data frame\n for file in files[:train_per]: # Go through all the files in the train set\n file_path = os.path.join(dir, file) # generate the file actual path\n data = pd.read_csv(file_path, sep=\" \", index_col=None, names=['x', 'y', 'z'],\n skip_blank_lines=True).dropna() # import the data from that file\n segmented_data_train = generate_segments(data, n_cluster,\n time_unit) # Generate segment of vectors of specified length\n full_data_train = full_data_train.append(segmented_data_train,\n ignore_index=True) # create a data frame of all such segments form all the files\n\n for file in files[-test_per:]: # get all the test files in the given dir\n file_path = os.path.join(dir, file) # generate the file actual path\n data = pd.read_csv(file_path, sep=\" \", index_col=None, names=['x', 'y', 'z'], skip_blank_lines=True).dropna()\n segmented_data_test = generate_segments(data, n_cluster,\n time_unit) # Generate segment of vectors of specified length\n full_data_test = full_data_test.append(segmented_data_test,\n ignore_index=True) # create a data frame of all such segments f\n return full_data_train, full_data_test\n\n\ndef create_feature_for_classifier(model, dir, n_cluster, time_unit):\n files = os.listdir(dir) # list all the files in dir\n train_per = int(0.8 * len(files)) # get 80% of the files\n test_per = int(0.2 * len(files)) # get 20% of the files for the testing data\n feature_train = pd.DataFrame() # initialize a empty train data frame\n feature_test = pd.DataFrame() # initialize a empty test data frame\n for file in files[:train_per]: # Go through all the files in the train set\n file_path = os.path.join(dir, file) # generate the file actual path\n data = pd.read_csv(file_path, sep=\" \", index_col=None, names=['x', 'y', 'z'], skip_blank_lines=True).dropna()\n segmented_data_train = generate_segments(data, n_cluster,\n time_unit) # Generate segment of vectors of specified length\n\n assignment = vq(segmented_data_train,\n model.cluster_centers_) # Generate the assignment vector which shall assign each segment to a given cluster\n assignment_array = np.array(assignment[0]) # take the assignment array\n feature = [0 for s in\n range(0, n_cluster + 1)] # initialize a feature vector of a set length for random forest classifier\n for i in assignment_array: # iterate through assignment\n feature[i] += 1 # fill up the bucket such that you have a histogram of points\n feature[n_cluster] = index_list.index(dir) + 1 # set the label for the classifier\n feature_df = pd.DataFrame(np.array(feature).reshape(1, n_cluster + 1)) # get everything in one row\n feature_df.columns = range(1, n_cluster + 2) # set the column labels\n feature_train = feature_train.append(feature_df) # create a full set of all these training\n\n for file in files[-test_per:]: # get all the test files in the given dir\n file_path = os.path.join(dir, file) # generate the file actual path\n data = pd.read_csv(file_path, sep=\" \", index_col=None, names=['x', 'y', 'z'], skip_blank_lines=True).dropna()\n segmented_data_test = generate_segments(data, n_cluster,\n time_unit) # Generate segment of vectors of specified length\n assignment = vq(segmented_data_test,\n model.cluster_centers_) # Generate the assignment vector which shall assign each segment to a given cluster\n assignment_array = np.array(assignment[0]) # take the assignment array\n feature = [0 for s in\n range(0, n_cluster + 1)] # initialize a feature vector of a set length for random forest classifier\n for i in assignment_array: # iterate through assignment\n feature[i] += 1 # fill up the bucket such that you have a histogram of points\n feature[n_cluster] = index_list.index(dir) + 1 # set the label for the classifier\n feature_df = pd.DataFrame(np.array(feature).reshape(1, n_cluster + 1)) # get everything in one row\n feature_df.columns = range(1, n_cluster + 2) # set the column labels\n feature_test = feature_test.append(feature_df) # create a full set of all these training\n return feature_train, feature_test\n\n\ndef generate_vectors(n_cluster, time_unit):\n # Generate the vector segments for each adl and split them into train and test\n brush_vector_train, brush_vector_test = read_attribute_from_all_file(os.path.join(DATA_PATH, \"Brush_teeth\"),\n n_cluster, time_unit)\n climb_stairs_vector_train, climb_stairs_vector_test = read_attribute_from_all_file(\n os.path.join(DATA_PATH, \"Climb_stairs\"), n_cluster, time_unit)\n comb_hair_vector_train, comb_hair_vector_test = read_attribute_from_all_file(os.path.join(DATA_PATH, \"Comb_hair\"),\n n_cluster, time_unit)\n descend_stairs_vector_train, descend_stairs_vector_test = read_attribute_from_all_file(\n os.path.join(DATA_PATH, \"Descend_stairs\"), n_cluster, time_unit)\n drink_glass_vector_train, drink_glass_vector_test = read_attribute_from_all_file(\n os.path.join(DATA_PATH, \"Drink_glass\"), n_cluster, time_unit)\n eat_meat_vector_train, eat_meat_vector_test = read_attribute_from_all_file(os.path.join(DATA_PATH, \"Eat_meat\"),\n n_cluster, time_unit)\n eat_soup_vector_train, eat_soup_vector_test = read_attribute_from_all_file(os.path.join(DATA_PATH, \"Eat_soup\"),\n n_cluster, time_unit)\n get_up_bed_vector_train, get_up_bed_vector_test = read_attribute_from_all_file(os.path.join(DATA_PATH, \"Getup_bed\"),\n n_cluster, time_unit)\n liedown_bed_vector_train, liedown_bed_vector_test = read_attribute_from_all_file(\n os.path.join(DATA_PATH, \"Liedown_bed\"), n_cluster, time_unit)\n pour_water_vector_train, pour_water_vector_test = read_attribute_from_all_file(\n os.path.join(DATA_PATH, \"Pour_water\"), n_cluster, time_unit)\n sitdown_chair_vector_train, sitdown_chair_vector_test = read_attribute_from_all_file(\n os.path.join(DATA_PATH, \"Sitdown_chair\"), n_cluster, time_unit)\n stand_up_chair_vector_train, stand_up_chair_vector_test = read_attribute_from_all_file(\n os.path.join(DATA_PATH, \"Standup_chair\"), n_cluster, time_unit)\n use_telephone_vector_train, use_telephone_vector_test = read_attribute_from_all_file(\n os.path.join(DATA_PATH, \"Use_telephone\"), n_cluster, time_unit)\n walk_vector_train, walk_vector_test = read_attribute_from_all_file(os.path.join(DATA_PATH, \"Walk\"), n_cluster,\n time_unit)\n print(\"Vector segmentation complete\")\n\n # # merge all the vector segments for each adl activity into one\n feature_vector = np.concatenate(\n [brush_vector_train, climb_stairs_vector_train, comb_hair_vector_train, descend_stairs_vector_train\n , drink_glass_vector_train, eat_meat_vector_train, eat_soup_vector_train, get_up_bed_vector_test,\n liedown_bed_vector_train,\n pour_water_vector_train, sitdown_chair_vector_train, stand_up_chair_vector_train,\n use_telephone_vector_train, walk_vector_train])\n return feature_vector\n\n\ndef generate_classifier_feature(feature_vector, n_cluster, time_unit):\n k_means = KMeans(n_clusters=n_cluster, random_state=0).fit(feature_vector) # initialize a k-mean model\n print(\"K-means clustering complete\")\n # Generate training and test features for all the adl activity\n train_classifier = pd.DataFrame()\n test_classifier = pd.DataFrame()\n for dir in index_list:\n train, test = create_feature_for_classifier(k_means, dir, n_cluster, time_unit) # create test and train for the classifier\n train_classifier = train_classifier.append(train)\n test_classifier = test_classifier.append(test)\n print(\"Finished creating features for classifier\")\n return train_classifier, test_classifier\n\n\nn_clust = 480\nsegment_l = 32\nfeature_vector = generate_vectors(n_clust, segment_l)\ntrain_classifier, test_classifier = generate_classifier_feature(feature_vector, n_clust, segment_l)\n# set up a random forest classifier\nrandom_forest_model = RandomForestClassifier(max_depth=32, random_state=8, n_estimators=90)\n# fit the model on training set\nrandom_forest_model.fit(train_classifier.iloc[:, :n_clust], train_classifier.iloc[:, n_clust])\n# test the model on test set\nprediction = random_forest_model.predict(test_classifier.iloc[:, :n_clust])\n# Calculate the accuracy\nacc = accuracy_score(test_classifier.iloc[:, n_clust], prediction)\nprint(\"Accuracy achieved is \" + str(acc * 100) + \"%\")\nprint(\"Error rate for the classifier is \"+ str((1-acc)*100)+\"%\")\nprint(confusion_matrix(test_classifier.iloc[:, n_clust], prediction))\n\n####################################################################################################################\n# Problem 2 part 2\n####################################################################################################################\n\nn_cluster_list = [40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 500]\ntime_unit_list = [4,8, 12,16, 20, 24, 28, 32, 36, 40]\naccuracy_cluster_list = []\naccuracy_segment_list = []\ndist_list=[]\n\n# get the optimum no of clusters\nfor k in n_cluster_list:\n k_means = KMeans(n_clusters=k, random_state=6).fit(feature_vector) # fit the data on different values of k\n dist_list.append(k_means.inertia_) # store the inertia in a list for each k\n\nplt.plot(n_cluster_list, dist_list, marker=\"o\") # plot the inertia against k\nplt.xlabel('k') # label x axis\nplt.ylabel('Distortion') # label y axis\nplt.title('Elbow plot showing the value of k') # set the plot title\nplt.grid(True) # set grid on\nplt.savefig('elbow_plot_part2.png') # save the plot\nplt.close() # close the plot\n\n\n# calculate the accuracy for different value of clusters\nfor n_cluster in n_cluster_list:\n print(\"Calculating accuracy for cluster = \" + str(n_cluster))\n feature_vector = generate_vectors(n_cluster, segment_l)\n train_classifier, test_classifier = generate_classifier_feature(feature_vector, n_cluster, segment_l)\n random_forest_model = RandomForestClassifier(max_depth=32, random_state=8, n_estimators=90)\n random_forest_model.fit(train_classifier.iloc[:, :n_cluster], train_classifier.iloc[:, n_cluster])\n prediction = random_forest_model.predict(test_classifier.iloc[:, :n_cluster])\n acc = accuracy_score(test_classifier.iloc[:, n_cluster], prediction)\n accuracy_cluster_list.append(acc)\n# calculate the accuracy for different value of segment length\nfor seg_length in time_unit_list:\n print(\"Calculating accuracy for segment length = \" + str(seg_length))\n feature_vector = generate_vectors(n_clust, seg_length)\n train_classifier, test_classifier = generate_classifier_feature(feature_vector, n_clust, seg_length)\n random_forest_model = RandomForestClassifier(max_depth=32, random_state=8, n_estimators=90)\n random_forest_model.fit(train_classifier.iloc[:, :n_clust], train_classifier.iloc[:, n_clust])\n prediction = random_forest_model.predict(test_classifier.iloc[:, :n_clust])\n acc = accuracy_score(test_classifier.iloc[:, n_clust], prediction)\n accuracy_segment_list.append(acc)\n\n# plot the accuracy as function of no of clusters\nplt.plot(n_cluster_list, accuracy_cluster_list)\nplt.xlabel(\"No of clusters\")\nplt.ylabel(\"Accuracy of Random Forest Classifier\")\nplt.title(\"Effect of changing no of clusters on the accuracy of classifier \")\nplt.grid(True)\nplt.savefig('cluster_accuracy.png')\nplt.close()\n\n# plot the accuracy as function of segment length\nplt.plot(time_unit_list, accuracy_segment_list)\nplt.xlabel(\"Vector segment length\")\nplt.ylabel(\"Accuracy of Random Forest Classifier\")\nplt.title(\"Effect of changing segment length on the accuracy of classifier \")\nplt.grid(True)\nplt.savefig('segment_length_accuracy.png')\nplt.close()\n\n\n\n# generate a plot that will have affect of both segment and no of cluster\nn_cluster_list = [25, 50, 200, 400]\ntime_unit_list = [4, 8, 32]\n\nresult_list = []\nfor seg_length in time_unit_list:\n interim = []\n for n_cluster in n_cluster_list:\n feature_vector = generate_vectors(n_cluster, seg_length)\n train_classifier, test_classifier = generate_classifier_feature(feature_vector, n_cluster, seg_length)\n random_forest_model = RandomForestClassifier(max_depth=32, random_state=8, n_estimators=90)\n random_forest_model.fit(train_classifier.iloc[:, :n_cluster], train_classifier.iloc[:, n_cluster])\n prediction = random_forest_model.predict(test_classifier.iloc[:, :n_cluster])\n acc = accuracy_score(test_classifier.iloc[:, n_cluster], prediction)\n interim.append(acc*100)\n result_list.append(interim)\n\n\nfor i, y in enumerate(result_list):\n plt.plot(n_cluster_list, y, label=time_unit_list[i])\nplt.xlabel(\"No of clusters\")\nplt.ylabel(\"Accuracy\")\nplt.title(\"Variation in Accuracy with segment size and no of cluster\")\nplt.ylim([0, 100])\nplt.yticks(np.arange(0, 100, 5))\nplt.legend()\nplt.grid(True)\nplt.savefig('problme2_part2.png')\nplt.close()\n\n\n## Best guess\n\nfeature_vector = generate_vectors(50, 4)\ntrain_classifier, test_classifier = generate_classifier_feature(feature_vector, 50, 4)\n# set up a random forest classifier\nrandom_forest_model = RandomForestClassifier(max_depth=32, random_state=8, n_estimators=90)\n# fit the model on training set\nrandom_forest_model.fit(train_classifier.iloc[:, :50], train_classifier.iloc[:, 50])\n# test the model on test set\nprediction = random_forest_model.predict(test_classifier.iloc[:, :50])\n# Calculate the accuracy\nacc = accuracy_score(test_classifier.iloc[:, 50], prediction)\nprint(\"Accuracy achieved is \" + str(acc * 100) + \"%\")\nprint(\"Error rate for the classifier is \"+ str((1-acc)*100)+\"%\")\nprint(confusion_matrix(test_classifier.iloc[:, 50], prediction))","sub_path":"homework4/agglomerative.py","file_name":"agglomerative.py","file_ext":"py","file_size_in_byte":20067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631222734","text":"import tensorflow as tf\ndef inference(x_img,keep_prob,training=True):\n def conv2(input_tensor,size,input_deep,output_deep):\n weight=tf.get_variable('weight',[size,size,input_deep,output_deep])\n bias=tf.get_variable('bias',[output_deep])\n conv1=tf.nn.conv2d(input=input_tensor,filter=weight,strides=[1,1,1,1],padding='SAME')\n conv1=tf.nn.relu(conv1+bias)\n return conv1\n def max_pool(input_tensor):\n return tf.nn.max_pool(input_tensor,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n def fc(input_tensor,input_shape,output_shape,activate,keep_prob):\n fc_weight=tf.get_variable('weight',[input_shape,output_shape])\n fc_bias=tf.get_variable('bias',[output_shape])\n if activate:\n fc=tf.nn.relu(tf.matmul(input_tensor,fc_weight)+fc_bias)\n else:\n fc=tf.matmul(input_tensor,fc_weight)+fc_bias\n if keep_prob is not None:\n fc=tf.nn.dropout(fc,keep_prob)\n return fc\n with tf.variable_scope('conv1'):\n conv1=conv2(x_img,3,1,32)\n conv1=tf.layers.batch_normalization(conv1,training=training)\n with tf.variable_scope('pool1'):\n pool1=max_pool(conv1)\n pool1=tf.layers.batch_normalization(pool1,training=training)\n with tf.variable_scope('conv2'):\n conv2=conv2(pool1,3,32,64)\n conv2=tf.layers.batch_normalization(conv2,training=training)\n with tf.variable_scope('pool2'):\n pool2=max_pool(conv2)\n pool2=tf.layers.batch_normalization(pool2,training=training)\n shapes=pool2.get_shape().as_list()\n print(shapes)\n fc_shape=[-1,shapes[1]*shapes[2]*shapes[3]]\n flatten=tf.reshape(pool2,fc_shape)\n with tf.variable_scope('fc1'):\n fc1=fc(flatten,fc_shape[1],1024,True,keep_prob)\n with tf.variable_scope('fc2'):\n fc2=fc(fc1,1024,10,False,None)\n y=tf.nn.softmax(fc2)\n return y\n \n","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"411395688","text":"from templates import getTemplates\nfrom urllib import request\nimport json\nfrom time import sleep\nfrom threading import Thread\n\nheaders = {\n \"Content-Type\": \"application/x-www-form-urlencoded;\",\n \"Origin\": \"file://\",\n \"User-Agent\": \"Mozilla/5.0 (iPad; CPU OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16B92\",\n \"Accept-Language\": \"en-us\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Connection\": \"close\",\n}\n\nurl = \"http://xzcngame1.funthree.com:7578/gamen.j\"\n\ndef keeper():\n login = request.Request(url, data=json.dumps(getTemplates('login')).encode(), headers=headers)\n request.urlopen(login)\n hb = request.Request(url, data=json.dumps(getTemplates('heartbeat')).encode(), headers=headers)\n while True:\n request.urlopen(hb)\n sleep(5)\n\nThread(target=keeper).start()\n\nsleep(1)\ncount = 0\n\ndef watch(i):\n global count\n for j in range(5, 300, 9):\n coord = \"%d_%d\" % (i, j)\n getmap = request.Request(url, data=json.dumps(getTemplates('getmap',coord)).encode(), headers=headers)\n # print(request.urlopen(getmap).read().decode())\n try:\n rep = json.loads(request.urlopen(getmap).read().decode())\n except:\n sleep(3)\n try:\n rep = json.loads(request.urlopen(getmap).read().decode())\n except:\n sleep(3)\n rep = json.loads(request.urlopen(getmap).read().decode())\n # print(rep)\n for k in rep['worldMap']['walker_counts']:\n getsinglemap = request.Request(url, data=json.dumps(getTemplates('singlemap',k)).encode(), headers=headers)\n rep_single = json.loads(request.urlopen(getsinglemap).read().decode())\n # print(rep_single)\n for r in rep_single['map_grid']['walkers']:\n # print(r)\n print(\"%s, %s, %s, %s\" % (r['gridId'], r['walkerId'], r['walkerName'], r['exts']))\n count -= 1\n\nfor i in range(4, 300, 7):\n while count > 1 :\n sleep(1)\n count += 1\n Thread(target=watch, args=(i,)).start()\n","sub_path":"getmap.py","file_name":"getmap.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16355791","text":"from selenium import webdriver\nimport re\n\nbrowser = webdriver.PhantomJS( )\n#爬取的歌手主页\nurl = 'http://music.163.com/#/artist?id=5771'\n# 打开网页\nbrowser.get(url) \nbrowser.switch_to.frame(browser.find_element_by_xpath(\"//iframe\"))\n#保存网页源码\nprint(browser.page_source,file=open('C:/Users/welwel/Desktop/source.txt','w',encoding='utf-8'))\nbrowser.quit()\n#获取歌曲id,专辑\n#music_html = open('C:/Users/welwel/Desktop/source.html','r',)\n#music_data = music_html.decode(\"utf-8\")\n#re_music = r'<a href=\"/song?id=(.*?)\"><b title=\"(.*?)\">(.*?)</b>'\n#\n#for each_music in match_all:\n# print(each_music)\n\n","sub_path":"初次/wangyi_get.py","file_name":"wangyi_get.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"294766575","text":"# from BaseJob import Jobs\n#\n# testjob = Jobs()\n# countr = testjob.register('172.36.0.1')\n# print(countr)\n# print testjob.get_job(countr,'sssss')\n# print(testjob.get_job('au','s'))\n\n# import time\n#\n# raw = record['create_time']\n# record['create_time'] = time.mktime(time.strptime(raw,\"%Y-%m-%d %H:%M:%S\"))\n# record['create_time'] = record['create_time'] *1000\n# aa = 'B072NC89YQ,B01BPSGESW,B00CKOYVG8,B01N0QH5L4,B07BGDCL4D,B00OTN18VO,B00SYRLNFW,B017DHA3ZE,B00KKEYOTE,B06XKZP15T,B015NHK7Y8,B008M2WGRI,B00NUF4YOA'\n# print aa.split(',')\nimport csvkit\nimport logging\nloger = logging.getLogger('csvtoes')\nloger.setLevel(logging.DEBUG)\nfhandler = logging.FileHandler('d:\\data\\csvtoes.log')\nshandler = logging.StreamHandler()\nloger.addHandler(shandler)\nloger.addHandler(fhandler)\nloger.warn('hello i am debug info 2')\nloger.warn('fatal error happened ')\n","sub_path":"advance/awsjobs/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}