diff --git "a/384.jsonl" "b/384.jsonl" new file mode 100644--- /dev/null +++ "b/384.jsonl" @@ -0,0 +1,726 @@ +{"seq_id":"617462275","text":"from parlai.agents.programr.parser.template.nodes.base import TemplateNode\nfrom parlai.agents.programr.utils.logging.ylogger import YLogger\nfrom parlai.agents.programr.utils.text.text import TextUtils\n\n\nclass TemplateCarouselNode(TemplateNode):\n\n def __init__(self):\n super().__init__()\n self._cards = []\n\n def resolve_to_string(self, brain):\n str = \"\"\n for card in self._cards:\n str += card.resolve_to_string(brain)\n str += \"\"\n return str\n\n def resolve(self, brain):\n try:\n return self.resolve_to_string(brain)\n except Exception as excep:\n YLogger.exception(brain, \"Failed to resolve\", excep)\n return \"\"\n\n def to_string(self):\n return \"[CAROUSEL] %d\" % (len(self._cards))\n\n def to_xml(self, brain):\n return self.resolve_to_string(brain)\n\n #######################################################################################################\n #\n\n def parse_expression(self, graph, expression):\n head_text = self.get_text_from_element(expression)\n self.parse_text(graph, head_text)\n\n for child in expression:\n tag_name = TextUtils.tag_from_text(child.tag)\n\n if tag_name == 'card':\n card_class = graph.get_node_class_by_name(\"card\")\n card = card_class()\n card.parse_expression(graph, child)\n self._cards.append(card)\n else:\n graph.parse_tag_expression(child, self)\n\n tail_text = self.get_tail_from_element(child)\n self.parse_text(graph, tail_text)\n\n","sub_path":"parlai/agents/programr/parser/template/nodes/richmedia/carousel.py","file_name":"carousel.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"79100609","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport nltk\nfrom nltk.corpus import stopwords\nimport re\nimport pickle\n\n# language modeling sklearn package \nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# reporcess the data and concat \n# keep the columns user ID uer login month n_post, n_unigram, n_unique,n_newword,vector,community (exclude use's)\n# In[2]:\n\n\n# caculate the number of posts each month the monthly data is not aggregated\ns_month_pkl = open('snap_month.pkl', 'rb')\n# list of tables which has the comment splitted with commas \ndf_list = pickle.load(s_month_pkl)\n\n\n# In[3]:\n\n\ndf_list[0].columns\n\n\n# In[4]:\n\n\n# the commnuity corpus here is a single string which is the collection of many strings and join together with white space\n\ndef corpus(all_comment,x):\n if len(x)==1:\n com_corpus = x\n else: \n com_corpus = [i for i in all_comment if i not in x]\n \n return ' '.join(com_corpus)\n\n# The new fuction added to exclude new words which intriduced by the user in user's corpus\n# the filtered comment will be vectorized and compaired to the commnunity corpus \n# the column that store the filtered comment for each user named 'vector'\n\ndef exclude_newwords(user_comment,community_corpus):\n user_words = user_comment.split()\n community_words = community_corpus.split()\n new_words = list(set(user_words).difference(set(community_words))) \n exclude_new_words = [i for i in user_words if i not in new_words]\n return ' '.join(exclude_new_words)\n \n\n\n# In[5]:\n\n\n# build the community corpus for each user \n# including newwords, vecotr,community_corpus\ndef build_dataframe(df):\n df['post']=df['comment'].apply(lambda x : ' '.join(x.split(',')))\n df['n_post']=df['comment'].apply(lambda x: len(x.split(',')))\n df['n_unigram'] = df['post'].apply(lambda x: len(x.split()))\n df['n_unique'] = df['post'].apply(lambda x: len(set(x.split())))\n all_comment = df['post'].tolist()\n df['community_corpus'] = df['post'].apply(lambda x: corpus(all_comment,x))\n df['vector']=[exclude_newwords(x,y) for x,y in zip(df['post'],df['community_corpus'])]\n df['n_newword'] = [len(x.split())-len(y.split())for x,y in zip(df['post'],df['vecor'])]\n return df[['user_name', 'month','n_post','n_unigram',\n 'n_unique','n_newword','vector','community_corpus']]\n\n\n# In[9]:\n\n\nlist_of_df=[]\nfor df in df_list:\n ndf = build_dataframe(df)\n list_of_df.append(ndf) \n\n\n# In[10]:\n\n\nlen(list_of_df)\n\n\n# In[12]:\n\n\nwith open ('snapshot_dataframe.pkl','wb') as f:\n pickle.dump(list_of_df,f)\n\n\n# # cosim similarity for all comments\n\n# In[13]:\n\n\ndef tokens(text):\n tokens = text.split()\n return tokens\n\ntf_vect = CountVectorizer(tokenizer = tokens, stop_words = None)\n\n# vectorizer use nltk tokenizer\ndef cosine_similarity_score(x,y):\n train_set = [x,y]\n vect = tf_vect.fit_transform(train_set)\n cos_sim = cosine_similarity(vect[0:1], vect)\n return cos_sim[0][1]\n\n\n# generate a new column to store the result\n# the name of the column is the number of month\ndef append_cosim (table):\n #table.replace('',np.nan,inplace=True)\n table['cosine_similarity'] = [cosine_similarity_score(x,y) for x,y in zip(table['vector'].astype(str),table['community_corpus'].astype(str))]\n df = table.drop(columns = ['vector','community_corpus']).copy() \n return df\n\n\n# In[15]:\n\n\n# final dataframe of each month\nlist_fdf=[]\nfor df in list_of_df:\n fdf=append_cosim(df)\n list_fdf.append(fdf)\n\n\n# In[16]:\n\n\nlen(list_fdf)\n\n\n# In[17]:\n\n\n# the final table of all 24 months\n# concat them together\nf_df = pd.concat(list_fdf).reset_index(drop=True)\n\n\n# In[20]:\n\n\n## fix the newword data\n\n\n# In[23]:\n\n\n# build the community corpus for each user \n# including newwords, vecotr,community_corpus\ndef fix_newword(df):\n df['post']=df['comment'].apply(lambda x : ' '.join(x.split(',')))\n all_comment = df['post'].tolist()\n df['community_corpus'] = df['post'].apply(lambda x: corpus(all_comment,x))\n df['vector']=[exclude_newwords(x,y) for x,y in zip(df['post'],df['community_corpus'])]\n df['n_newword'] = [len(x.split())-len(y.split())for x,y in zip(df['post'],df['vector'])]\n return df[['n_newword']]\n\n\n# In[26]:\n\n\nfix_dfs=[]\nfor df in df_list:\n fix = fix_newword(df)\n fix_dfs.append(fix)\n\n\n# In[27]:\n\n\nfix_df = pd.concat(fix_dfs).reset_index(drop=True)\n\n\n# In[29]:\n\n\nf_df['n_newword']=fix_df['n_newword']\n\n\n# In[30]:\n\n\nprint(len(f_df))\n\nf_df.head()\n\n\n# In[31]:\n\n\nf_df.to_csv('Snapshot_user_in_month.csv',index=False)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"10_03 each month data together Not aggregate it (snapshot).py","file_name":"10_03 each month data together Not aggregate it (snapshot).py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"349526552","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass LocalItemSkuCreateVO(object):\n\n def __init__(self):\n self._original_price = None\n self._sale_price = None\n self._sale_status = None\n self._stock_num = None\n\n @property\n def original_price(self):\n return self._original_price\n\n @original_price.setter\n def original_price(self, value):\n self._original_price = value\n @property\n def sale_price(self):\n return self._sale_price\n\n @sale_price.setter\n def sale_price(self, value):\n self._sale_price = value\n @property\n def sale_status(self):\n return self._sale_status\n\n @sale_status.setter\n def sale_status(self, value):\n self._sale_status = value\n @property\n def stock_num(self):\n return self._stock_num\n\n @stock_num.setter\n def stock_num(self, value):\n self._stock_num = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.original_price:\n if hasattr(self.original_price, 'to_alipay_dict'):\n params['original_price'] = self.original_price.to_alipay_dict()\n else:\n params['original_price'] = self.original_price\n if self.sale_price:\n if hasattr(self.sale_price, 'to_alipay_dict'):\n params['sale_price'] = self.sale_price.to_alipay_dict()\n else:\n params['sale_price'] = self.sale_price\n if self.sale_status:\n if hasattr(self.sale_status, 'to_alipay_dict'):\n params['sale_status'] = self.sale_status.to_alipay_dict()\n else:\n params['sale_status'] = self.sale_status\n if self.stock_num:\n if hasattr(self.stock_num, 'to_alipay_dict'):\n params['stock_num'] = self.stock_num.to_alipay_dict()\n else:\n params['stock_num'] = self.stock_num\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = LocalItemSkuCreateVO()\n if 'original_price' in d:\n o.original_price = d['original_price']\n if 'sale_price' in d:\n o.sale_price = d['sale_price']\n if 'sale_status' in d:\n o.sale_status = d['sale_status']\n if 'stock_num' in d:\n o.stock_num = d['stock_num']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/LocalItemSkuCreateVO.py","file_name":"LocalItemSkuCreateVO.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"116543224","text":"'''\nInput: a List of integers\nReturns: a List of integers\n'''\n\n\ndef moving_zeroes(arr):\n # Your code here\n # if its is zero, remove from list\n non_zero = [i for i in arr if i != 0]\n zero = [i for i in arr if i == 0]\n non_zero.extend(zero) # extend add to the end of the list\n return non_zero\n\n\nif __name__ == '__main__':\n # Use the main function here to test out your implementation\n arr = [0, 3, 1, 0, -2]\n\n print(f\"The resulting of moving_zeroes is: {moving_zeroes(arr)}\")\n","sub_path":"moving_zeroes/moving_zeroes.py","file_name":"moving_zeroes.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"618742134","text":"from django.forms import ModelForm\n\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout\nfrom crispy_forms.bootstrap import StrictButton\n\nfrom .models import Event\n\n\nclass EventForm(ModelForm):\n\n class Meta:\n model = Event\n fields = ['title', 'start', 'end']\n\n def __init__(self, *args, **kwargs):\n super(EventForm, self).__init__(*args, **kwargs)\n\n self.helper = FormHelper()\n self.helper.form_method = 'post'\n self.helper.form_action = 'event_add'\n self.helper.form_class = 'form-horizontal'\n self.helper.label_class = 'col-lg-2'\n self.helper.field_class = 'col-lg-2'\n self.helper.layout = Layout(\n 'title',\n 'start',\n 'end',\n StrictButton('Create Event', css_class='btn-default', type='submit')\n )\n","sub_path":"simplepearl/planner/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"610713241","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 24 21:18:39 2020\r\n\r\n@author: salam\r\n\"\"\"\r\n\r\n# Remove missing data\r\n\r\ncountries = [\"\", \"Argentina\", \"\", \"Brazil\", \"Chile\", \"\", \"Columbia\", \r\n \"\", \"Ecuador\", \"\", \"\", \"Venezuela\"]\r\n\r\ny = list(filter(None, countries))\r\n\r\nprint(y)","sub_path":"removing_basic_data.py","file_name":"removing_basic_data.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"72207434","text":"import importlib\nimport os\nimport socket\nimport sys\nfrom os import environ\nfrom os.path import basename, normpath\nfrom pathlib import Path\nfrom platform import system\nfrom shutil import copytree, which\nfrom subprocess import PIPE, Popen\nfrom typing import List, Optional\nfrom urllib import request\nfrom warnings import warn\n\nimport matplotlib.pyplot as plt\nimport pkg_resources\nimport pytest\n\n# constants\n\nSHAPEFILE_EXTENSIONS = [\"prj\", \"shx\", \"dbf\"]\n\n\n# misc utilities\n\n\ndef get_project_root_path(path=None) -> Path:\n \"\"\"\n Infers the path to the project root given the path to the current working directory.\n The current working location must be somewhere in the project, below the project root.\n\n This function aims to work whether invoked from the autotests directory, the examples\n directory, the flopy module directory, or any subdirectories of these. GitHub Actions\n CI runners, local `act` runners for GitHub CI, and local environments are supported.\n This function can be modified to support other flopy testing environments if needed.\n\n Parameters\n ----------\n path : the path to the current working directory\n\n Returns\n -------\n The absolute path to the project root\n \"\"\"\n\n cwd = Path(path) if path is not None else Path(os.getcwd())\n\n def backtrack_or_raise():\n tries = [1]\n if is_in_ci():\n tries.append(2)\n for t in tries:\n parts = cwd.parts[0 : cwd.parts.index(\"flopy\") + t]\n pth = Path(*parts)\n if (\n next(iter([p for p in pth.glob(\"setup.cfg\")]), None)\n is not None\n ):\n return pth\n raise Exception(\n f\"Can't infer location of project root from {cwd} \"\n f\"(run from project root, flopy module, examples, or autotest)\"\n )\n\n if cwd.name == \"autotest\":\n # we're in top-level autotest folder\n return cwd.parent\n elif \"autotest\" in cwd.parts and cwd.parts.index(\n \"autotest\"\n ) > cwd.parts.index(\"flopy\"):\n # we're somewhere inside autotests\n parts = cwd.parts[0 : cwd.parts.index(\"autotest\")]\n return Path(*parts)\n elif \"examples\" in cwd.parts and cwd.parts.index(\n \"examples\"\n ) > cwd.parts.index(\"flopy\"):\n # we're somewhere inside examples folder\n parts = cwd.parts[0 : cwd.parts.index(\"examples\")]\n return Path(*parts)\n elif \"flopy\" in cwd.parts:\n if cwd.parts.count(\"flopy\") >= 2:\n # we're somewhere inside the project or flopy module\n return backtrack_or_raise()\n elif cwd.parts.count(\"flopy\") == 1:\n if cwd.name == \"flopy\":\n # we're in project root\n return cwd\n elif cwd.name == \".working\":\n # we're in local `act` github actions runner\n return backtrack_or_raise()\n else:\n raise Exception(\n f\"Can't infer location of project root from {cwd}\"\n f\"(run from project root, flopy module, examples, or autotest)\"\n )\n else:\n raise Exception(\n f\"Can't infer location of project root from {cwd}\"\n f\"(run from project root, flopy module, examples, or autotest)\"\n )\n\n\ndef get_example_data_path(path=None) -> Path:\n \"\"\"\n Gets the absolute path to example models and data.\n The path argument is a hint, interpreted as\n the current working location.\n \"\"\"\n return get_project_root_path(path) / \"examples\" / \"data\"\n\n\ndef get_flopy_data_path(path=None) -> Path:\n \"\"\"\n Gets the absolute path to flopy module data.\n The path argument is a hint, interpreted as\n the current working location.\n \"\"\"\n return get_project_root_path(path) / \"flopy\" / \"data\"\n\n\ndef get_current_branch() -> str:\n # check if on GitHub Actions CI\n ref = environ.get(\"GITHUB_REF\")\n if ref is not None:\n return basename(normpath(ref)).lower()\n\n # otherwise ask git about it\n if not which(\"git\"):\n raise RuntimeError(\"'git' required to determine current branch\")\n stdout, stderr, code = run_cmd(\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\")\n if code == 0 and stdout:\n return stdout.strip().lower()\n raise ValueError(f\"Could not determine current branch: {stderr}\")\n\n\ndef is_connected(hostname):\n \"\"\"See https://stackoverflow.com/a/20913928/ to test hostname.\"\"\"\n try:\n host = socket.gethostbyname(hostname)\n s = socket.create_connection((host, 80), 2)\n s.close()\n return True\n except Exception:\n pass\n return False\n\n\ndef is_in_ci():\n # if running in GitHub Actions CI, \"CI\" variable always set to true\n # https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables\n return bool(os.environ.get(\"CI\", None))\n\n\ndef is_github_rate_limited() -> Optional[bool]:\n \"\"\"\n Determines if a GitHub API rate limit is applied to the current IP.\n Note that running this function will consume an API request!\n\n Returns\n -------\n True if rate-limiting is applied, otherwise False (or None if the connection fails).\n \"\"\"\n try:\n with request.urlopen(\n \"https://api.github.com/users/octocat\"\n ) as response:\n remaining = int(response.headers[\"x-ratelimit-remaining\"])\n if remaining < 10:\n warn(\n f\"Only {remaining} GitHub API requests remaining before rate-limiting\"\n )\n return remaining > 0\n except:\n return None\n\n\n_has_exe_cache = {}\n_has_pkg_cache = {}\n\n\ndef has_exe(exe):\n if exe not in _has_exe_cache:\n _has_exe_cache[exe] = bool(which(exe))\n return _has_exe_cache[exe]\n\n\ndef has_pkg(pkg):\n if pkg not in _has_pkg_cache:\n\n # for some dependencies, package name and import name are different\n # (e.g. pyshp/shapefile, mfpymake/pymake, python-dateutil/dateutil)\n # pkg_resources expects package name, importlib expects import name\n try:\n _has_pkg_cache[pkg] = bool(importlib.import_module(pkg))\n except ModuleNotFoundError:\n try:\n _has_pkg_cache[pkg] = bool(pkg_resources.get_distribution(pkg))\n except pkg_resources.DistributionNotFound:\n _has_pkg_cache[pkg] = False\n\n return _has_pkg_cache[pkg]\n\n\ndef requires_exe(*exes):\n missing = {exe for exe in exes if not has_exe(exe)}\n return pytest.mark.skipif(\n missing,\n reason=f\"missing executable{'s' if len(missing) != 1 else ''}: \"\n + \", \".join(missing),\n )\n\n\ndef requires_pkg(*pkgs):\n missing = {pkg for pkg in pkgs if not has_pkg(pkg)}\n return pytest.mark.skipif(\n missing,\n reason=f\"missing package{'s' if len(missing) != 1 else ''}: \"\n + \", \".join(missing),\n )\n\n\ndef requires_platform(platform, ci_only=False):\n return pytest.mark.skipif(\n system().lower() != platform.lower()\n and (is_in_ci() if ci_only else True),\n reason=f\"only compatible with platform: {platform.lower()}\",\n )\n\n\ndef excludes_platform(platform, ci_only=False):\n return pytest.mark.skipif(\n system().lower() == platform.lower()\n and (is_in_ci() if ci_only else True),\n reason=f\"not compatible with platform: {platform.lower()}\",\n )\n\n\ndef requires_branch(branch):\n current = get_current_branch()\n return pytest.mark.skipif(\n current != branch, reason=f\"must run on branch: {branch}\"\n )\n\n\ndef excludes_branch(branch):\n current = get_current_branch()\n return pytest.mark.skipif(\n current == branch, reason=f\"can't run on branch: {branch}\"\n )\n\n\nrequires_github = pytest.mark.skipif(\n not is_connected(\"github.com\"), reason=\"github.com is required.\"\n)\n\n\nrequires_spatial_reference = pytest.mark.skipif(\n not is_connected(\"spatialreference.org\"),\n reason=\"spatialreference.org is required.\",\n)\n\n\n# example data fixtures\n\n\n@pytest.fixture(scope=\"session\")\ndef project_root_path(request) -> Path:\n return get_project_root_path(request.session.path)\n\n\n@pytest.fixture(scope=\"session\")\ndef example_data_path(request) -> Path:\n return get_example_data_path(request.session.path)\n\n\n@pytest.fixture(scope=\"session\")\ndef flopy_data_path(request) -> Path:\n return get_flopy_data_path(request.session.path)\n\n\n@pytest.fixture(scope=\"session\")\ndef example_shapefiles(example_data_path) -> List[Path]:\n return [f.resolve() for f in (example_data_path / \"prj_test\").glob(\"*\")]\n\n\n# keepable temporary directory fixtures for various scopes\n\n\n@pytest.fixture(scope=\"function\")\ndef tmpdir(tmpdir_factory, request) -> Path:\n node = (\n request.node.name.replace(\"/\", \"_\")\n .replace(\"\\\\\", \"_\")\n .replace(\":\", \"_\")\n )\n temp = Path(tmpdir_factory.mktemp(node))\n yield Path(temp)\n\n keep = request.config.getoption(\"--keep\")\n if keep:\n copytree(temp, Path(keep) / temp.name)\n\n keep_failed = request.config.getoption(\"--keep-failed\")\n if keep_failed and request.node.rep_call.failed:\n copytree(temp, Path(keep_failed) / temp.name)\n\n\n@pytest.fixture(scope=\"class\")\ndef class_tmpdir(tmpdir_factory, request) -> Path:\n assert (\n request.cls is not None\n ), \"Class-scoped temp dir fixture must be used on class\"\n temp = Path(tmpdir_factory.mktemp(request.cls.__name__))\n yield temp\n\n keep = request.config.getoption(\"--keep\")\n if keep:\n copytree(temp, Path(keep) / temp.name)\n\n\n@pytest.fixture(scope=\"module\")\ndef module_tmpdir(tmpdir_factory, request) -> Path:\n temp = Path(tmpdir_factory.mktemp(request.module.__name__))\n yield temp\n\n keep = request.config.getoption(\"--keep\")\n if keep:\n copytree(temp, Path(keep) / temp.name)\n\n\n@pytest.fixture(scope=\"session\")\ndef session_tmpdir(tmpdir_factory, request) -> Path:\n temp = Path(tmpdir_factory.mktemp(request.session.name))\n yield temp\n\n keep = request.config.getoption(\"--keep\")\n if keep:\n copytree(temp, Path(keep) / temp.name)\n\n\n# fixture to automatically close any plots (or optionally show them)\n\n\n@pytest.fixture(autouse=True)\ndef close_plot(request):\n yield\n\n # plots only shown if requested via CLI flag,\n # figures are available, and we're not in CI\n show = request.config.getoption(\"--show-plots\")\n if len(plt.get_fignums()) > 0 and not is_in_ci() and show:\n plt.show()\n else:\n plt.close(\"all\")\n\n\n# pytest configuration hooks\n\n\n@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_runtest_makereport(item, call):\n # this is necessary so temp dir fixtures can\n # inspect test results and check for failure\n # (see https://doc.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures)\n\n outcome = yield\n rep = outcome.get_result()\n\n # report attribute for each phase (setup, call, teardown)\n # we're only interested in result of the function call\n setattr(item, \"rep_\" + rep.when, rep)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"-K\",\n \"--keep\",\n action=\"store\",\n default=None,\n help=\"Move the contents of temporary test directories to correspondingly named subdirectories at the given \"\n \"location after tests complete. This option can be used to exclude test results from automatic cleanup, \"\n \"e.g. for manual inspection. The provided path is created if it does not already exist. An error is \"\n \"thrown if any matching files already exist.\",\n )\n\n parser.addoption(\n \"--keep-failed\",\n action=\"store\",\n default=None,\n help=\"Move the contents of temporary test directories to correspondingly named subdirectories at the given \"\n \"location if the test case fails. This option automatically saves the outputs of failed tests in the \"\n \"given location. The path is created if it doesn't already exist. An error is thrown if files with the \"\n \"same names already exist in the given location.\",\n )\n\n parser.addoption(\n \"-M\",\n \"--meta\",\n action=\"store\",\n metavar=\"NAME\",\n help=\"Marker indicating a test is only run by other tests (e.g., the test framework testing itself).\",\n )\n\n parser.addoption(\n \"-S\",\n \"--smoke\",\n action=\"store_true\",\n default=False,\n help=\"Run only smoke tests (should complete in <1 minute).\",\n )\n\n parser.addoption(\n \"--show-plots\",\n action=\"store_true\",\n default=False,\n help=\"Show any figure windows created by test cases. (Useful to display plots for visual inspection, \"\n \"but automated tests should probably also check patch collections or figure & axis properties.)\",\n )\n\n\ndef pytest_configure(config):\n config.addinivalue_line(\n \"markers\",\n \"meta(name): mark test to run only inside other groups of tests.\",\n )\n\n\ndef pytest_runtest_setup(item):\n # apply meta-test option\n meta = item.config.getoption(\"--meta\")\n metagroups = [mark.args[0] for mark in item.iter_markers(name=\"meta\")]\n if metagroups and meta not in metagroups:\n pytest.skip()\n\n # smoke tests are \\ {slow U example U regression}\n smoke = item.config.getoption(\"--smoke\")\n slow = list(item.iter_markers(name=\"slow\"))\n example = list(item.iter_markers(name=\"example\"))\n regression = list(item.iter_markers(name=\"regression\"))\n if smoke and (slow or example or regression):\n pytest.skip()\n\n\ndef pytest_report_header(config):\n \"\"\"Header for pytest to show versions of packages.\"\"\"\n\n # if we ever drop support for python 3.7, could use importlib.metadata instead?\n # or importlib_metadata backport: https://importlib-metadata.readthedocs.io/en/latest/\n # pkg_resources discouraged: https://setuptools.pypa.io/en/latest/pkg_resources.html\n\n processed = set()\n flopy_pkg = pkg_resources.get_distribution(\"flopy\")\n lines = []\n items = []\n for pkg in flopy_pkg.requires():\n name = pkg.name\n processed.add(name)\n try:\n version = pkg_resources.get_distribution(name).version\n items.append(f\"{name}-{version}\")\n except pkg_resources.DistributionNotFound:\n items.append(f\"{name} (not found)\")\n lines.append(\"required packages: \" + \", \".join(items))\n installed = []\n not_found = []\n for pkg in flopy_pkg.requires([\"optional\"]):\n name = pkg.name\n if name in processed:\n continue\n processed.add(name)\n try:\n version = pkg_resources.get_distribution(name).version\n installed.append(f\"{name}-{version}\")\n except pkg_resources.DistributionNotFound:\n not_found.append(name)\n if installed:\n lines.append(\"optional packages: \" + \", \".join(installed))\n if not_found:\n lines.append(\"optional packages not found: \" + \", \".join(not_found))\n return \"\\n\".join(lines)\n\n\n# functions to run commands and scripts\n\n\ndef run_cmd(*args, verbose=False, **kwargs):\n \"\"\"Run any command, return tuple (stdout, stderr, returncode).\"\"\"\n args = [str(g) for g in args]\n if verbose:\n print(\"running: \" + \" \".join(args))\n p = Popen(args, stdout=PIPE, stderr=PIPE, **kwargs)\n stdout, stderr = p.communicate()\n stdout = stdout.decode()\n stderr = stderr.decode()\n returncode = p.returncode\n if verbose:\n print(f\"stdout:\\n{stdout}\")\n print(f\"stderr:\\n{stderr}\")\n print(f\"returncode: {returncode}\")\n return stdout, stderr, returncode\n\n\ndef run_py_script(script, *args, verbose=False):\n \"\"\"Run a Python script, return tuple (stdout, stderr, returncode).\"\"\"\n return run_cmd(\n sys.executable, script, *args, verbose=verbose, cwd=Path(script).parent\n )\n\n\n# use noninteractive matplotlib backend if in Mac OS CI to avoid pytest-xdist node failure\n# e.g. https://github.com/modflowpy/flopy/runs/7748574375?check_suite_focus=true#step:9:57\n@pytest.fixture(scope=\"session\", autouse=True)\ndef patch_macos_ci_matplotlib():\n if is_in_ci() and system().lower() == \"darwin\":\n import matplotlib\n\n matplotlib.use(\"agg\")\n","sub_path":"autotest/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":16223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"106147401","text":"import turtle\n\ndef draw_square(name):\n for i in range(0,4):\n name.forward(100)\n name.right(90)\n\ndef drawing():\n window = turtle.Screen()\n window.bgcolor(\"green\")\n\n anca = turtle.Turtle()\n anca.shape(\"turtle\")\n anca.speed(2)\n anca.color(\"yellow\")\n for i in range(1,37):\n draw_square(anca)\n anca.right(10)\n\n tibi = turtle.Turtle()\n tibi.circle(100)\n tibi.shape(\"turtle\")\n tibi.color(\"blue\")\n\n chibi = turtle.Turtle()\n chibi.shape(\"turtle\")\n chibi.color(\"blue\")\n timesx = 1\n while timesx <=3:\n chibi.forward(80)\n chibi.left(120)\n timesx +=1\n\n window.exitonclick()\ndrawing()\n","sub_path":"drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"610918157","text":"from django.shortcuts import get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom products.models import Product\nfrom .models import Cart\nimport yaml\n\n\ndef cart_contents(request):\n \"\"\"\n Ensures that the cart contents are available when rendering\n every page\n \"\"\"\n cart = request.session.get('cart', {})\n if request.user.is_authenticated:\n sync_carts(request)\n shippingfee = 8\n cart_items = []\n total = 0\n product_count = 0\n for id, quantity in cart.items():\n product = get_object_or_404(Product, pk=id)\n total += quantity * product.price\n product_count += quantity\n cart_items.append({'id': id, 'quantity': quantity, 'product': product})\n if total < 50:\n total += shippingfee\n else:\n shippingfee = \"FREE\"\n\n return {'cart_items': cart_items, 'total': total, 'product_count':\n product_count, 'shippingfee': shippingfee}\n\n\n\"\"\"\nmethod not in use anymore as I found dictionary conversion\ninto string and converting back to dictionary with yaml better\nto store whole cart content into one field in db. But splitting\nthe cart dictionary into two strings (one for keys and one for values)\nto make it fit for a CharField worked too, same as for re-conversion\nfrom string to dictionary.\n\ndef make_cart_strings(cart):\n idstring=\"\"\n quantitystring=\"\"\n for k,v in cart.items():\n idstring+=str(k)+\",\"\n quantitystring+=str(v)+\",\"\n return (idstring, quantitystring)\n\n\ndef make_cart_dict(productstring, quantitystring):\n idlist = productstring.split(',')\n idlist.pop(len(idlist)-1)\n quantitylist = quantitystring.split(',')\n quantitylist.pop(len(quantitylist)-1)\n quantitylist_iter = iter(quantitylist)\n newcart = {}\n for id in idlist:\n newcart[id]=next(quantitylist_iter)\n return newcart\n\"\"\"\n\n\ndef merge_carts(tmp_cart_from_db, cart):\n \"\"\"\n Compares both carts and if products found on both carts (cart in session)\n and cart in database. They are merged with higher product quantity. \n \"\"\"\n merged_cart = cart\n quantity_change = False\n\n for id, quantity in tmp_cart_from_db.items():\n if id not in merged_cart:\n merged_cart[id] = quantity\n elif id in merged_cart:\n if tmp_cart_from_db[id] > merged_cart[id]:\n merged_cart[id] = quantity\n quantity_change = True\n return merged_cart, quantity_change\n\n\n@login_required\ndef sync_carts(request):\n \"\"\"\n When user already has added products to the shopping cart and loggs in,\n the idea is to merge that local cart with the shopping cart found in\n database (if any).\n \"\"\"\n cart = request.session.get('cart', {})\n user_cart = None\n\n try:\n user_cart = Cart.objects.get(user=request.user.id)\n except:\n messages.success(request, \"Saving cart to database\")\n name = str(request.user)+\"'s cart\"\n user_cart = Cart(user=request.user, name=name, product_list=\"\")\n user_cart.save()\n\n if user_cart.product_list != \"\":\n if cart == {}:\n request.session['cart'] = yaml.load(user_cart.product_list,\n Loader=yaml.FullLoader)\n else:\n tmp_cart_db = yaml.load(user_cart.product_list,\n Loader=yaml.FullLoader)\n tmp_merged_cart = merge_carts(tmp_cart_db, cart)\n merged_cart = tmp_merged_cart[0]\n quantity_change = tmp_merged_cart[1]\n user_cart.product_list = str(merged_cart)\n user_cart.save()\n request.session['cart'] = merged_cart\n if quantity_change:\n messages.success(request, \"Order quantity has been updated for \\\n someproducts with higher value.\")\n\n elif user_cart.product_list == \"\":\n if cart != {}:\n user_cart.product_list = str(cart)\n user_cart.save()\n return\n","sub_path":"cart/contexts.py","file_name":"contexts.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"273941519","text":"\"\"\"\nA series of classifiers that evaluate transMap, AugustusTMR and AugustusCGP output.\n\nThese classifiers are broken down into 2 groups, which will each end up as a table in the database:\n\n__Metrics:\n\nThese classifiers are per-transcript evaluations based on both the transcript alignment and the genome context.\n1. PercentUnknownBases: % of mRNA bases that are Ns.\n2. AlnCoverage: Alignment coverage in transcript space.\n3. AlnIdentity: Alignment identity in transcript space.\n4. PercentMissingIntrons: Number of original introns not within a wiggle distance of any introns in the target.\n5. PercentMissingExons: Do we lose any exons? Defined based on parent sequence, with wiggle room.\n6. CdsStartStat: Is the CDS likely to be a complete start? Simply extracted from the genePred\n7. CdsEndStat: Is the CDS likely to be a complete stop? Simply extracted from the genePred\n\n__Evaluation:\n\nThese classifiers are per-transcript evaluations based on the transcript alignment.\nUnlike the other two tables, this table stores the actual location of the problems (in genome coordinates) as a\nBED-like format. In cases where there are multiple problems, they will be additional rows.\n1. CodingInsertion: Do we have any frame-shifting coding insertions?\n2. CodingDeletion: Do we have any frame-shifting coding deletions?\n3. CodingMult3Insertion: Do we have any mod3 coding insertions?\n4. CodingMult3Deletion: Do we have any mod3 coding deletions?\n5. NonCodingInsertion: Do we have indels in UTR sequence?\n6. NonCodingDeletion: Do we have any indels in UTR sequence?\n7. InFrameStop: Are there any in-frame stop codons?\n\n\nThe Metrics and Evaluation groups will have multiple tables for each of the input methods used:\ntxMode:\n1) transMap\n2) augTM\n3) augTMR\n4) augCGP\n\nalnMode:\n1) CDS\n2) mRNA\n\n\"\"\"\nimport itertools\n\nimport pandas as pd\n\nimport tools.bio\nimport tools.dataOps\nimport tools.fileOps\nimport tools.intervals\nimport tools.mathOps\nimport tools.nameConversions\nimport tools.psl\nimport tools.sqlInterface\nimport tools.transcripts\n\n# hard coded variables\n# fuzz distance is the distance between introns allowed in intron coordinates before triggering NumMissingIntrons\n# fuzz distance is counted from both sides of the intron\nfuzz_distance = 7\n# the amount of exon-exon coverage required to consider a exon as present\nmissing_exons_coverage_cutoff = 0.8\n\n\ndef classify(eval_args):\n \"\"\"\n Runs alignment classification for all alignment modes\n :param eval_args: argparse Namespace produced by EvaluateTranscripts.get_args()\n :return: list of (tablename, dataframe) tuples\n \"\"\"\n # load shared inputs\n ref_tx_dict = tools.transcripts.get_gene_pred_dict(eval_args.annotation_gp)\n tx_biotype_map = tools.sqlInterface.get_transcript_biotype_map(eval_args.ref_db_path)\n seq_dict = tools.bio.get_sequence_dict(eval_args.fasta)\n # results stores the final dataframes\n results = {}\n for tx_mode, path_dict in eval_args.transcript_modes.iteritems():\n tx_dict = tools.transcripts.get_gene_pred_dict(path_dict['gp'])\n aln_modes = ['CDS', 'mRNA'] if tx_mode != 'augCGP' else ['CDS']\n for aln_mode in aln_modes:\n psl_iter = list(tools.psl.psl_iterator(path_dict[aln_mode]))\n mc_df = metrics_classify(aln_mode, ref_tx_dict, tx_dict, tx_biotype_map, psl_iter)\n ec_df = evaluation_classify(aln_mode, ref_tx_dict, tx_dict, tx_biotype_map, psl_iter, seq_dict)\n results[tools.sqlInterface.tables[aln_mode][tx_mode]['metrics'].__tablename__] = mc_df\n results[tools.sqlInterface.tables[aln_mode][tx_mode]['evaluation'].__tablename__] = ec_df\n return results\n\n\ndef metrics_classify(aln_mode, ref_tx_dict, tx_dict, tx_biotype_map, psl_iter):\n \"\"\"\n Calculates the alignment metrics and the number of missing original introns on this transcript_chunk\n :return: DataFrame\n \"\"\"\n r = []\n for ref_tx, tx, psl, biotype in tx_iter(psl_iter, ref_tx_dict, tx_dict, tx_biotype_map):\n if biotype == 'protein_coding':\n start_ok, stop_ok = start_stop_stat(tx)\n r.append([ref_tx.name2, ref_tx.name, tx.name, 'StartCodon', start_ok])\n r.append([ref_tx.name2, ref_tx.name, tx.name, 'StopCodon', stop_ok])\n percent_missing_introns = calculate_percent_original_introns(ref_tx, tx, psl, aln_mode)\n percent_missing_exons = calculate_percent_original_exons(ref_tx, psl, aln_mode)\n r.append([ref_tx.name2, ref_tx.name, tx.name, 'AlnCoverage', psl.coverage])\n r.append([ref_tx.name2, ref_tx.name, tx.name, 'AlnIdentity', psl.identity])\n r.append([ref_tx.name2, ref_tx.name, tx.name, 'PercentUnknownBases', psl.percent_n])\n r.append([ref_tx.name2, ref_tx.name, tx.name, 'PercentOriginalIntrons', percent_missing_introns])\n r.append([ref_tx.name2, ref_tx.name, tx.name, 'PercentOriginalExons', percent_missing_exons])\n columns = ['GeneId', 'TranscriptId', 'AlignmentId', 'classifier', 'value']\n df = pd.DataFrame(r, columns=columns)\n df.value = pd.to_numeric(df.value) # coerce all into floats\n df = df.sort_values(columns)\n df = df.set_index(['GeneId', 'TranscriptId', 'AlignmentId', 'classifier'])\n assert len(r) == len(df)\n return df\n\n\ndef evaluation_classify(aln_mode, ref_tx_dict, tx_dict, tx_biotype_map, psl_iter, seq_dict):\n \"\"\"\n Calculates the evaluation metrics on this transcript_chunk\n :return: DataFrame\n \"\"\"\n r = []\n for ref_tx, tx, psl, biotype in tx_iter(psl_iter, ref_tx_dict, tx_dict, tx_biotype_map):\n indels = find_indels(tx, psl, aln_mode)\n for category, i in indels:\n r.append([ref_tx.name2, ref_tx.name, tx.name, category, i.chromosome, i.start, i.stop, i.strand])\n if biotype == 'protein_coding' and tx.cds_size > 50: # we don't want to evaluate tiny ORFs\n i = in_frame_stop(tx, seq_dict)\n if i is not None:\n r.append([ref_tx.name2, ref_tx.name, tx.name, 'InFrameStop', i.chromosome, i.start, i.stop, i.strand])\n columns = ['GeneId', 'TranscriptId', 'AlignmentId', 'classifier', 'chromosome', 'start', 'stop', 'strand']\n df = pd.DataFrame(r, columns=columns)\n df = df.sort_values(columns)\n df = df.set_index(['GeneId', 'TranscriptId', 'AlignmentId', 'classifier'])\n assert len(r) == len(df)\n return df\n\n\n###\n# Metrics Classifiers\n###\n\n\ndef start_stop_stat(tx):\n \"\"\"\n Calculate the StartCodon, StopCodon metrics by looking at CdsStartStat/CdsEndStat and taking strand into account\n \"\"\"\n start_ok = True if tx.cds_start_stat == 'cmpl' else False\n stop_ok = True if tx.cds_end_stat == 'cmpl' else False\n if tx.strand == '-':\n start_ok, stop_ok = stop_ok, start_ok\n return start_ok, stop_ok\n\n\ndef calculate_percent_original_introns(ref_tx, tx, psl, aln_mode):\n \"\"\"\n Determines how many of the gaps present in a given transcript are within a wiggle distance of the parent.\n\n Algorithm:\n 1) Convert the coordinates of each block in the transcript to mRNA/CDS depending on the alignment.\n 2) Use the mRNA/CDS alignment to calculate a mapping between alignment positions and transcript positions.\n 3) Determine if each block gap coordinate is within fuzz_distance of a parental block gap.\n\n :param ref_tx: GenePredTranscript object representing the parent transcript\n :param tx: GenePredTranscript object representing the target transcript\n :param psl: PslRow object representing the mRNA/CDS alignment between ref_tx and tx\n :param aln_mode: One of ('CDS', 'mRNA'). Determines if we aligned CDS or mRNA.\n :return: float between 0 and 1 or nan (single exon transcript)\n \"\"\"\n # before we calculate anything, make sure we have introns to lose\n if len(ref_tx.intron_intervals) == 0:\n return float('nan')\n\n # generate a list of reference introns in current coordinates (mRNA or CDS)\n ref_introns = get_intron_coordinates(ref_tx, aln_mode)\n\n # generate a list of target introns in current coordinates (mRNA or CDS)\n # note that since this PSL is target-referenced, we use query_coordinate_to_target()\n tgt_introns = []\n for intron in get_intron_coordinates(tx, aln_mode):\n p = psl.query_coordinate_to_target(intron)\n if p is not None:\n tgt_introns.append(p)\n\n # if we lost all introns due to CDS filtering, return nan\n if len(tgt_introns) == 0:\n return float('nan')\n\n # count the number of introns within wiggle distance of each other\n num_original = 0\n for ref_intron in ref_introns:\n closest = tools.mathOps.find_closest(tgt_introns, ref_intron)\n if closest - fuzz_distance < ref_intron < closest + fuzz_distance:\n num_original += 1\n return tools.mathOps.format_ratio(num_original, len(ref_introns))\n\n\ndef calculate_percent_original_exons(ref_tx, psl, aln_mode):\n \"\"\"\n Calculates how many reference exons are missing in this transcript.\n\n This is determined by using coordinate translations from the reference exons to the target, determining how many\n of the target bases are covered through brute force\n\n :param ref_tx: GenePredTranscript object representing the parent transcript\n :param psl: PslRow object representing the mRNA/CDS alignment between ref_tx and tx\n :param aln_mode: One of ('CDS', 'mRNA'). Determines if we aligned CDS or mRNA.\n :return: float between 0 and 1\n \"\"\"\n # convert the reference exons to alignment coordinates.\n # We don't need the original exons because we can't produce useful coordinates here\n # which is why this is a metric and not an evaluation\n ref_exons = get_exon_intervals(ref_tx, aln_mode).values()\n # note that since this PSL is target-referenced, we use target_coordinate_to_query()\n num_original = 0\n for exon in ref_exons:\n present_bases = 0\n for i in xrange(exon.start, exon.stop):\n if psl.target_coordinate_to_query(i) is not None:\n present_bases += 1\n if tools.mathOps.format_ratio(present_bases, len(exon)) >= missing_exons_coverage_cutoff:\n num_original += 1\n return tools.mathOps.format_ratio(num_original, len(ref_exons))\n\n\n###\n# Alignment Evaluation Classifiers\n###\n\n\ndef in_frame_stop(tx, fasta):\n \"\"\"\n Finds the first in frame stop of this transcript, if there are any\n\n :param tx: Target GenePredTranscript object\n :param fasta: pyfasta Fasta object mapping the genome fasta for this analysis\n :return: A ChromosomeInterval object if an in frame stop was found otherwise None\n \"\"\"\n seq = tx.get_cds(fasta)\n for pos, codon in tools.bio.read_codons_with_position(seq):\n if tools.bio.translate_sequence(codon) == '*':\n start = tx.cds_coordinate_to_chromosome(pos)\n stop = tx.cds_coordinate_to_chromosome(pos + 3)\n if tx.strand == '-':\n start, stop = stop, start\n return tools.intervals.ChromosomeInterval(tx.chromosome, start, stop, tx.strand)\n return None\n\n\ndef find_indels(tx, psl, aln_mode):\n \"\"\"\n Walks the psl alignment looking for alignment gaps. Reports all such gaps in Chromosome Coordinates, marking\n the type of gap (CodingInsertion, CodingMult3Insertion, CodingDeletion, CodingMult3Deletion)\n\n Insertion/Deletion is relative to the target genome, for example:\n\n CodingInsertion:\n ref: ATGC--ATGC\n tgt: ATGCGGATGC\n\n CodingDeletion:\n ref: ATGCGGATGC\n tgt: ATGC--ATGC\n\n :param tx: GenePredTranscript object representing the target transcript\n :param psl: PslRow object describing CDS alignment between ref_tx and tx.\n :param aln_mode: One of ('CDS', 'mRNA'). Determines if we aligned CDS or mRNA.\n :return: paired list of [category, ChromosomeInterval] objects if a coding insertion exists else []\n \"\"\"\n def interval_is_coding(tx, i):\n \"\"\"returns True if the given ChromosomeInterval object is coding in this tx\"\"\"\n return i.start >= tx.thick_start and i.stop <= tx.thick_stop\n\n def convert_coordinates_to_chromosome(left_pos, right_pos, coordinate_fn, strand):\n \"\"\"convert alignment coordinates to target chromosome coordinates, inverting if negative strand\"\"\"\n left_chrom_pos = coordinate_fn(left_pos)\n assert left_chrom_pos is not None\n right_chrom_pos = coordinate_fn(right_pos)\n assert right_chrom_pos is not None\n if strand == '-':\n left_chrom_pos, right_chrom_pos = right_chrom_pos, left_chrom_pos\n assert right_chrom_pos >= left_chrom_pos\n return left_chrom_pos, right_chrom_pos\n\n def parse_indel(left_pos, right_pos, coordinate_fn, tx, offset, gap_type):\n \"\"\"Converts either an insertion or a deletion into a output interval\"\"\"\n left_chrom_pos, right_chrom_pos = convert_coordinates_to_chromosome(left_pos, right_pos, coordinate_fn,\n tx.strand)\n if left_chrom_pos is None or right_chrom_pos is None:\n assert aln_mode == 'CDS'\n return None\n i = tools.intervals.ChromosomeInterval(tx.chromosome, left_chrom_pos, right_chrom_pos, tx.strand)\n indel_type = find_indel_type(tx, i, offset)\n return [''.join([indel_type, gap_type]), i]\n\n def find_indel_type(tx, i, offset):\n \"\"\"Determines what type this indel is - coding/noncoding, mult3 or no\"\"\"\n if interval_is_coding(tx, i):\n this_type = 'CodingMult3' if offset % 3 == 0 else 'Coding'\n else:\n this_type = 'NonCoding'\n return this_type\n\n # depending on mode, we convert the coordinates from either CDS or mRNA\n # we also have a different position cutoff to make sure we are not evaluating terminal gaps\n if aln_mode == 'CDS':\n coordinate_fn = tx.cds_coordinate_to_chromosome\n else:\n coordinate_fn = tx.mrna_coordinate_to_chromosome\n\n # r holds the output\n r = []\n\n # remember where we were last iteration\n q_pos = 0\n t_pos = 0\n # iterate over block starts[i], q_starts[i + 1], t_starts[i + 1]\n for block_size, q_start, t_start in itertools.izip(*[psl.block_sizes, psl.q_starts[1:], psl.t_starts[1:]]):\n q_offset = q_start - block_size - q_pos\n t_offset = t_start - block_size - t_pos\n assert not (q_offset == t_offset == 0)\n assert (q_offset >= 0 and t_offset >= 0)\n if q_offset != 0: # query insertion -> insertion in target sequence\n left_pos = q_start - q_offset\n right_pos = q_start\n row = parse_indel(left_pos, right_pos, coordinate_fn, tx, q_offset, 'Insertion')\n if row is not None:\n r.append(row)\n if t_offset != 0: # target insertion -> insertion in reference sequence\n left_pos = right_pos = q_start\n row = parse_indel(left_pos, right_pos, coordinate_fn, tx, t_offset, 'Deletion')\n if row is not None:\n r.append(row)\n q_pos = q_start\n t_pos = t_start\n return r\n\n\n###\n# Helper functions\n###\n\n\ndef tx_iter(psl_iter, ref_tx_dict, tx_dict, tx_biotype_map):\n \"\"\"\n yields tuples of (GenePredTranscript , GenePredTranscript , PslRow, biotype\n \"\"\"\n for psl in psl_iter:\n # this psl is target-referenced\n ref_tx = ref_tx_dict[psl.t_name]\n tx = tx_dict[psl.q_name]\n biotype = tx_biotype_map[psl.t_name]\n yield ref_tx, tx, psl, biotype\n\n\ndef convert_cds_frames(ref_tx, tx, aln_mode):\n \"\"\"\n Wrapper for convert_cds_frame that converts the reference and target GenePredTranscript objects to CDS-frame\n Transcript objects only if the biotype is protein_coding and the transcripts are out of frame\n\n :param ref_tx: Reference GenePredTranscript object\n :param tx: Target GenePredTranscript object\n :param aln_mode: If we are in CDS mode, we need to convert the transcripts to a CDS-framed object.\n :return: tuple of GenePredTranscript objects (ref_tx, tx)\n \"\"\"\n if aln_mode == 'CDS':\n if ref_tx.offset != 0:\n ref_tx = convert_cds_frame(ref_tx)\n if tx.offset != 0:\n tx = convert_cds_frame(tx)\n return ref_tx, tx\n\n\ndef convert_cds_frame(tx):\n \"\"\"\n If this GenePredTranscript object is out of frame, return a new Transcript object representing just the CDS, in\n frame, trimmed to be a multiple of 3\n\n :param tx: GenePredTranscript object\n :return: Transcript object\n \"\"\"\n offset = tx.offset\n mod3 = (tx.cds_size - offset) % 3\n if tx.strand == '+':\n b = tx.get_bed(new_start=tx.thick_start + offset, new_stop=tx.thick_stop - mod3)\n else:\n b = tx.get_bed(new_start=tx.thick_start + mod3, new_stop=tx.thick_stop - offset)\n return tools.transcripts.Transcript(b)\n\n\ndef get_intron_coordinates(tx, aln_mode):\n \"\"\"\n Converts the block_starts coordinates to mRNA or CDS coordinates used in the alignment based on the alignment mode.\n\n :param tx:GenePredTranscript object\n :param aln_mode: One of ('CDS', 'mRNA'). Used to determine if we aligned in CDS space or mRNA space\n :return: list of integers\n \"\"\"\n if aln_mode == 'CDS':\n tx = convert_cds_frame(tx)\n introns = [tx.chromosome_coordinate_to_cds(tx.start + x) for x in tx.block_starts[1:]]\n else:\n introns = [tx.chromosome_coordinate_to_mrna(tx.start + x) for x in tx.block_starts[1:]]\n # remove None which means this transcript is protein_coding and that exon is entirely non-coding\n return [x for x in introns if x is not None]\n\n\ndef get_exon_intervals(tx, aln_mode):\n \"\"\"\n Generates a dict of intervals for this transcript in either mRNA coordinates or CDS coordinates depending on\n alignment mode.\n\n We maintain a mapping of where the exon came from to deal with CDS conversions and negative strands easily.\n\n :param tx: GenePredTranscript object\n :param aln_mode: One of ('CDS', 'mRNA'). Used to determine if we aligned in CDS space or mRNA space\n :return: dict of ChromosomeInterval objects {reference:converted}\n \"\"\"\n if aln_mode == 'CDS':\n tx = convert_cds_frame(tx)\n exons = {}\n for exon in tx.exon_intervals:\n start = tx.chromosome_coordinate_to_mrna(exon.start)\n stop = tx.chromosome_coordinate_to_mrna(exon.stop - 1) # zero based, half open\n if tx.strand == '-':\n start, stop = stop, start\n i = tools.intervals.ChromosomeInterval(None, start, stop + 1, '.')\n exons[exon] = i\n return exons\n","sub_path":"CAT/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":18529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"26173456","text":"#Lector Archivos v1\n#Autor Matias Cea\n\nimport csv\nlista=[]\nwith open('ciudades-paises.csv', 'r') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n lista.append([row[0], row[1]])\npais=[]\nwith open('Paises.csv', 'r') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n pais.append(row)\n\nlista.pop(0)\nlista_filtrada=[]\nid=1\nfor x in lista:\n lista1=[]\n for y in pais:\n if (x[1]) == (y[1]):\n lista1.append(id)\n lista1.append(x[0])\n lista1.append(y[0])\n id+=1\n \n lista_filtrada.append(lista1)\n \n#lista_filtrada=[]\n#\n#for x in lista:\n# variable = True\n# for y in lista_filtrada:\n# if (x[1], x[2])==(y[1], y[1]):\n# variable = False\n# \n# if variable:\n# lista_filtrada.append(x)\n#i=1\n#for x in lista_filtrada:\n# x.insert(0, i)\n# i+=1\n \n#def take(elem):\n# return int(elem[0])\n#lista_filtrada.sort(key=take)\n#print(lista_filtrada)\n\n#\n#--------------------- Escribir Archivo----------------------\nf = open('Ciudades.csv', 'a')\n\nwith f:\n writer = csv.writer(f)\n for row in lista_filtrada:\n writer.writerow(row)\n","sub_path":"Desktop/IIC2413-Grupo83-master/Datos/Filtro_Ciudad.py","file_name":"Filtro_Ciudad.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"306182095","text":"# -*- coding: utf-8 -*-\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nhttps://www.tensorflow.org/tutorials/\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\nimport tensorflow as tf\nmnist = tf.keras.datasets.mnist\n\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n])\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=5)\nmodel.evaluate(x_test, y_test)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nhttps://github.com/nlintz/TensorFlow-Tutorials/blob/master/07_lstm.py\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n#Inspired by https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/recurrent_network.py\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\n\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# configuration\n# O * W + b -> 10 labels for each image, O[? 28], W[28 10], B[10]\n# ^ (O: output 28 vec from 28 vec input)\n# |\n# +-+ +-+ +--+\n# |1|->|2|-> ... |28| time_step_size = 28\n# +-+ +-+ +--+\n# ^ ^ ... ^\n# | | |\n# img1:[28] [28] ... [28]\n# img2:[28] [28] ... [28]\n# img3:[28] [28] ... [28]\n# ...\n# img128 or img256 (batch_size or test_size 256)\n# each input size = input_vec_size=lstm_size=28\n\n# configuration variables\ninput_vec_size = lstm_size = 28\ntime_step_size = 28\n\nbatch_size = 128\ntest_size = 256\n\ndef init_weights(shape):\n return tf.Variable(tf.random_normal(shape, stddev=0.01))\n\n\ndef model(X, W, B, lstm_size):\n # X, input shape: (batch_size, time_step_size, input_vec_size)\n XT = tf.transpose(X, [1, 0, 2]) # permute time_step_size and batch_size\n # XT shape: (time_step_size, batch_size, input_vec_size)\n XR = tf.reshape(XT, [-1, lstm_size]) # each row has input for each lstm cell (lstm_size=input_vec_size)\n # XR shape: (time_step_size * batch_size, input_vec_size)\n X_split = tf.split(XR, time_step_size, 0) # split them to time_step_size (28 arrays)\n # Each array shape: (batch_size, input_vec_size)\n\n # Make lstm with lstm_size (each input vector size)\n lstm = rnn.BasicLSTMCell(lstm_size, forget_bias=1.0, state_is_tuple=True)\n\n # Get lstm cell output, time_step_size (28) arrays with lstm_size output: (batch_size, lstm_size)\n outputs, _states = rnn.static_rnn(lstm, X_split, dtype=tf.float32)\n\n # Linear activation\n # Get the last output\n return tf.matmul(outputs[-1], W) + B, lstm.state_size # State size to initialize the stat\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\ntrX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels\ntrX = trX.reshape(-1, 28, 28)\nteX = teX.reshape(-1, 28, 28)\n\nX = tf.placeholder(\"float\", [None, 28, 28])\nY = tf.placeholder(\"float\", [None, 10])\n\n# get lstm_size and output 10 labels\nW = init_weights([lstm_size, 10])\nB = init_weights([10])\n\npy_x, state_size = model(X, W, B, lstm_size)\n\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))\ntrain_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)\npredict_op = tf.argmax(py_x, 1)\n\nsession_conf = tf.ConfigProto()\nsession_conf.gpu_options.allow_growth = True\n\n# Launch the graph in a session\nwith tf.Session(config=session_conf) as sess:\n # you need to initialize all variables\n tf.global_variables_initializer().run()\n\n for i in range(100):\n for start, end in zip(range(0, len(trX), batch_size), range(batch_size, len(trX)+1, batch_size)):\n sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})\n\n test_indices = np.arange(len(teX)) # Get A Test Batch\n np.random.shuffle(test_indices)\n test_indices = test_indices[0:test_size]\n\n print(i, np.mean(np.argmax(teY[test_indices], axis=1) ==\nsess.run(predict_op, feed_dict={X: teX[test_indices]})))\n \n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nhttps://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/recurrent_network.py\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\"\"\" Recurrent Neural Network.\nA Recurrent Neural Network (LSTM) implementation example using TensorFlow library.\nThis example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)\nLinks:\n [Long Short Term Memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf)\n [MNIST Dataset](http://yann.lecun.com/exdb/mnist/).\nAuthor: Aymeric Damien\nProject: https://github.com/aymericdamien/TensorFlow-Examples/\n\"\"\"\n\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\n\n# Import MNIST data\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\n'''\nTo classify images using a recurrent neural network, we consider every image\nrow as a sequence of pixels. Because MNIST image shape is 28*28px, we will then\nhandle 28 sequences of 28 steps for every sample.\n'''\n\n# Training Parameters\nlearning_rate = 0.001\ntraining_steps = 10000\nbatch_size = 128\ndisplay_step = 200\n\n# Network Parameters\nnum_input = 28 # MNIST data input (img shape: 28*28)\ntimesteps = 28 # timesteps\nnum_hidden = 128 # hidden layer num of features\nnum_classes = 10 # MNIST total classes (0-9 digits)\n\n# tf Graph input\nX = tf.placeholder(\"float\", [None, timesteps, num_input])\nY = tf.placeholder(\"float\", [None, num_classes])\n\n# Define weights\nweights = {\n 'out': tf.Variable(tf.random_normal([num_hidden, num_classes]))\n}\nbiases = {\n 'out': tf.Variable(tf.random_normal([num_classes]))\n}\n\n\ndef RNN(x, weights, biases):\n\n # Prepare data shape to match `rnn` function requirements\n # Current data input shape: (batch_size, timesteps, n_input)\n # Required shape: 'timesteps' tensors list of shape (batch_size, n_input)\n\n # Unstack to get a list of 'timesteps' tensors of shape (batch_size, n_input)\n x = tf.unstack(x, timesteps, 1)\n\n # Define a lstm cell with tensorflow\n lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)\n\n # Get lstm cell output\n outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)\n\n # Linear activation, using rnn inner loop last output\n return tf.matmul(outputs[-1], weights['out']) + biases['out']\n\nlogits = RNN(X, weights, biases)\nprediction = tf.nn.softmax(logits)\n\n# Define loss and optimizer\nloss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=Y))\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\ntrain_op = optimizer.minimize(loss_op)\n\n# Evaluate model (with test logits, for dropout to be disabled)\ncorrect_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n# Initialize the variables (i.e. assign their default value)\ninit = tf.global_variables_initializer()\n\n# Start training\nwith tf.Session() as sess:\n\n # Run the initializer\n sess.run(init)\n\n for step in range(1, training_steps+1):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n # Reshape data to get 28 seq of 28 elements\n batch_x = batch_x.reshape((batch_size, timesteps, num_input))\n # Run optimization op (backprop)\n sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})\n if step % display_step == 0 or step == 1:\n # Calculate batch loss and accuracy\n loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,\n Y: batch_y})\n print(\"Step \" + str(step) + \", Minibatch Loss= \" + \\\n \"{:.4f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.3f}\".format(acc))\n\n print(\"Optimization Finished!\")\n\n # Calculate accuracy for 128 mnist test images\n test_len = 128\n test_data = mnist.test.images[:test_len].reshape((-1, timesteps, num_input))\n test_label = mnist.test.labels[:test_len]\n print(\"Testing Accuracy:\", \\\n sess.run(accuracy, feed_dict={X: test_data, Y: test_label}))\n","sub_path":"RNN_HandWrittenRecognition.py","file_name":"RNN_HandWrittenRecognition.py","file_ext":"py","file_size_in_byte":8688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"233499092","text":"import boto3\nimport json\n\ncloudtrail = boto3.client('cloudtrail')\n\nresponse = cloudtrail.lookup_events(\n LookupAttributes=[\n {\n 'AttributeKey': 'EventName',\n 'AttributeValue': 'AuthorizeSecurityGroupIngress'\n }\n ]\n)\n\nprint('----------Inbound Rules----------')\nfor event in response['Events']:\n result = json.loads(event['CloudTrailEvent'])\n print(\"CloudTrail Event ID :\",result['eventID'])\n print('Event Time(UTC) :',result['eventTime'])\n print(\"User ARN :\",result['userIdentity']['arn'])\n print('AWS Region :',result['awsRegion'],'/','Request Source IP :',result['sourceIPAddress'])\n print('SecurityGroup :',result['requestParameters']['groupId'],'/',boto3.resource('ec2').SecurityGroup(result['requestParameters']['groupId']).group_name)\n for rules in result['requestParameters']['ipPermissions']['items']:\n if rules['ipProtocol'] == '-1':\n print(\"From All IP, All Port, All Protocol\") \n else:\n print(\"From IP {:18s} To Port {}-{}/{}\".format(rules['ipRanges']['items'][0]['cidrIp'],rules['fromPort'],rules['toPort'],rules['ipProtocol'])) \n print('-------------------------')\n","sub_path":"AuthorizeSecurityGroupIngress.py","file_name":"AuthorizeSecurityGroupIngress.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"568566529","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('profile/', views.profileview, name='profiles'),\n path('rider/', views.riderprofile, name='riderprofile'),\n path('riderUpdate/', views.riderUpdateForm, name='riderUpdate'),\n path('customer/', views.customerProfile, name='customerprofile'),\n path('customerUpdate', views.customerProfileUpdate, name='customerupdate'),\n path('staff/', views.staffProfile, name='staffprofile'),\n path('staff/', views.staffUpdateForm, name='staffupdate'),\n]\n","sub_path":"profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"503920663","text":"#!/usr/bin/python\n\n## @file\n# Contains class View.\n\n# import avango-guacamole libraries\nimport avango\nimport avango.gua\nimport avango.script\nimport avango.oculus\nfrom avango.script import field_has_changed\n\n# import framework libraries\nfrom ClientTrackingReader import *\nfrom ClientPortal import *\nfrom ConsoleIO import *\n\n# import python libraries\nimport time\n\n\n## Internal representation of a standard view on client side.\n# Creates the viewing setup needed for one individual workspace-displaygroup-screen-user view.\nclass View(avango.script.Script):\n\n ## @var sf_pipeline_string\n # String field containing the concatenated pipeline values.\n sf_pipeline_string = avango.SFString()\n\n ## Default constructor.\n def __init__(self):\n self.super(View).__init__()\n\n ## @var portal_pre_views\n # A list of all PortalPreView instances for this view.\n self.portal_pre_views = []\n\n ## Custom constructor.\n # @param SCENEGRAPH Reference to the scenegraph to be displayed.\n # @param VIEWER Reference to the viewer to which the created pipeline will be appended to.\n # @param DISPLAY_INSTANCE An instance of Display to represent the values.\n # @param WORKSPACE_ID ID of the workspace to deal with.\n # @param DISPLAY_GROUP_ID ID of the display group to deal with.\n # @param SCREEN_ID ID of the screen to deal with.\n # @param USER_ID ID of the user to deal with.\n def my_constructor(self, SCENEGRAPH, VIEWER, DISPLAY_INSTANCE, WORKSPACE_ID, DISPLAY_GROUP_ID, SCREEN_ID, USER_ID):\n\n ## @var SCENEGRAPH\n # Reference to the scenegraph.\n self.SCENEGRAPH = SCENEGRAPH\n\n ## @var is_stereo\n # Boolean indicating if the view to be constructed is stereo or mono.\n self.is_stereo = DISPLAY_INSTANCE.stereo\n\n ## @var workspace_id\n # ID of the workspace to deal with.\n self.workspace_id = WORKSPACE_ID\n\n ## @var display_group_id\n # ID of the display group to deal with.\n self.display_group_id = DISPLAY_GROUP_ID\n\n ## @var screen_id\n # ID of the screen to deal with.\n self.screen_id = SCREEN_ID\n\n ## @var user_id\n # ID of the user to deal with.\n self.user_id = USER_ID\n\n # retrieve the needed values from display\n ## @var display_values\n # Values that are retrieved from the display. Vary for each view on this display.\n self.display_values = DISPLAY_INSTANCE.register_view()\n\n ## @var display_render_mask\n # Additional render mask contraints given by the display.\n self.display_render_mask = DISPLAY_INSTANCE.render_mask\n\n # check if no more users allowed at this screen\n if not self.display_values:\n # TODO better handling of this case?\n print_error('Error: no more users allowed at display \"' + DISPLAY_INSTANCE.name + '\"!', False)\n return\n\n ## @var window_size\n # Size of the window in which this View will be rendered.\n self.window_size = avango.gua.Vec2ui(DISPLAY_INSTANCE.resolution[0], DISPLAY_INSTANCE.resolution[1]) \n\n # create camera\n ## @var camera\n # The camera from which this View will be rendered.\n self.camera = avango.gua.nodes.Camera()\n self.camera.SceneGraph.value = SCENEGRAPH.Name.value\n self.camera.Mode.value = DISPLAY_INSTANCE.cameramode\n\n # set render mask for camera\n _render_mask = \"(main_scene | w\" + str(WORKSPACE_ID) + \"_dg\" + str(DISPLAY_GROUP_ID) + \"_u\" + str(USER_ID) + \") && !do_not_display_group && !portal_invisible_group\"\n self.camera.RenderMask.value = _render_mask\n #print repr(self.camera.RenderMask.value)\n\n # create pipeline\n ## @var pipeline\n # The pipeline used to render this View.\n self.pipeline = avango.gua.nodes.Pipeline()\n self.pipeline.Enabled.value = True\n\n '''\n Standard View\n '''\n\n self.camera.LeftScreen.value = \"/net/w\" + str(self.workspace_id) + \"_dg\" + str(self.display_group_id) + \"_u\" + str(self.user_id) + \"/screen_\" + str(self.screen_id)\n self.camera.RightScreen.value = \"/net/w\" + str(self.workspace_id) + \"_dg\" + str(self.display_group_id) + \"_u\" + str(self.user_id) + \"/screen_\" + str(self.screen_id)\n self.camera.LeftEye.value = \"/net/w\" + str(self.workspace_id) + \"_dg\" + str(self.display_group_id) + \"_u\" + str(self.user_id) + \"/head/eyeL\"\n self.camera.RightEye.value = \"/net/w\" + str(self.workspace_id) + \"_dg\" + str(self.display_group_id) + \"_u\" + str(self.user_id) + \"/head/eyeR\"\n\n # create window\n ## @var window\n # The window in which this View will be rendered to.\n self.window = avango.gua.nodes.Window()\n self.window.Display.value = self.display_values[0] # GPU-ID\n self.window.Title.value = \"Display: \" + str(DISPLAY_INSTANCE.name) + \"; User: \" + str(self.user_id)\n self.window.LeftResolution.value = self.window_size\n self.window.RightResolution.value = self.window_size\n\n if DISPLAY_INSTANCE.stereomode == \"SIDE_BY_SIDE\":\n self.window.Size.value = avango.gua.Vec2ui(self.window_size.x * 2, self.window_size.y)\n self.window.LeftPosition.value = avango.gua.Vec2ui(0, 0)\n self.window.RightPosition.value = avango.gua.Vec2ui(self.window_size.x, 0)\n self.window.StereoMode.value = avango.gua.StereoMode.SIDE_BY_SIDE\n \n elif DISPLAY_INSTANCE.stereomode == \"ANAGLYPH_RED_CYAN\" or DISPLAY_INSTANCE.stereomode == \"CHECKERBOARD\":\n self.window.Size.value = self.window_size\n self.window.LeftPosition.value = avango.gua.Vec2ui(0, 0)\n self.window.RightPosition.value = avango.gua.Vec2ui(0, 0)\n \n if DISPLAY_INSTANCE.stereomode == \"ANAGLYPH_RED_CYAN\":\n self.window.StereoMode.value = avango.gua.StereoMode.ANAGLYPH_RED_CYAN\n\n elif DISPLAY_INSTANCE.stereomode == \"CHECKERBOARD\":\n self.window.StereoMode.value = avango.gua.StereoMode.CHECKERBOARD\n\n self.pipeline.LeftResolution.value = self.window.LeftResolution.value\n self.pipeline.RightResolution.value = self.window.RightResolution.value\n\n if self.is_stereo:\n self.pipeline.EnableStereo.value = True\n else:\n self.pipeline.EnableStereo.value = False\n\n self.pipeline.Window.value = self.window\n self.pipeline.Camera.value = self.camera\n self.pipeline.EnableFPSDisplay.value = True\n\n '''\n General user settings\n '''\n\n # set display string and warpmatrices as given by the display\n if len(self.display_values) > 1:\n self.set_warpmatrices(self.window, self.display_values[1])\n\n # append pipeline to the viewer\n VIEWER.Pipelines.value.append(self.pipeline)\n\n ## @var frame_trigger\n # Triggers framewise evaluation of frame_callback method.\n self.frame_trigger = avango.script.nodes.Update(Callback = self.frame_callback, Active = True)\n \n\n ## Sets the warp matrices if there is a correct amount of them.\n # @param WINDOW The window instance to apply the warp matrices to.\n # @param WARPMATRICES A list of warp matrices to be applied if there are enough of them.\n def set_warpmatrices(self, WINDOW, WARPMATRICES):\n \n if len(WARPMATRICES) == 6:\n WINDOW.WarpMatrixRedRight.value = WARPMATRICES[0]\n WINDOW.WarpMatrixGreenRight.value = WARPMATRICES[1]\n WINDOW.WarpMatrixBlueRight.value = WARPMATRICES[2]\n \n WINDOW.WarpMatrixRedLeft.value = WARPMATRICES[3]\n WINDOW.WarpMatrixGreenLeft.value = WARPMATRICES[4]\n WINDOW.WarpMatrixBlueLeft.value = WARPMATRICES[5]\n\n ## Creates a PortalPreView instance for the portal copied at LOCAL_PORTAL_NODE.\n # @param SERVER_PORTAL_NODE Server portal grouping node.\n def create_portal_preview(self, SERVER_PORTAL_NODE):\n _pre_view = PortalPreView()\n _pre_view.my_constructor(SERVER_PORTAL_NODE, self)\n self.portal_pre_views.append(_pre_view)\n\n ## Removes the PortalPreView instance of LOCAL_PORTAL_NODE.\n # @param LOCAL_PORTAL_NODE The client portal node to remove the PreView for.\n def remove_portal_preview(self, LOCAL_PORTAL_NODE):\n\n _pre_views_to_remove = []\n\n for _pre_view in self.portal_pre_views:\n if _pre_view.compare_portal_node(LOCAL_PORTAL_NODE) == True:\n _pre_views_to_remove.append(_pre_view)\n \n for _pre_view in _pre_views_to_remove:\n print(\"Remove a pre view\")\n _pre_view.delete()\n self.portal_pre_views.remove(_pre_view)\n del _pre_view\n print(\"New list of pre views\", self.portal_pre_views)\n\n ## Called whenever sf_pipeline_string changes.\n @field_has_changed(sf_pipeline_string)\n def sf_pipeline_string_changed(self):\n \n _splitted_string = self.sf_pipeline_string.value.split(\"#\")\n\n print_message(\"w\" + str(self.workspace_id) + \"_dg\" + str(self.display_group_id) + \"_u\" + str(self.user_id) + \": Set pipeline values to \" + str(_splitted_string))\n\n # Note: Calling avango.gua.create_texture during runtime causes the application\n # to crash. All textures have to be preloaded, for example in ClientPipelineValues.py\n # avango.gua.create_texture(_splitted_string[0])\n \n if self.display_render_mask == \"!main_scene\":\n self.pipeline.BackgroundMode.value = avango.gua.BackgroundMode.COLOR\n self.pipeline.BackgroundColor.value = avango.gua.Color(0.2, 0.45, 0.6)\n else:\n self.pipeline.BackgroundMode.value = avango.gua.BackgroundMode.SKYMAP_TEXTURE\n self.pipeline.BackgroundTexture.value = _splitted_string[0]\n self.pipeline.FogTexture.value = _splitted_string[0]\n\n if _splitted_string[1] == \"True\":\n self.pipeline.EnableBloom.value = True\n else:\n self.pipeline.EnableBloom.value = False\n\n self.pipeline.BloomIntensity.value = float(_splitted_string[2])\n self.pipeline.BloomThreshold.value = float(_splitted_string[3])\n self.pipeline.BloomRadius.value = float(_splitted_string[4])\n\n if _splitted_string[5] == \"True\":\n self.pipeline.EnableSsao.value = True\n else:\n self.pipeline.EnableSsao.value = False\n\n self.pipeline.SsaoRadius.value = float(_splitted_string[6])\n self.pipeline.SsaoIntensity.value = float(_splitted_string[7])\n\n if _splitted_string[8] == \"True\":\n self.pipeline.EnableBackfaceCulling.value = True\n else:\n self.pipeline.EnableBackfaceCulling.value = False\n\n if _splitted_string[9] == \"True\":\n self.pipeline.EnableFrustumCulling.value = True\n else:\n self.pipeline.EnableFrustumCulling.value = False\n\n if _splitted_string[10] == \"True\":\n self.pipeline.EnableFXAA.value = True\n else:\n self.pipeline.EnableFXAA.value = False\n\n _ambient_color_values = _splitted_string[11].split(\",\")\n _ambient_color = avango.gua.Color(float(_ambient_color_values[0]), float(_ambient_color_values[1]), float(_ambient_color_values[2]))\n self.pipeline.AmbientColor.value = _ambient_color\n\n if _splitted_string[12] == \"True\":\n self.pipeline.EnableFog.value = True\n else:\n self.pipeline.EnableFog.value = False\n\n self.pipeline.FogStart.value = float(_splitted_string[13])\n self.pipeline.FogEnd.value = float(_splitted_string[14])\n self.pipeline.NearClip.value = float(_splitted_string[15])\n self.pipeline.FarClip.value = float(_splitted_string[16])\n \n #avango.gua.reload_materials()\n \n ## Evaluated every frame until connection is setup.\n def frame_callback(self):\n\n try:\n _pipeline_info_node = self.SCENEGRAPH[\"/net/pipeline_values\"].Children.value[0]\n except:\n return\n\n # connect sf_pipeline_string with Name field of info node once\n if _pipeline_info_node != None and self.sf_pipeline_string.value == \"\":\n self.sf_pipeline_string.connect_from(_pipeline_info_node.Name)\n self.frame_trigger.Active.value = False\n","sub_path":"lib-client/View.py","file_name":"View.py","file_ext":"py","file_size_in_byte":11448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"152621299","text":"from __future__ import print_function\r\nimport argparse\r\nfrom math import log10\r\n\r\nimport os\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport matplotlib.pyplot as plt\r\nfrom torch.utils.data.dataloader import DataLoader\r\nfrom model import Net\r\nfrom torch.autograd import Variable\r\nfrom dataset import get_training_set , get_test_set\r\n\r\ntorch.cuda.set_device(0) # use the chosen gpu\r\n\r\ndef adjust_learning_rate(optimizer, epoch):\r\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 20 epochs\"\"\"\r\n lr = opt.lr * (0.1 ** (epoch // opt.step))\r\n for param_group in optimizer.param_groups:\r\n param_group[\"lr\"] = lr\r\n\r\ndef train(epoch):\r\n\r\n adjust_learning_rate(optimizer, epoch-1)\r\n\r\n print(\"Epoch = {}, lr = {}\".format(epoch, optimizer.param_groups[0][\"lr\"]))\r\n\r\n #model.train()\r\n\r\n epoch_loss = 0\r\n for iteration, batch in enumerate(training_data_loader, 1):\r\n input, target = Variable(batch[0]), Variable(batch[1], requires_grad=False)\r\n\r\n if opt.cuda:\r\n input = input.cuda()\r\n target = target.cuda()\r\n\r\n loss = criterion(model(input), target)\r\n epoch_loss += loss.item()\r\n optimizer.zero_grad()\r\n loss.backward()\r\n nn.utils.clip_grad_norm_(model.parameters(),opt.clip)\r\n optimizer.step()\r\n\r\n #print(\"===> Epoch({}/{}): Loss: {:.4f}\".format(epoch, len(training_data_loader), loss.item()))\r\n epoch_loss = epoch_loss / len(training_data_loader)\r\n #Loss_list.append(epoch_loss)\r\n print(\"===> Epoch {} Complete: Avg. Loss: {:.10f}\".format(epoch, epoch_loss))\r\n\r\n\r\ndef test():\r\n avg_psnr = 0\r\n with torch.no_grad():\r\n for batch in testing_data_loader:\r\n inputs, targets = batch[0].to(device), batch[1].to(device)\r\n\r\n mse = criterion(model(inputs), targets)\r\n calc_psnr = 10 * log10(1 / mse.item())\r\n avg_psnr += calc_psnr\r\n\r\n avg_psnr = avg_psnr /len(testing_data_loader)\r\n #Psnr_list.append(avg_psnr)\r\n print(\"===> Avg. PSNR: {:.10f} dB\".format(avg_psnr))\r\n\r\ndef checkpoint(epoch):\r\n model_out_path = \"checkpoint/\" + \"model_epoch_{}.pth\".format(epoch)\r\n if not os.path.exists(\"checkpoint/\"):\r\n os.makedirs(\"checkpoint/\")\r\n torch.save(model, model_out_path)\r\n print(\"Checkpoint saved to {}\".format(model_out_path))\r\n\r\n\r\n# Training settings\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='PyTorch Super Res Example')\r\n parser.add_argument('--upscale_factor', type=int, default=1, help=\"super resolution upscale factor\")\r\n parser.add_argument('--batchSize', type=int, default=1, help='training batch size')\r\n parser.add_argument('--testBatchSize', type=int, default=1, help='testing batch size')\r\n parser.add_argument('--num_epochs', type=int, default=80, help='number of epochs to train for')\r\n parser.add_argument('--lr', type=float, default=0.001, help='Learning Rate. Default=0.01')\r\n parser.add_argument(\"--momentum\", default=0.9, type=float, help=\"Momentum, Default: 0.9\")\r\n parser.add_argument(\"--weight-decay\", \"--wd\", default=1e-4, type=float, help=\"Weight decay, Default: 1e-4\")\r\n parser.add_argument(\"--clip\", type=float, default=0.4, help=\"Clipping Gradients. Default=0.4\")\r\n parser.add_argument(\"--step\", type=int, default=10)\r\n parser.add_argument('--cuda', default=True, help='use cuda?')\r\n parser.add_argument('--threads', type=int, default=1, help='number of threads for data loader to use')\r\n parser.add_argument('--seed', type=int, default=123, help='random seed to use. Default=123')\r\n opt = parser.parse_args()\r\n print(opt)\r\n\r\n if opt.cuda and not torch.cuda.is_available():\r\n raise Exception(\"No GPU found, please run without --cuda\")\r\n\r\n torch.manual_seed(opt.seed)\r\n device = torch.device(\"cuda\" if opt.cuda else \"cpu\")\r\n\r\n print('===> Loading datasets')\r\n train_set = get_training_set()\r\n test_set = get_test_set()\r\n training_data_loader = DataLoader(dataset=train_set,\r\n batch_size=opt.batchSize,\r\n shuffle=True)\r\n testing_data_loader = DataLoader(dataset=test_set,\r\n batch_size=opt.testBatchSize)\r\n\r\n #Loss_list=[]\r\n #Psnr_list=[]\r\n\r\n print('===> Building model')\r\n model = Net().to(device)\r\n criterion = nn.MSELoss()\r\n\r\n # optimizer = optim.SGD( params=model.parameters(), lr=opt.lr, momentum=opt.momentum, weight_decay=opt.weight_decay)\r\n optimizer = optim.Adam(params=model.parameters(), lr=opt.lr)\r\n\r\n for epoch in range(1, opt.num_epochs+1):\r\n train(epoch)\r\n test()\r\n checkpoint(epoch)\r\n\r\n\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"518839663","text":"import gym\nfrom policy_gradient import PolicyGradient\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nenv = gym.make('CartPole-v0')\nenv = env.unwrapped\n\n# Policy gradient has high variance, seed for reproducability\nenv.seed(1)\n\nprint(\"env.action_space\", env.action_space)\nprint(\"env.observation_space\", env.observation_space)\nprint(\"env.observation_space.high\", env.observation_space.high)\nprint(\"env.observation_space.low\", env.observation_space.low)\n\n\nRENDER_ENV = False\nEPISODES = 500\nrewards = []\nRENDER_REWARD_MIN = 50\n\nif __name__ == \"__main__\":\n\n\n # Load checkpoint\n load_path = None #\"output/weights/CartPole-v0.ckpt\"\n save_path = None #\"output/weights/CartPole-v0-temp.ckpt\"\n\n PG = PolicyGradient(\n n_x = env.observation_space.shape[0],\n n_y = env.action_space.n,\n learning_rate=0.01,\n reward_decay=0.95,\n load_path=load_path,\n save_path=save_path\n )\n\n\n for episode in range(EPISODES):\n\n observation = env.reset()\n episode_reward = 0\n\n while True:\n if RENDER_ENV: env.render()\n\n # 1. Choose an action based on observation\n action = PG.choose_action(observation)\n\n # 2. Take action in the environment\n observation_, reward, done, info = env.step(action)\n\n # 3. Store transition for training\n PG.store_transition(observation, action, reward)\n\n if done:\n episode_rewards_sum = sum(PG.episode_rewards)\n rewards.append(episode_rewards_sum)\n max_reward_so_far = np.amax(rewards)\n\n print(\"==========================================\")\n print(\"Episode: \", episode)\n print(\"Reward: \", episode_rewards_sum)\n print(\"Max reward so far: \", max_reward_so_far)\n\n # 4. Train neural network\n discounted_episode_rewards_norm = PG.learn()\n\n # Render env if we get to rewards minimum\n if max_reward_so_far > RENDER_REWARD_MIN: RENDER_ENV = True\n\n\n break\n\n # Save new observation\n observation = observation_\n","sub_path":"RL-Using-Tensorflow/Policy Gradient/run_cartpole.py","file_name":"run_cartpole.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"419862502","text":"from django.urls import path \nfrom . import views\nurlpatterns = [\n path('', views.main_page),\n path('shows', views.all_shows),\n path('shows/', views.show_this_show),\n path('shows//edit', views.edit),\n path('delete/', views.delete),\n path('shows/new', views.add_new)\n ]\n","sub_path":"Django_projects/shows_tv/firstapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"22556336","text":"from keras.models import load_model\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn import preprocessing\n\nimport numpy as np\nimport pickle\n\nMAX_SEQUENCE_LENGTH = 100\n\n\nclass IntentClassifier():\n\n def __init__(self, model_path, tokenizer_path, encoder_path):\n print('>> initializing label encoder')\n self.encoder = preprocessing.LabelEncoder()\n print('>> loading saved classes')\n self.encoder.classes_ = np.load(encoder_path)\n\n print('>> loading keras tokenizer')\n with open(tokenizer_path, 'rb') as handle:\n self.tokenizer = pickle.load(handle)\n\n self.model = load_model(model_path)\n\n def prediction(self, statement):\n user_text = [statement]\n user_seq = self.tokenizer.texts_to_sequences(user_text)\n user_input = pad_sequences(user_seq, maxlen=MAX_SEQUENCE_LENGTH)\n user_predict_prob = self.model.predict(user_input)\n user_predict = user_predict_prob.argmax(axis=-1)\n user_intent_predict = self.encoder.inverse_transform(user_predict)\n return user_intent_predict\n","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"336716800","text":"class Solution(object):\n @staticmethod\n def counting_valleys(steps, seq):\n valleys, level = 0, 0\n for direction in seq:\n level += 1 if direction == 'U' else -1\n if level == 0 and direction == 'U':\n valleys += 1\n\n return valleys\n\n\nimport unittest\n\nclass SolutionTest(unittest.TestCase):\n def test_counting_valleys(self):\n self.assertEqual(1, Solution.counting_valleys(8, 'UDDDUDUU'))\n self.assertEqual(0, Solution.counting_valleys(6, 'UUUDDD'))\n self.assertEqual(2, Solution.counting_valleys(12, 'DDUUUUDDDDUU'))\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Algorithms/counting_valleys.py","file_name":"counting_valleys.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"644605362","text":"import socket,threading,time,sys\n\ncoding='utf-8'\n\ndef main():\n addr,port='127.0.0.1',2146\n\n addr,port = askAddr(addr,port)\n print('Connecting',addr,'on port',port)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setblocking(1)\n try:\n s.connect((addr,port))\n except Exception as e:\n print('Failed:',e)\n input()\n \n print('======[Connected]======')\n t = threading.Thread(target=recv,args=(s,))\n t.start()\n \n send(s)\n\ndef askAddr(addr='127.0.0.1', port=2146):\n \n inp = input('Set Address (default %s):' % addr)\n if inp!='':\n addr=inp\n inp = input('Set Port (default %d):' % port)\n if inp!='':\n port=int(inp)\n return addr,port\n\ndef recv(s):\n while True:\n data=s.recv(1024)\n if data:\n sys.stdout.write(str(data,'utf-8'))\n sys.stdout.flush()\n else:\n print('=====[Disconnected]=====')\n break\n\n\ndef send(s):\n while True:\n t=input()\n s.send(bytes(t+'\\n','utf-8'))\n\n\ndef decode(data):\n return str(data, coding)\n\ndef encode(text):\n return bytes(text, coding)\n\n\nmain()\n","sub_path":"SimpleClient.py","file_name":"SimpleClient.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"516583166","text":"\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 23 20:11:39 2018\r\n\r\n@author: XY\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport random as ra\r\nimport networkx as nx\r\n\r\ndef read_network(file_path):\r\n with open(file_path) as f:\r\n net = nx.read_adjlist(file_path, create_using=nx.Graph())\r\n return net\r\n\r\ndef build_reward_mat(net, seed):\r\n reward_mat = np.array([[-1 for i in range(net.number_of_nodes())] for j in range(net.number_of_nodes())])\r\n for i in net.edges():\r\n reward_mat[i[0]][i[1]] = 0\r\n reward_mat[i[1]][i[0]] = 0\r\n# =============================================================================\r\n# for i in net.nodes():\r\n# reward_mat[i][i] = 0\r\n# if i in seed:\r\n# reward_mat[i][i] = 100\r\n# =============================================================================\r\n for i in seed:\r\n for j in net.neighbors(i):\r\n reward_mat[j][i] = 100\r\n return reward_mat\r\n\r\ndef learn_Q(gamma,net,reward_mat,seed):\r\n q_mat = np.array([[0 for i in range(net.number_of_nodes())] for j in range(net.number_of_nodes())])\r\n i = 0\r\n while True:\r\n state = ra.sample(net.nodes(),1)[0]\r\n seedtarget = seed\r\n while True:\r\n choice = list(net.neighbors(state))\r\n #choice.append(state)\r\n next_state = ra.sample(choice,1)[0]\r\n qval = reward_mat[state,next_state] + gamma * max(q_mat[next_state])\r\n q_mat[state, next_state] = qval\r\n state = next_state\r\n if state in seedtarget:\r\n break\r\n \r\n i += 1\r\n if i == 1000:\r\n break\r\n \r\n return q_mat\r\n\r\n# =============================================================================\r\n# def rank(net,q_mat,seed):\r\n# path = []\r\n# profit_set = []\r\n# rankprofit = []\r\n# for i in net.nodes():\r\n# state = i\r\n# action = i\r\n# ipath = [state]\r\n# profit = []\r\n# while True:\r\n# neighbors = list(net.neighbors(state))\r\n# remain_list = list(set(neighbors) - set(ipath))\r\n# q_max = 0\r\n# if len(ipath) == 6 or len(remain_list) == 0:\r\n# path.append(ipath)\r\n# profit_set.append(profit)\r\n# break\r\n# #从剩余的节点中选择最大跳转\r\n# for j in remain_list:\r\n# if q_mat[state,j] >= q_max:\r\n# action = j\r\n# q_max = q_mat[state,j]\r\n# ipath.append(action)\r\n# profit.append(q_max)\r\n# #if action in seed or len(ipath)==6:\r\n# #print(state,action)\r\n# state = action\r\n# \r\n# for i in path:\r\n# times = 0\r\n# length = len(i)\r\n# profit = 0\r\n# for j in i[1:]:\r\n# # =============================================================================\r\n# # if j in seed:\r\n# # sumcount += 1\r\n# # profit += (length - times)\r\n# # =============================================================================\r\n# profit = profit + (length - times) * profit_set[i[0]][times]\r\n# times += 1 \r\n# print(i,profit)\r\n# rankprofit.append((i[0],profit))\r\n# result = sorted(rankprofit, key = lambda i:i[1], reverse = True)\r\n# candicate = []\r\n# count = 0\r\n# print(result)\r\n# for i in result:\r\n# if i[0] not in seed:\r\n# candicate.append(i[0])\r\n# count += 1\r\n# if count == 16:\r\n# break\r\n# return(candicate)\r\n# ===============================================================================\r\n\r\ndef rank(q_mat,net,seed):\r\n record = []\r\n candicate = []\r\n count = 0\r\n for i,num in enumerate(q_mat):\r\n value = float(np.sum(num)/len(list(net.neighbors(i))))\r\n record.append((i,value))\r\n result = sorted(record, key = lambda i :i[1], reverse = True)\r\n for i in result:\r\n if i[0] not in seed:\r\n candicate.append(i[0])\r\n count += 1\r\n if count == 14:\r\n break\r\n return(candicate)\r\n \r\ndef recall(com,candicate):\r\n com = set(com)\r\n candicate = set(candicate)\r\n cross = com & candicate\r\n #print(cross)\r\n recall = float(len(cross)) / (len(com)-2)\r\n return(recall) \r\n \r\n \r\nif __name__ == '__main__':\r\n net = nx.karate_club_graph()\r\n #com = list(map(int,['8', '9', '14', '15', '18', '20', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32','33']))\r\n com = list(map(int,['0','1','2','3','4','5','6','7','10','11','12','13','16','17','19','21']))\r\n gam_range = [float(i)/100 for i in range(0,105,5)]\r\n record_gam = {}\r\n for gamma in gam_range:\r\n recall_list = []\r\n for i in range(100): \r\n seed = ra.sample(com,2)\r\n #seed = [22,32]\r\n #print(seed)\r\n reward_mat = build_reward_mat(net, seed)\r\n #print(reward_mat)\r\n q_mat = learn_Q(gamma, net, reward_mat,seed)\r\n #print(q_mat.shape)\r\n # =============================================================================\r\n # for i,num in enumerate(q_mat):\r\n # #print(num)\r\n # print(i,num,float(np.sum(num)/len(list(net.neighbors(i)))))\r\n # =============================================================================\r\n candicate = rank(q_mat,net,seed)\r\n recall_list.append(recall(com, candicate))\r\n #print(recall_list,np.mean(recall_list))\r\n record_gam[gamma] = np.mean(recall_list)\r\n print('finish{0} experiment,recall is {1}'.format(gamma,np.mean(recall_list)))\r\n print(record_gam) \r\n for i in record_gam.keys():\r\n print(i,record_gam[i])\r\n ","sub_path":"Qlearn-base.py","file_name":"Qlearn-base.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"595651573","text":"#!/usr/bin/python\n# coding=utf-8\n\nfrom src.lib.phone_control import PhoneControl\nfrom src.lib.logger import Logger\nimport src.lib.utils as utils\nimport os\nfrom src.lib.calculator import Calculator\n\n\ndef run(a, op, b, filename=\"log_calculator.txt\"):\n # path to save logs\n cwd_path = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(cwd_path, \"..\", \"..\", \"qa\", \"reports\", \"\")\n logger = Logger(filename, path)\n controller = PhoneControl(1)\n\n serials = controller.read_serials()\n for i in range(len(serials)):\n logger.write_log(\" Device {} = {}\".format(i + 1, serials))\n\n controller.init_device(serials[i])\n device_params = utils.get_device_data(serials[i])\n logger.write_log(\"Script UI Calculator -----------------\")\n\n try:\n calculator = Calculator(a, op, b)\n if calculator.valid:\n logger.write_log(\"Operation: \" + a + op + b)\n action(logger, controller, calculator, device_params)\n else:\n logger.error_log(\"Validation of Inputs Failed\")\n except SyntaxError as ex:\n logger.end_log(ex.message)\n except ValueError as ex:\n logger.end_log(ex.message)\n except TypeError as ex:\n logger.end_log(ex.message)\n except ZeroDivisionError as ex:\n logger.end_log(ex.message)\n except Exception as ex:\n logger.error_log(ex.message)\n\n\ndef action(logger, controller, calculator, params):\n controller.unlock_phone()\n controller.click_home()\n controller.click_button(params['calculator']['text'], params['calculator']['className'])\n # empty calculator, depending on the state\n\n # calculator has a previous result saved\n if controller.detailed_button_exists(params['calculator_clear']['className'], params['calculator_clear']['packageName'], params['calculator_clear']['description']):\n controller.longclick_detailed_button(params['calculator_clear']['className'], params['calculator_clear']['packageName'],\n params['calculator_clear']['description'])\n # calculator has non processed input\n if controller.detailed_button_exists(params['calculator_delete']['className'], params['calculator_delete']['packageName'], params['calculator_delete']['description']):\n controller.longclick_detailed_button(params['calculator_delete']['className'],\n params['calculator_delete']['packageName'], params['calculator_delete']['description'])\n controller.clear_text_textfield(params['calculator_delete']['className'],\n params['calculator_delete']['packageName'])\n for i in calculator.number1:\n if i == \"-\":\n controller.click_detailed_button(params[\"-\"][\"className\"], params[\"-\"][\"packageName\"],\n params[\"-\"][\"description\"])\n else:\n controller.click_button(i, params['digit_calculator'])\n\n controller.click_detailed_button(params[calculator.operator][\"className\"], params[calculator.operator][\"packageName\"],\n params[calculator.operator][\"description\"])\n for i in calculator.number2:\n if i == \"-\":\n controller.click_detailed_button(params[\"-\"][\"className\"], params[\"-\"][\"packageName\"],\n params[\"-\"][\"description\"])\n else:\n controller.click_button(i, params['digit_calculator'])\n controller.click_detailed_button(params[\"=\"][\"className\"], params[\"=\"][\"packageName\"], params[\"=\"][\"description\"])\n result = controller.get_text_textfield(params[\"calculator_textfield\"][\"className\"],\n params[\"calculator_textfield\"][\"packageName\"])\n\n # validate result\n if calculator.validate_result(result):\n logger.write_log(\"VALID RESULT: \" + str(calculator.res))\n logger.end_log()\n else:\n logger.error_log(\"Results don't match\")\n\n controller.click_home()\n\n\n# ---------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n # manual input\n run(\"56546\", \"*\", \"546541\")","sub_path":"src/scripts/calculator_ui.py","file_name":"calculator_ui.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"523028285","text":"#!/usr/bin/env python3\n\"\"\"\n ROS publisher node publishing an incrementing number \n\tReads the publish rate from ROS Parameter server\n \n Author: Jari Honkanen\n\"\"\"\n\nimport rospy\nfrom std_msgs.msg import Int64\n\nif __name__ == '__main__':\n\n\trospy.init_node(\"simple_number_publisher\")\n\tpub = rospy.Publisher(\"/number\", Int64, queue_size=10)\n\n\trospy.loginfo(\"[INFO] simple_number_publisher started\")\n\n\ttry:\n\t\tpublish_freq = rospy.get_param(\"/number_publish_frequency\") # Rate in Hz\n\texcept KeyError as e:\n\t\trospy.logwarn(\"[ERROR] getting number_publish_frequency failed\")\n\t\tpublish_freq = 1\n\n\trate = rospy.Rate(publish_freq) \n\n\trospy.set_param(\"/number_publisher_message\", \"Hi, there!\")\n\n\tnumber = 1\n\n\twhile not rospy.is_shutdown():\n\n\t\tmsg = Int64()\n\t\tmsg.data = number \n\t\tpub.publish(msg)\n\t\trospy.loginfo(\"[INFO] Published number \" + str(number))\n\t\tnumber += 1\n\t\trate.sleep()\n","sub_path":"my_simple_robot_nodes/scripts/simple_number_publisher_with_param.py","file_name":"simple_number_publisher_with_param.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"250583121","text":"import os, statistics\n\nshowers = ['geminids', 'leonids', 'orionids', 'perseids', 'quadrantids',\\\n 'eta_aquariids']\n\nfiles = ['allData', 'closePeakData', 'peakData']\n\nbasedir = '/home/cwp/EMC/lib/analysis/zhr/finalData/'\n\npossibilities = ['Average of all: ','Err of all: ','UQ of all: ',\\\n 'Average of peak: ','Err of peak: ','UQ of peak: ',\\\n 'Average of close peak: ','Err of close peak: ','UQ of close peak: ']\n\nfor shower in showers:\n print('===========%s===========' % shower)\n avgs = {}\n pers = {}\n errs = {}\n for directory in files:\n avgs[directory]={}\n pers[directory]={}\n errs[directory]={}\n\n for observerFile in os.listdir(basedir+directory+'/'+shower+'/'):\n with open(basedir+directory+'/'+shower+'/'+observerFile, 'r') as f:\n allLines = f.readlines()\n for line in allLines:\n year = line.split(',')[0]\n avgZhr = float(line.split(',')[1])\n errZhr = float(line.split(',')[2])\n perZhr = float(line.split(',')[3].split('\\n')[0])\n\n if year not in avgs[directory].keys():\n avgs[directory][year] = [avgZhr]\n else:\n avgs[directory][year].append(avgZhr)\n\n if year not in errs[directory].keys():\n errs[directory][year] = [errZhr]\n else:\n errs[directory][year].append(errZhr)\n\n if year not in pers[directory].keys():\n pers[directory][year] = [perZhr]\n else:\n pers[directory][year].append(perZhr)\n\n\n for year in ['2005','2006','2007','2010','2011','2012','2013','2014','2015','2016']:\n print('Year: ',year)\n try:\n with open(basedir+'final/'+year+shower+'.txt', 'r') as f:\n lines = f.readlines()\n\n for i in range(len(lines)):\n print(lines[i])\n\n except:\n pass\n\n \"\"\"\n for directory in files:\n try:\n print(directory)\n print('Mean mean: ',statistics.mean(avgs[directory][year]))\n print('Mean err: ',statistics.mean(errs[directory][year]))\n print('Mean 90th percentile: ',statistics.mean(pers[directory][year]))\n except:\n pass\n \"\"\"\n raw_input()\n","sub_path":"lib/analysis/zhr/finalStuff.py","file_name":"finalStuff.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"335649332","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nimport urlparse\n\ndef join(url, part):\n sep = \"/\"\n if url.endswith(\"/\"):\n sep = \"\"\n return \"%s%s%s\" % (url, sep, part)\n\ndef make(url, path = None):\n u = \"\"\n\n if path is not None:\n u = urlparse.urlunparse((url.scheme, url.netloc, path, url.params, \n url.query, url.fragment))\n else:\n u = url.geturl()\n\n return u\n","sub_path":"venv/Lib/site-packages/caldav/lib/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"304168102","text":"\"\"\"empty message\n\nRevision ID: e032cee1827b\nRevises: ef534dc6a6e3\nCreate Date: 2020-04-22 08:48:04.721179\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e032cee1827b'\ndown_revision = 'ef534dc6a6e3'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('ix_post_model_title', table_name='post_model')\n op.create_index(op.f('ix_post_model_title'), 'post_model', ['title'], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_post_model_title'), table_name='post_model')\n op.create_index('ix_post_model_title', 'post_model', ['title'], unique=False)\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/e032cee1827b_.py","file_name":"e032cee1827b_.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"556575549","text":"from typing import List, Dict, Tuple\n\nfrom collections import namedtuple\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom scipy.optimize import approx_fprime as derivative\nfrom time import time\n\nfrom corners import FrameCorners\nfrom _camtrack import *\n\nProjectionError = namedtuple(\n 'ProjectionError',\n ('frame_id', 'id_3d', 'id_2d')\n)\n\n\ndef run_bundle_adjustment(intrinsic_mat: np.ndarray,\n list_of_corners: List[FrameCorners],\n max_inlier_reprojection_error: float,\n view_mats: List[np.ndarray],\n point_positions: List[np.ndarray]) -> Tuple[List[np.ndarray], List[np.ndarray]]:\n print('Running bundle adjustment')\n orig_point_positions = point_positions\n def transf(p):\n if p is not None:\n return p\n return np.zeros(3)\n point_positions = np.array([transf(p) for p in point_positions])\n proj_mats = [intrinsic_mat @ view_mat for view_mat in view_mats]\n projection_errors = []\n used_3d_points_inds = set()\n\n for k, (proj_mat, corners) in enumerate(zip(proj_mats, list_of_corners)):\n indices = np.array([ind for ind in corners.ids if point_positions[ind] is not None], dtype=np.int32)\n indices_2d_local = np.array([k for k, ind in enumerate(corners.ids) if ind in indices], np.int32)\n indices_3d_local = indices[:, 0]\n inlier_indices = calc_inlier_indices(point_positions[indices_3d_local],\n corners.points[indices_2d_local],\n proj_mat,\n max_inlier_reprojection_error)\n for ind in inlier_indices:\n id_3d = indices_3d_local[ind]\n id_2d = indices_2d_local[ind]\n used_3d_points_inds.add(id_3d)\n projection_errors.append(ProjectionError(frame_id=k, id_3d=id_3d, id_2d=id_2d))\n\n used_3d_points_inds = list(sorted(used_3d_points_inds))\n point_ind_to_position = {}\n n_matrix_params = 6 * len(view_mats)\n p = np.concatenate([_view_mats3x4_to_rt(view_mats),\n _points_to_flat_coordinates(point_positions[used_3d_points_inds])])\n for k, point_ind in enumerate(used_3d_points_inds):\n point_ind_to_position[point_ind] = n_matrix_params + 3 * k\n\n if _run_optimization(projection_errors, list_of_corners, point_ind_to_position, p, intrinsic_mat, 3):\n for k in range(len(view_mats)):\n r_vec = p[6 * k: 6 * k + 3].reshape(3, 1)\n t_vec = p[6 * k + 3: 6 * k + 6].reshape(3, 1)\n view_mat = rodrigues_and_translation_to_view_mat3x4(r_vec, t_vec)\n view_mats[k] = view_mat\n\n for k, ind in enumerate(used_3d_points_inds):\n orig_point_positions[ind] = p[n_matrix_params + 3 * k: n_matrix_params + 3 * k + 3]\n\n return view_mats, orig_point_positions\n\n\ndef _view_mats3x4_to_rt(view_mats: List[np.ndarray]) -> np.ndarray:\n result = np.zeros(6 * len(view_mats))\n for k, mat in enumerate(view_mats):\n pos = 6 * k\n r, t = view_mat3x4_to_rodrigues_and_translation(mat)\n result[pos: pos + 3] = r[:, 0]\n result[pos + 3: pos + 6] = t[:]\n return result\n\n\ndef _points_to_flat_coordinates(points: np.ndarray) -> np.ndarray:\n return points.reshape(-1)\n\n\ndef _vec_to_proj_mat(vec: np.ndarray, intrinsic_mat: np.ndarray) -> np.ndarray:\n r_vec = vec[0:3].reshape(3, 1)\n t_vec = vec[3:6].reshape(3, 1)\n view_mat = rodrigues_and_translation_to_view_mat3x4(r_vec, t_vec)\n return np.dot(intrinsic_mat, view_mat)\n\n\ndef _reprojection_error(vec: np.ndarray, point2d: np.ndarray, intrinsic_mat: np.ndarray) -> np.float32:\n point3d = vec[6:9]\n proj_mat = _vec_to_proj_mat(vec, intrinsic_mat)\n point3d_hom = np.hstack((point3d, 1))\n proj_point2d = np.dot(proj_mat, point3d_hom)\n proj_point2d = proj_point2d / proj_point2d[2]\n proj_point2d = proj_point2d.T[:2]\n proj_error = (point2d - proj_point2d).reshape(-1)\n return np.linalg.norm(proj_error)\n\n\ndef _reprojection_errors(projection_errors: List[ProjectionError],\n list_of_corners: List[FrameCorners],\n mapping: Dict[int, int],\n p: np.ndarray,\n intrinsic_mat: np.ndarray) -> np.ndarray:\n errors = np.zeros(len(projection_errors))\n for i, proj_err in enumerate(projection_errors):\n vec = np.zeros(9)\n\n mat_pos = 6 * proj_err.frame_id\n vec[:6] = p[mat_pos: mat_pos + 6]\n\n point_pos = mapping[proj_err.id_3d]\n vec[6:] = p[point_pos: point_pos + 3]\n\n point2d = list_of_corners[proj_err.frame_id].points[proj_err.id_2d]\n\n errors[i] = _reprojection_error(vec, point2d, intrinsic_mat)\n\n return errors\n\n\ndef _compute_jacobian(projection_errors: List[ProjectionError],\n list_of_corners: List[FrameCorners],\n mapping: Dict[int, int],\n p: np.ndarray,\n intrinsic_mat: np.ndarray) -> csr_matrix:\n start_time = time()\n print(\"Started Jacobian computation\")\n # J = np.zeros((len(projection_errors), len(p)))\n rows = np.zeros(9 * len(projection_errors), dtype=np.int32)\n cols = np.zeros(9 * len(projection_errors), dtype=np.int32)\n vals = np.zeros(9 * len(projection_errors), dtype=np.float32)\n cur = 0\n for row, proj_err in enumerate(projection_errors):\n vec = np.zeros(9)\n\n mat_pos = 6 * proj_err.frame_id\n vec[:6] = p[mat_pos: mat_pos + 6]\n\n point_pos = mapping[proj_err.id_3d]\n vec[6:] = p[point_pos: point_pos + 3]\n\n point2d = list_of_corners[proj_err.frame_id].points[proj_err.id_2d]\n\n partial_derivatives = derivative(vec,\n lambda v: _reprojection_error(v, point2d, intrinsic_mat),\n np.full_like(vec, 1e-9))\n\n for i in range(6):\n rows[cur] = row\n cols[cur] = mat_pos + i\n vals[cur] = partial_derivatives[i]\n cur += 1\n\n for i in range(3):\n rows[cur] = row\n cols[cur] = point_pos + i\n vals[cur] = partial_derivatives[6 + i]\n cur += 1\n print(f\"Finished in {time() - start_time} sec\")\n return csr_matrix((vals, (rows, cols)), shape=(len(projection_errors), len(p)))\n\n\ndef _run_optimization(projection_errors: List[ProjectionError],\n list_of_corners: List[FrameCorners],\n mapping: Dict[int, int],\n p: np.ndarray,\n intrinsic_mat: np.ndarray,\n n_steps: int) -> bool:\n n = 3 * len(list_of_corners)\n lmbd = 2.\n initial_error = _reprojection_errors(projection_errors, list_of_corners, mapping, p, intrinsic_mat).sum()\n print(f'Initial error: {initial_error}')\n if initial_error < 1.:\n print(f'Error is too small for BA')\n return False\n\n total_steps = 0\n successful_steps = 0\n hit_the_bottom = False\n lmbd_change = 4.\n while successful_steps < n_steps or total_steps < n_steps * 2:\n total_steps += 1\n J = _compute_jacobian(projection_errors, list_of_corners, mapping, p, intrinsic_mat)\n JJ = (J.T @ J).toarray()\n JJ += lmbd * np.diag(np.diag(JJ))\n U = JJ[:n, :n]\n W = JJ[:n, n:]\n V = JJ[n:, n:]\n try:\n V_inv = np.zeros_like(V)\n for i in range(0, len(V), 3):\n s = 3 * i\n t = 3 * i + 3\n V_inv[s:t, s:t] = np.linalg.inv(V[s:t, s:t])\n except np.linalg.LinAlgError:\n hit_the_bottom = True\n lmbd *= lmbd_change\n continue\n\n g = J.T @ _reprojection_errors(projection_errors, list_of_corners, mapping, p, intrinsic_mat)\n A = U - W @ V_inv @ W.T\n b = W @ V_inv @ g[n:] - g[:n]\n\n try:\n dc = np.linalg.solve(A, b)\n except np.linalg.LinAlgError:\n hit_the_bottom = True\n lmbd *= lmbd_change\n continue\n\n dx = V_inv @ (-g[n:] - W.T @ dc)\n\n p[:n] += dc\n p[n:] += dx\n error = _reprojection_errors(projection_errors, list_of_corners, mapping, p, intrinsic_mat).sum()\n if error > initial_error:\n p[:n] -= dc\n p[n:] -= dx\n lmbd *= lmbd_change\n hit_the_bottom = True\n print(f\"Lambda changed to {lmbd}\")\n else:\n initial_error = error\n successful_steps += 1\n if not hit_the_bottom:\n lmbd /= lmbd_change\n print(f\"Lambda changed to {lmbd}\")\n print(f\"Current error {error}\")\n print(f'Final error: {initial_error}')\n return True\n","sub_path":"camtrack/ba.py","file_name":"ba.py","file_ext":"py","file_size_in_byte":8812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"308454590","text":"# @Time : 2/18/19 2:42 PM\n# @Author : weishu\n# @Company : 3-Reality\n# @File : insightFace.py\n# @Software: PyCharm\n\nimport cv2\nimport os\nimport numpy as np\nimport mxnet as mx\nimport sklearn.preprocessing\n\nclass Insightface_API(object):\n def __init__(self, model_str, img_size = 112):\n ctx = mx.cpu()\n # ctx = mx.gpu(0)\n image_size = [img_size, img_size]\n _vec = model_str.split(',')\n layer = 'fc1'\n assert len(_vec) == 2\n prefix = _vec[0]\n epoch = int(_vec[1])\n print('loading', prefix, epoch)\n sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)\n all_layers = sym.get_internals()\n sym = all_layers[layer + '_output']\n model = mx.mod.Module(symbol=sym, context=ctx, label_names=None)\n # model.bind(data_shapes=[('data', (args.batch_size, 3, image_size[0], image_size[1]))], label_shapes=[('softmax_label', (args.batch_size,))])\n model.bind(for_training=False, data_shapes=[('data', (1, 3, image_size[0], image_size[1]))])\n model.set_params(arg_params, aux_params)\n self.model = model\n\n def extract(self, img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = np.transpose(img, (2, 0, 1))\n input_blob = np.expand_dims(img, axis=0)\n data = mx.nd.array(input_blob)\n db = mx.io.DataBatch(data=(data,))\n self.model.forward(db, is_train=False)\n embedding = self.model.get_outputs()[0].asnumpy()\n embedding = sklearn.preprocessing.normalize(embedding).flatten()\n return embedding\n\n\nif __name__ == '__main__':\n from utils.util import distance\n # extract_model_path = os.environ['HOME'] + \"/models/insightface/model-r50-am-lfw/model, 0\"\n # insightface_API = Insightface_API(extract_model_path)\n # img1 = cv2.imread(os.environ['HOME'] + \"/A311D/insightface/test_112_cz_1.jpg\")\n # imbeddings1 = insightface_API.extract(img1)\n # print(imbeddings1)\n #\n # img2 = cv2.imread(os.environ['HOME'] + \"/A311D/insightface/test_112_cz_5.jpg\")\n # imbeddings2 = insightface_API.extract(img2)\n # print(imbeddings2)\n #\n # print(distance([imbeddings1], [imbeddings2], 0))\n\n with open('/home/weishu/A311D/insightface/bin_r/output0_512_1_cz_1.txt', 'r') as f:\n imbeddings1_ = f.readlines()\n for i in range(0, len(imbeddings1_)):\n imbeddings1_[i] = float(imbeddings1_[i].rstrip('\\n'))\n print(imbeddings1_)\n\n with open('/home/weishu/A311D/insightface/bin_r/output0_512_1_cz_5.txt', 'r') as f:\n imbeddings2_ = f.readlines()\n for i in range(0, len(imbeddings2_)):\n imbeddings2_[i] = float(imbeddings2_[i].rstrip('\\n'))\n print(imbeddings2_)\n\n print(distance([imbeddings1_], [imbeddings2_], 0))\n\n","sub_path":"api/insightFace.py","file_name":"insightFace.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"405482196","text":"from datetime import datetime\nfrom csv_merge.tools.helpers import rpad, tuples_to_dicts\n\ndef transform(data):\n \"\"\"Transforms data to the target common structure:\n - amount (float)\n - date (date)\n - from (int)\n - source (str)\n - to (int)\n - transaction (str)\n\n Args:\n data (list[dict]): source data arrived from bank2\n\n Returns:\n list[dict]: normalized data to the common structure\n \"\"\"\n dataset = []\n record = {'source': 'BANK2'}\n for row in data:\n for (k,v) in row.items():\n if k == 'date':\n record[k] =datetime.strptime(v,'%d-%m-%Y').strftime('%Y-%m-%d')\n elif k == 'amounts':\n # converting for the input data validation\n # padding zeroes to the right to have proper cents \n record['amount'] = rpad(str(float(v)))\n elif k == 'transaction':\n record[k] = v\n elif k in {'from', 'to'}:\n # converting for the input data validation\n record[k] = int(v)\n else:\n raise Exception(f'Unexpected column {k} obtained from BANK2')\n # sorting the dict to have the same order. \n # Due to we have no requirement regarding the order, it will be alphabetical\n sorted_record = sorted(record.items(), key=lambda entity: entity[0])\n #due to sorted() function returns list of tuples, we need to get back list of dicts\n dataset.append(tuples_to_dicts(sorted_record))\n\n return dataset","sub_path":"csv_merge/tools/csv_parser/bank2_parser.py","file_name":"bank2_parser.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"494201900","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 14 16:15:24 2021\r\n\r\n@author: travis.czechorski\r\n\r\nEmail: travis.czechorski@maine.edu\r\n tjczec01@gmail.com\r\n \r\nAdvisor: thomas.schwartz@maine.edu\r\n \r\nGithub: https://github.com/tjczec01 \r\n\r\n\"\"\"\r\n\r\nfrom fipy import CellVariable, Grid1D, TransientTerm, VanLeerConvectionTerm, DiffusionTerm, ImplicitSourceTerm, ConvectionTerm, CentralDifferenceConvectionTerm, Viewer\r\nfrom fipy.tools import numerix\r\n\r\nmolarWeight = 0.118\r\nee = -0.455971\r\ngasConstant = 8.314\r\ntemperature = 650.\r\nvbar = 1.3e-05\r\nliquidDensity = 7354.3402662299995\r\nvaporDensity = 82.855803327810008\r\n\r\ndef f(rho):\r\n return ee * rho**2 / molarWeight**2 + gasConstant * temperature * rho / molarWeight * \\\r\n numerix.log(rho / (molarWeight - vbar * rho))\r\n \r\ndef mu(rho):\r\n return 2 * ee * rho / molarWeight**2 + gasConstant * temperature / molarWeight * \\\r\n (numerix.log(rho / (molarWeight - vbar * rho)) + molarWeight / (molarWeight - vbar * rho))\r\n \r\ndef P(rho):\r\n return rho * mu(rho) - f(rho)\r\n\r\nprint(numerix.allclose(mu(liquidDensity), mu(vaporDensity)))\r\n\r\nprint(numerix.allclose(P(liquidDensity), P(vaporDensity)))\r\n\r\nLx = 1e-6\r\nnx = 100\r\ndx = Lx / nx\r\nmesh = Grid1D(nx=nx, dx=dx)\r\n\r\ndensity = CellVariable(mesh=mesh, hasOld=True, name=r'$\\rho$')\r\nvelocity = CellVariable(mesh=mesh, hasOld=True, name=r'$u$')\r\ndensityPrevious = density.copy()\r\nvelocityPrevious = velocity.copy()\r\n\r\npotentialNC = CellVariable(mesh=mesh, name=r'$\\mu^{NC}$')\r\n\r\nepsilon = 1e-16\r\nfreeEnergy = (f(density) + epsilon * temperature / 2 * density.grad.mag**2).cellVolumeAverage\r\n\r\nmatrixDiagonal = CellVariable(mesh=mesh, name=r'$a_f$', value=1e+20, hasOld=True)\r\ncorrectionCoeff = mesh._faceAreas * mesh._cellDistances / matrixDiagonal.faceValue\r\nmassEqn = TransientTerm(var=density) \\\r\n + VanLeerConvectionTerm(coeff=velocity.faceValue + correctionCoeff \\\r\n * (density * potentialNC.grad).faceValue, \\\r\n var=density) \\\r\n - DiffusionTerm(coeff=correctionCoeff * density.faceValue**2, var=potentialNC)\r\n \r\nviscosity = 1e-3\r\nConvectionTerm = CentralDifferenceConvectionTerm\r\nmomentumEqn = TransientTerm(coeff=density, var=velocity) \\\r\n + ConvectionTerm(coeff=[[1]] * density.faceValue * velocity.faceValue, var=velocity) \\\r\n == DiffusionTerm(coeff=2 * viscosity, var=velocity) \\\r\n - ConvectionTerm(coeff=density.faceValue * [[1]], var=potentialNC) \\\r\n + ImplicitSourceTerm(coeff=density.grad[0], var=potentialNC)\r\n \r\nvelocity.constrain(0, mesh.exteriorFaces)\r\npotentialDerivative = 2 * ee / molarWeight**2 + gasConstant * temperature * molarWeight / density / (molarWeight - vbar * density)**2\r\npotential = mu(density)\r\n\r\npotentialNCEqn = ImplicitSourceTerm(coeff=1, var=potentialNC) \\\r\n == potential \\\r\n + ImplicitSourceTerm(coeff=potentialDerivative, var=density) \\\r\n - potentialDerivative * density \\\r\n - DiffusionTerm(coeff=epsilon * temperature, var=density)\r\n \r\npotentialNC.faceGrad.constrain(value=[0], where=mesh.exteriorFaces)\r\n\r\ncoupledEqn = massEqn & momentumEqn & potentialNCEqn\r\n\r\nnumerix.random.seed(2011)\r\ndensity[:] = (liquidDensity + vaporDensity) / 2 * \\\r\n (1 + 0.01 * (2 * numerix.random.random(mesh.numberOfCells) - 1))\r\n \r\nfrom fipy import input\r\nif __name__ == '__main__':\r\n viewers = Viewer(density), Viewer(velocity), Viewer(potentialNC)\r\n for viewer in viewers:\r\n viewer.plot()\r\n input('Arrange viewers, then press to proceed...')\r\n for viewer in viewers:\r\n viewer.plot()\r\n \r\ncfl = 0.1\r\ntolerance = 1e-1\r\ndt = 1e-14\r\ntimestep = 0\r\nrelaxation = 0.5\r\nif __name__ == '__main__':\r\n totalSteps = 1e10\r\nelse:\r\n totalSteps = 10\r\n \r\nwhile timestep < totalSteps:\r\n\r\n sweep = 0\r\n dt *= 1.1\r\n residual = 1.\r\n initialResidual = None\r\n\r\n density.updateOld()\r\n velocity.updateOld()\r\n matrixDiagonal.updateOld()\r\n\r\n while residual > tolerance:\r\n\r\n densityPrevious[:] = density\r\n velocityPrevious[:] = velocity\r\n previousResidual = residual\r\n\r\n dt = min(dt, dx / max(abs(velocity)) * cfl)\r\n\r\n coupledEqn.cacheMatrix()\r\n residual = coupledEqn.sweep(dt=dt)\r\n\r\n if initialResidual is None:\r\n initialResidual = residual\r\n\r\n residual = residual / initialResidual\r\n\r\n if residual > previousResidual * 1.1 or sweep > 20:\r\n density[:] = density.old\r\n velocity[:] = velocity.old\r\n matrixDiagonal[:] = matrixDiagonal.old\r\n dt = dt / 10.\r\n if __name__ == '__main__':\r\n print('Recalculate the time step')\r\n timestep -= 1\r\n break\r\n else:\r\n matrixDiagonal[:] = coupledEqn.matrix.takeDiagonal()[mesh.numberOfCells:2 * mesh.numberOfCells]\r\n density[:] = relaxation * density + (1 - relaxation) * densityPrevious\r\n velocity[:] = relaxation * velocity + (1 - relaxation) * velocityPrevious\r\n\r\n sweep += 1\r\n\r\n if __name__ == '__main__' and timestep % 10 == 0:\r\n print('timestep: %e / %e, dt: %1.5e, free energy: %1.5e' % (timestep, totalSteps, dt, freeEnergy))\r\n for viewer in viewers:\r\n viewer.plot()\r\n\r\n timestep += 1\r\n \r\nfrom fipy import input\r\nif __name__ == '__main__':\r\n input('finished')\r\nprint(freeEnergy < 1.5e9)","sub_path":"fipyexample.py","file_name":"fipyexample.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"439340138","text":"\"\"\" Library imports\n\"\"\"\nimport netifaces\nimport struct\nimport socket\nimport sys\nimport _thread\nimport threading\nimport time\n\nimport Helper\nimport Message\nimport RipEntry\nimport Interfaces\nimport Request\nimport Response\nimport GlobalParameters\n\n''' Global containers '''\nrouting_table = Interfaces.scann_interfaces()\nneighbours_list = list()\n\n''' This is infinite thread which in every 30 seconds sends\n update to its neighbours by split horizon '''\n\n\ndef split_horizon(sock):\n\n while True:\n\n ''' sleep thread for 30 seconds '''\n time.sleep(GlobalParameters.UPDATE_TIME_INTERVAL_SECONDS)\n\n ''' log routing table'''\n current_time = int(time.time())\n\n GlobalParameters.logging_lock.acquire()\n print(\"\\nSending update...\")\n\n # lock neighbours list\n GlobalParameters.neighbours_lock.acquire()\n\n ''' take each neighbour from neighbours list '''\n for neighbour in neighbours_list:\n entry_list = list()\n ''' construct message from routing table for neighbour '''\n\n # lock routing table\n GlobalParameters.routing_table_lock.acquire()\n\n print(\"Sending update to \" + neighbour)\n\n for (network, mask) in routing_table:\n\n (hop_count, src_ip, last_update_time) = routing_table[(network, mask)]\n ''' don't send message back to neighbour '''\n if src_ip == neighbour:\n continue\n\n ''' increase hop count '''\n if hop_count < GlobalParameters.INFINITY_HOP_COUNT:\n hop_count += 1\n\n ''' check if 180 seconds passed without update\n on this entry\n '''\n if current_time - last_update_time > GlobalParameters.INVALID_TIMER_DEFAULT_SECONDS \\\n and last_update_time > 0:\n hop_count = GlobalParameters.INFINITY_HOP_COUNT\n ''' update routing table entry metric as infinite '''\n routing_table[(network, mask)] = (hop_count, src_ip, current_time)\n\n ''' log this entry '''\n Helper.log(network, mask, hop_count)\n\n entry = RipEntry.RipEntry(GlobalParameters.ADDRESS_FAMILY,\n GlobalParameters.ROUTE_TAG,\n network,\n mask,\n GlobalParameters.NEXT_HOP_ZERO,\n hop_count)\n\n entry_list.append(entry)\n GlobalParameters.routing_table_lock.release()\n\n ''' make 25-25 entry messages and send them one-by-one '''\n while len(entry_list) > 0:\n ''' construct message '''\n result_list, entry_list = Helper.pop_first_n_element(entry_list,\n GlobalParameters.MAX_NUMBER_OF_ENTRIES)\n\n ''' get message '''\n rip_message = Message.Message(GlobalParameters.RESPONSE,\n GlobalParameters.RIPv2_VERSION,\n GlobalParameters.UNUSED,\n result_list)\n ''' take message bytes '''\n message_bytes = Helper.message_to_bytes(rip_message)\n ''' send message '''\n neighbour_address = (neighbour, GlobalParameters.RIP_PORT)\n sock.sendto(message_bytes, neighbour_address)\n\n # release locks\n GlobalParameters.logging_lock.release()\n GlobalParameters.neighbours_lock.release()\n\n\nrequest = Helper.construct_first_request()\nmulti_cast_address = (GlobalParameters.IP_MULTI_CAST_ADDRESS,\n GlobalParameters.RIP_PORT)\n\n''' setup socket and start server '''\n\nprint(\"\\nStart listening on socket UDP 520\")\n\n''' set socket listening to multi casts and reusable port '''\n\nwith socket.socket(socket.AF_INET, socket.SOCK_DGRAM,\n socket.IPPROTO_UDP) as server_socket:\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n server_socket.bind((GlobalParameters.IP_MULTI_CAST_ADDRESS,\n GlobalParameters.RIP_PORT))\n\n server_socket.setsockopt(socket.IPPROTO_IP,\n socket.IP_MULTICAST_TTL,\n GlobalParameters.TTL)\n\n server_socket.setsockopt(socket.IPPROTO_IP,\n socket.IP_ADD_MEMBERSHIP,\n socket.inet_aton(GlobalParameters.IP_MULTI_CAST_ADDRESS) +\n socket.inet_aton(GlobalParameters.LISTEN_ALL_INTERFACES))\n\n print(\"\\nSending request to 224.0.0.9\")\n sent = server_socket.sendto(request, multi_cast_address)\n\n ''' Send multi cast request to neighbours '''\n\n _thread.start_new_thread(split_horizon, (server_socket,))\n\n ''' Run server '''\n while True:\n\n ''' get byte data from socket '''\n data, server = server_socket.recvfrom(GlobalParameters.MAX_NUMBER_OF_RECEIVED_BYTES)\n message = Helper.bytes_to_message(data)\n neighbour_ip = server[0]\n\n ''' lock and update neighbours list '''\n GlobalParameters.neighbours_lock.acquire()\n if neighbour_ip not in neighbours_list:\n neighbours_list.append(neighbour_ip)\n GlobalParameters.neighbours_lock.release()\n\n ''' assert version number to be 2 '''\n if message.get_version() != GlobalParameters.RIPv2_VERSION:\n GlobalParameters.logging_lock.acquire()\n print(\"Not RIPv2 version. Nothing to respond\\n\")\n GlobalParameters.logging_lock.release()\n continue\n\n if message.get_command() is GlobalParameters.REQUEST:\n Request.handle_request(message, server_socket, server, routing_table)\n else:\n Response.handle_response(message, server, routing_table)\n","sub_path":"RIPv2/ripd.py","file_name":"ripd.py","file_ext":"py","file_size_in_byte":6041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"18674891","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 15 01:48:56 2017\n\n@author: Junwoo Suh\n\nDeals with input and output of the data\n\"\"\"\n\nimport os\nfrom tkinter import Tk\nfrom tkinter import filedialog\nimport preprocess.process_data as data\n\n\ndef open_data():\n # Read EDF file using Gui\n root = Tk()\n root.fname = filedialog.askopenfilename(initialdir=os.getcwd(),\n title=\"Select EDF data file\",\n filetypes=((\"EDF files\", \"*.edf\"),\n (\"all files\", \"*.*\")))\n root.aname = filedialog.askopenfilename(initialdir=os.getcwd(),\n title=\"Select EDF annotation file\",\n filetypes=((\"text files\", \"*.txt\"), (\"all files\", \"*.*\")))\n root.header = filedialog.askopenfilename(initialdir=os.getcwd(),\n title=\"Select EDF header file\",\n filetypes=((\"text files\", \"*.txt\"), (\"all files\", \"*.*\")))\n root.destroy()\n return data.raw_signal(root.fname, root.aname, root.header)\n\ndef read_annot(annot):\n # Read annotation file in text form\n has_sleep_score = False\n with open(annot,\"r\") as input_file:\n sc_list = []\n for i, line in enumerate(input_file):\n delimited_line = line.split(\"\\t\") # .txt file is delimited with tab\n if \"Sleep Stage\" in delimited_line : # Actual data starts after this line\n has_sleep_score = True\n data_start = i + 1 # Mark the line that the data starts\n sc_ind = delimited_line.index('Event')\n time_ind = delimited_line.index('Time [hh:mm:ss]')\n continue # Skip the line that contains names\n if has_sleep_score:\n if i == data_start:\n anot_start = delimited_line[time_ind] # Find start time\n \n event = delimited_line[sc_ind].split(\"-\") # event is used to remove CAP related events\n if event[0] == \"SLEEP\": # Get only sleep related events\n sc = delimited_line[0]\n if sc == 'W':\n n_sc = 0\n elif sc == 'R':\n n_sc = 1\n elif sc == 'S1':\n n_sc = 2\n elif sc == 'S2':\n n_sc = 3\n elif sc == 'S3':\n n_sc = 4\n else:\n n_sc = 5\n sc_list.append(n_sc) # Record sleep Scores\n if delimited_line[time_ind] != '':\n line_buff = delimited_line\n else:\n continue\n if delimited_line[time_ind] != '':\n anot_end = delimited_line[time_ind] # Find end time\n else:\n anot_end = line_buff[time_ind] # Find end time\n \n anot_start, anot_end = anot_start.split(\":\"), anot_end.split(\":\")\n return anot_start, anot_end, sc_list\nh_freq = 60 # Just a testing value. Can try different number under Nyquist Frequency\n\ndef read_header(pname,header):\n #Read the header file in text form\n pstart, pN = False, 0\n with open(header, \"r\") as input_file:\n for ii,line in enumerate(input_file):\n delimited_line = line.split('.')\n if delimited_line[0] == pname:\n pstart = True\n pN = ii\n continue\n # If the patient id matches get next two lines\n if pstart and ii == pN+ 1: \n r_start_time = line[line.find(\"[\")+1:line.find(\"]\")].split(' ')[0].split(\":\")\n if pstart and ii == pN + 2:\n r_length = line.split(\":\")[1:4] #This is needed due to data formats\n r_length[2] = r_length[2].split('(')[0]\n break\n return r_start_time, r_length\n","sub_path":"Preprocess/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"305826327","text":"\nfrom flask import jsonify\nimport sys\n\nfrom logger_module import get_logger\n\nimport common\nimport constants\nfrom common import mdb\nfrom db_connection_cursor import get_db_connection\nfrom db_connection_cursor import get_db_cursor\nfrom common import make_response\nfrom common import create_response\n\nlogger = get_logger(__file__)\n\n\n# dvcUser class ---------------------------------------------------------------------------\nclass dvcUser:\n \n ''' Device User class '''\n def __init__(self, _id = None, group_id = None, \n username = None, uuid = None):\n\n methodName = sys._getframe().f_code.co_name \n\n self._id = _id\n self.group_id = group_id\n self.username = username\n self.uuid = uuid\n\n def getUserInfo(self, **kwargs):\n\n methodName = sys._getframe().f_code.co_name \n with get_db_connection(database=common.mdb) as devconn, get_db_cursor(devconn, dictionary = True) as cursor:\n try:\n sql = \"SELECT id, group_id, username, uuid, stripe_cust_id \" \\\n \" FROM users \" \n\n if len(kwargs) != 0:\n where = \"WHERE\"\n for key, value in kwargs.items():\n if type(value) == int:\n condition = (\" {field} = {_data} \").format(field = key, _data = value)\n else:\n condition = (\" {field} = \\\"{_data}\\\" \").format(field = key, _data = value)\n if where == \"WHERE\":\n where += (\" {cond} \").format(cond = condition)\n else:\n where += (\" AND {cond} \").format(cond = condition)\n sql += \" \"\n sql += where \n\n cursor.execute(sql)\n userInfo = cursor.fetchall()\n\n return(userInfo)\n\n except Exception as e:\n logger.debug(e) \n self.response = make_response(constants.USER_INFO_FAIL,\n methodName,\n constants.BAD_REQUEST_400)\n\n\n \n def delDvcUser(self, **kwargs):\n with get_db_connection(database=common.mdb) as devconn, get_db_cursor(devconn, dictionary = True) as cursor:\n try:\n sql = \"DELETE FROM users \"\n\n if len(kwargs) != 0:\n where = \"WHERE\"\n for key, value in kwargs.items():\n if type(value) == int:\n condition = (\" {field} = {_data} \").format(field = key, _data = value)\n else:\n condition = (\" {field} = \\\"{_data}\\\" \").format(field = key, _data = value)\n if where == \"WHERE\":\n where += (\" {cond} \").format(cond = condition)\n else:\n where += (\" AND {cond} \").format(cond = condition)\n sql += \" \"\n sql += where \n\n cursor.execute(sql)\n devconn.commit()\n\n except Exception as e:\n logger.debug(e) \n\n\n\n# dvcUser class ---------------------------------------------------------------------------\n\n\n# Ugr class ---------------------------------------------------------------------------\nclass uGR:\n\n ''' UserGroupRole class '''\n\n def __init__(self, username = None, user_id = None, user_uuid = None, group_id = None, \n groupname = None, parent_id = None,\n ugr_id = None, role_tag = None, ugr_uuid = None):\n\n methodName = sys._getframe().f_code.co_name \n\n self.username = username\n self.user_id = user_id\n self.user_uuid = user_uuid\n self.group_id = group_id\n self.groupname = groupname\n self.parent_id = parent_id\n self.ugr_id = ugr_id\n self.role_tag = role_tag\n self.ugr_uuid = ugr_uuid\n\n def getUgrInfo(self):\n\n methodName = sys._getframe().f_code.co_name \n #logger.debug(\"\\n\\n Inside %s\" % methodName) #CTO\n with get_db_connection(database=common.mdb) as devconn, get_db_cursor(devconn) as cursor:\n #logger.debug(\"AFT get_db_connection()\") #CTO\n try:\n sql = \"SELECT UGR.id, UGR.group_id, UGR.role_tag, \" \\\n \" UGR.uuid, G.name, G.parent_id, U.id, U.uuid \" \\\n \" FROM groups G, user_group_roles UGR, users U\" \\\n \" WHERE UGR.user_id = U.id \" \\\n \" AND G.id = UGR.group_id \" \\\n \" AND U.username = \\\"%s\\\" \" \\\n \" ORDER BY UGR.id \" % (self.username)\n cursor.execute(sql)\n rows = cursor.fetchall()\n ugrInfo = []\n for row in rows:\n self.user_id = row[6]\n self.user_uuid = row[7]\n self.group_id = row[1]\n self.groupname = row[4]\n self.parent_id = row[5]\n self.ugr_id = row[0]\n self.role_tag = row[2]\n self.ugr_uuid = row[3]\n\n ugrTmp = {}\n ugrTmp = {\n \"user_id\" : self.user_id,\n \"user_uuid\" : self.user_uuid,\n \"username\" : self.username,\n \"group_id\" : self.group_id,\n \"groupname\" : self.groupname,\n \"parent_id\" : self.parent_id,\n \"ugr_id\" : self.ugr_id,\n \"role_tag\" : self.role_tag,\n \"ugr_uuid\" : self.ugr_uuid\n }\n ugrInfo.append(ugrTmp)\n\n return(ugrInfo)\n\n except Exception as e:\n logger.debug(e) \n\n\n \n\n# Ugr class ---------------------------------------------------------------------------\n\n\n# dvcGroup class ---------------------------------------------------------------------------\nclass dvcGroup:\n\n ''' Device Group class '''\n\n def __init__(self, group_id = None, group_name = None, \n parent_id = None, group_uuid = None, grplvl = None):\n\n self.dvc_grp_dict = {\n \"id\" : group_id,\n \"name\" : group_name,\n \"parent_id\" : parent_id,\n \"uuid\" : group_uuid,\n \"grplvl\" : grplvl\n }\n\n def getGroupInfo(self, **kwargs):\n with get_db_connection(database=common.mdb) as devconn, get_db_cursor(devconn, dictionary = True) as cursor:\n try:\n sql = \" SELECT id, name, parent_id, uuid, grplvl \" \\\n \" FROM groups \" \n\n if len(kwargs) != 0:\n where = \"WHERE\"\n for key, value in kwargs.items():\n if type(value) == int:\n condition = (\" {field} = {_data} \").format(field = key, _data = value)\n else:\n condition = (\" {field} = \\\"{_data}\\\" \").format(field = key, _data = value)\n if where == \"WHERE\":\n where += (\" {cond} \").format(cond = condition)\n else:\n where += (\" AND {cond} \").format(cond = condition)\n sql += \" \"\n sql += where \n\n cursor.execute(sql)\n groups_data = cursor.fetchall() #cursor.fetchone()\n return groups_data\n\n except Exception as e:\n logger.debug(e) \n\n def getUsersInGroup(self):\n with get_db_connection(database=common.mdb) as devconn, get_db_cursor(devconn, dictionary = True) as cursor:\n try:\n sql = (\" SELECT U.id, U.fname, U.group_id, U.lname, U.username, U.uuid \" \n \" FROM users U \" \n \"INNER JOIN groups G \" \n \" WHERE G.id = {grp_id} \" \n \" AND G.id = U.group_id \" \n \" ORDER BY U.id\").format(grp_id = self.dvc_grp_dict[\"id\"])\n cursor.execute(sql)\n user_dict_list = cursor.fetchall()\n return user_dict_list\n\n except Exception as e:\n logger.debug(e) \n\n def getAssetsInGroup(self):\n with get_db_connection(database=common.mdb) as devconn, get_db_cursor(devconn, dictionary = True) as cursor:\n try:\n sql = (\" SELECT S.id, S.deviceid, S.name, S.group_id, S.uuid \" \n \" FROM sentinels S \" \n \"INNER JOIN groups G \" \n \" WHERE G.id = {grp_id} \" \n \" AND G.id = S.group_id \" \n \" ORDER BY S.id\").format(grp_id = self.dvc_grp_dict[\"id\"])\n cursor.execute(sql)\n asset_dict_list = cursor.fetchall()\n return asset_dict_list\n\n except Exception as e:\n logger.debug(e) \n\n\n def delDvcGroup(self, **kwargs):\n with get_db_connection(database=common.mdb) as devconn, get_db_cursor(devconn, dictionary = True) as cursor:\n try:\n sql = \"DELETE FROM groups \"\n\n if len(kwargs) != 0:\n where = \"WHERE\"\n for key, value in kwargs.items():\n if type(value) == int:\n condition = (\" {field} = {_data} \").format(field = key, _data = value)\n else:\n condition = (\" {field} = \\\"{_data}\\\" \").format(field = key, _data = value)\n\n if where == \"WHERE\":\n where += (\" {cond} \").format(cond = condition)\n else:\n where += (\" AND {cond} \").format(cond = condition)\n sql += \" \"\n sql += where \n\n cursor.execute(sql)\n devconn.commit()\n\n except Exception as e:\n logger.debug(e) \n\n# dvcGroup class ---------------------------------------------------------------------------\n","sub_path":"pytest/userGroupRole.py","file_name":"userGroupRole.py","file_ext":"py","file_size_in_byte":10686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"508288540","text":"import os\nfrom xml_to_automl import xml_to_automl\nfrom train_test_split import label_split\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--train_size', default=0.8, type=int, help = 'proportional size of training set')\nparser.add_argument('--google_uri', default='GoogleCloudURI/', type=str, help = 'Google Cloud URI for image paths')\n\nopt = parser.parse_args()\n\ndef convert(train_size=opt.train_size, GoogleCloud_URI=opt.google_uri):\n image_path = os.path.join(os.getcwd(), ('images/'))\n xml_df = xml_to_automl(image_path, GoogleCloud_URI)\n labeled_df = label_split(xml_df, train_size)\n labeled_df.to_csv(('output/automl_labels.csv'), index=None)\n print('Successfully converted xml to automl csv format') \n\nconvert()","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"164491981","text":"\"\"\"goliath URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\n\nurlpatterns = [\n\turl(r'^', include('smitty.apps.core.urls')),\n url(r'^admin/', admin.site.urls),\n url(r'^', include('messages_extends.urls')),\n url(r'^accounts/', include('registration.backends.simple.urls')),\n url(r'^minecraft/', include('smitty.apps.mine.urls')),\n url(r'^left4dead2/', include('smitty.apps.l4d2.urls')),\n url(r'^ark-survival/', include('smitty.apps.arkse.urls')),\n url(r'^console/', include('smitty.apps.console.urls')),\n]\n\n","sub_path":"smitty/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"595682165","text":"import pylab as pl\nimport scipy\nimport scipy.optimize as opt\nf = open(\"intersalt1.txt\", \"r\")\n\n# In x und y werden die Wertepaare gespeichert\nx = []\ny = []\n\nfor line in f.readlines():\n\tline = line.strip()\n\tcolumns = line.split()\n\tif columns[0]!='#':\n\t\ta = float(columns[2])\n\t\tb = float(columns[3])\n\t\tx.append(a)\n\t\ty.append(b)\nf.close()\n\n\ndef linear(X,Y,A):\n\treturn X*Y+A\nparam,cov = opt.curve_fit(linear, x, y, p0=[1,150] )\nprint(param)\nFit = [linear(v,param[0],param[1]) for v in x]\npl.subplot(1,2,1)\npl.xlabel('Blutdruck')\npl.ylabel('Natrium')\npl.plot(x,y,'r*')\npl.plot(x, Fit, 'b-')\n\n\ntmp_y = list(y)\ncounter=0\nfor i in range(0,len(tmp_y)):\n\tif tmp_y[i] < 60:\n\t\ty.pop(i-counter)\n\t\tx.pop(i-counter)\n\t\tcounter+=1\nFit = [linear(v,param[0],param[1]) for v in x]\npl.subplot(1,2,2)\npl.xlabel('Blutdruck')\npl.ylabel('Natrium')\npl.plot(x,y,'r*')\npl.plot(x, Fit, 'b-')\t\t\n\npl.show()","sub_path":"Blatt8/Salz.py","file_name":"Salz.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"644751206","text":"import pglet\nfrom pglet import Stack, Textbox, Button\n\ndef test_stack_add():\n s = Stack(horizontal=True, vertical_fill=True, horizontal_align='center', vertical_align='baseline',\n gap='large', wrap=True, scrollx=True, scrolly=True, controls=[\n Textbox(id=\"firstName\"),\n Textbox(id=\"lastName\")\n ])\n assert isinstance(s, pglet.Control)\n assert isinstance(s, pglet.Stack)\n #raise Exception(s.get_cmd_str())\n assert s.get_cmd_str() == (\n 'stack gap=\"large\" horizontal=\"true\" horizontalalign=\"center\" '\n 'scrollx=\"true\" scrolly=\"true\" verticalalign=\"baseline\" verticalfill=\"true\" wrap=\"true\"\\n'\n ' textbox id=\"firstName\"\\n'\n ' textbox id=\"lastName\"'\n ), \"Test failed\"\n\ndef test_nested_stacks_add():\n s = Stack(controls=[\n Textbox(id=\"firstName\"),\n Textbox(id=\"lastName\"),\n Stack(horizontal=True, controls=[\n Button(id=\"ok\", text=\"OK\", primary=True),\n Button(id=\"cancel\", text=\"Cancel\")\n ])\n ])\n assert isinstance(s, pglet.Control)\n assert isinstance(s, pglet.Stack)\n #raise Exception(s.get_cmd_str())\n assert s.get_cmd_str() == (\n 'stack\\n'\n ' textbox id=\"firstName\"\\n'\n ' textbox id=\"lastName\"\\n'\n ' stack horizontal=\"true\"\\n'\n ' button id=\"ok\" primary=\"true\" text=\"OK\"\\n'\n ' button id=\"cancel\" text=\"Cancel\"'\n ), \"Test failed\"","sub_path":"tests/test_stack.py","file_name":"test_stack.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"580997833","text":"\"\"\"\nAuthor: Luke Mains\nDate: 3.July.2018\n\"\"\"\n\n# Imports\nfrom collections import Counter\n\n# Main:\nmessage = input('Enter message to decode: ')\nletter_freq = Counter()\n\nwhile True:\n cipher_letters = ''\n guesses = ''\n\n letter_freq.clear()\n letter_freq.update([x for x in message if x.isupper()])\n\n print(message, '({})'.format(letter_freq.most_common(3)))\n\n letters = (input('Enter cipher letter and letter to swap with. \\\"a b\\\" will swap a out with b.\\n').split(' '))\n cipher_letters = cipher_letters.join(letters[0].upper())\n guesses = guesses.join(letters[1].lower())\n\n translation_table = str.maketrans(cipher_letters, guesses)\n\n message = message.translate(translation_table)\n","sub_path":"Head Line Puzzles/guesses.py","file_name":"guesses.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"352392141","text":"import logging\n\nfrom rest_framework.views import exception_handler\n\nfrom api.base.exceptions import ServiceException\n\nlogger = logging.getLogger(__name__)\n\n'''\n{\n \"status\": 401,\n \"code\": 2500,\n \"message\": \"error message\",\n \"more_info\": \"http://www.bitberry.app/docs/errors/2500\"\n}\n'''\n\n\ndef api_exception_handler(exc, context):\n # Call REST framework's default exception handler first,\n # to get the standard error response.\n response = exception_handler(exc, context)\n print(f\"response: {response}, {type(exc)}, {exc}\")\n if response:\n if isinstance(exc, ServiceException):\n response.data[\"code\"] = exc.code\n response.data[\"detail\"] = exc.detail\n response.data[\"more_info\"] = exc.more_info\n\n response.data['status'] = response.status_code\n\n return response\n","sub_path":"api/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"637801152","text":"from collections import Counter\n\n\ndata = []\nq1 = 0\nwith open(\"data/day8.txt\") as f:\n for line in f:\n inp, out = map(tuple, map(str.split, line.strip().split(\" | \")))\n for d in out:\n if len(d) in (2, 3, 4, 7):\n q1 += 1\n data.append((inp, out))\n\nprint(\"Q1:\", q1)\nnumbers = {\n 'abcefg': 0,\n 'cf': 1,\n 'acdeg': 2,\n 'acdfg': 3,\n 'bcdf': 4,\n 'abdfg': 5,\n 'abdefg': 6, \n 'acf': 7,\n 'abcdefg': 8,\n 'abcdfg': 9\n}\ntotal = 0\nfor inp, out in data:\n displays = dict.fromkeys(\"abcdefg\")\n lens = list(map(len, inp))\n displays['a'], *_ = set(inp[lens.index(3)]) - set(inp[lens.index(2)])\n\n one = Counter(inp[lens.index(2)])\n seven = Counter(inp[lens.index(3)])\n four = Counter(inp[lens.index(4)])\n\n c = Counter(''.join(x for x in inp if len(x) == 6))\n displays['e'], *_ = [k for k,v in (c + four).items() if v == 2]\n displays['f'], *_ = [k for k,v in (c + one).items() if v == 4]\n displays['c'], *_ = set(one.keys()) - {displays['f']}\n\n c5 = Counter(''.join(x for x in inp if len(x) == 5))\n\n rem = Counter(''.join(x for x in inp if len(x) > 4))\n displays['d'], *_ = [k for k,v in (c5 + four).items() if v == 4]\n displays['g'], *_ = [k for k,v in rem.items() if v == 7 and k != displays['a']]\n displays['b'], *_ = set(\"abcdefg\") - set(displays.values())\n \n reverse = {v:k for k,v in displays.items()}\n \n value = '' \n for number in out:\n value += str(numbers[''.join(sorted(map(reverse.get, number)))])\n total += int(value) \nprint(\"Q2:\", total)\n\n\n","sub_path":"2021/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"58075460","text":"from ..common.helpers import JsonSerializer, get_current_time\nfrom ..extensions import db\n\n\nclass SnapshotJsonSerializer(JsonSerializer):\n __json_public__ = ['snapshot_id', 'instance_id', 'create_date']\n\n\nclass Snapshot(db.Model, SnapshotJsonSerializer):\n __tabename__ = 'snapshots'\n def __repr__(self):\n return ' %s' % (k, v))\n\t\t\t\tif not isinstance(v, str) and v.primary_key:\n\t\t\t\t\tif primaryKey:\n\t\t\t\t\t\traise RuntimeError('Duplicate primary key for field %s' % k)\n\t\t\t\t\tprimaryKey = k\n\t\t\t\telse:\n\t\t\t\t\tfields.append(k)\n\t\t#list 'fields' have all key in dict 'attrs' except primary key.\n\t\tif not primaryKey:\n\t\t\traise RuntimeError('Primary key is not found.')\n\t\tfor k in mappings.keys():\n\t\t\tattrs.pop(k)\n\t\t#use map to generate a list called escaped_fields which translates every %s in fields to `%s`\n\t\tescaped_fields = list(map(lambda x: '`%s`' % x, fields))\n\t\tattrs['__mappings__'] = mappings\n\t\tattrs['__table__'] = table\n\t\tattrs['__primary_key__'] = primaryKey\n\t\tattrs['__fields__'] = fields\n\t\t#in follow example, id is primary key.\n\t\t#select sql as select `id`, `name`, `gender` from `Users` \n\t\tattrs['__select__'] = 'select `%s`, %s from `%s`' % (primaryKey, ', '.join(escaped_fields), table)\n\t\t#insert sql as insert into `Users` (`name`, `gender`, `id`) values (?, ?, ?)\n\t\t#create_args_string() need to write.\n\t\tattrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (table, ', '.join(escaped_fields), primaryKey, ', '.join(['?' for _ in range(len(escaped_fields)+1)]))\n\t\t#update sql as update `Users` set `name`=?, `gender`=? where `id` = ?\n\t\t#?.replace need to translate by webtodb.execute\n\t\tattrs['__update__'] = 'update `%s` set %s where `%s` = ?' % (table, ', '.join(map(lambda f: '`%s`=?' % (mappings.get(f).name or f), fields)), primaryKey)\n\t\t#delete sql as delete from `Users` where `id`=?\n\t\tattrs['__delete__'] = 'delete from `%s` where `%s`=?' % (table, primaryKey)\n\t\treturn type.__new__(cls, name, bases, attrs)\n\n\n\n#define model for all type of elements\nclass Model(dict, metaclass=ModelMetaclass):\n\n\tdef __init__(self, **kw):\n\t\tsuper(Model, self).__init__(**kw)\n\n\tdef __getattr__(self, key):\n\t\ttry:\n\t\t\treturn self[key]\n\t\texcept KeyError as e:\n\t\t\traise AttributeError(r\"'Model' has no attribute as '%s'\" % key)\n\n\tdef __setattr__(self, key, value):\n\t\tself[key] = value\n\n\tdef getValue(self, key):\n\t\treturn getattr(self, key)\n\n\tdef getValueOrDefault(self, key):\n\t\tvalue = getattr(self, key)\n\t\tif not value:\n\t\t\tfield = self.__mappings__[key]\n\t\t\tif field.default:\n\t\t\t\tvalue = field.default() if callable(field.default) else field.default\n\t\t\t\tlogging.debug('using default value for %s: %s' % (key, str(value)))\n\t\t\t\tsetattr(self, key, value)\n\t\treturn value\n\n\t@classmethod\n\tasync def find(cls, primarykey):\n\t\t#find someone by primary key.\n\t\t#the order of args refer to webtodb.select which is sql, args, size.\n\t\tresult = await select('%s where `%s`=?' % (cls.__select__, cls.__primary_key__), [primarykey], 1)\n\t\tif len(result) == 0:\n\t\t\treturn None\n\t\treturn cls(**rs[0])\n\n#define field, such as str, int, etc.\nclass Field(object):\n\t#When defining subclasses, arguments should be given in the order of the parent class.\n\tdef __init__(self, name, column_type, primary_key, default):\n\t\tself.name = name\n\t\tself.column_type = column_type\n\t\tself.primary_key = primary_key\n\t\tself.default = default\n\n\tdef __str__(self):\n\t\treturn '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)\n\n\nclass StringField(Field):\n\tdef __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'):\n\t\t#this order refer to Field.\n\t\tsuper().__init__(name, ddl, primary_key, default)\n\n\nclass IntField(Field):\n\n\tdef __init__(self, name=None, primary_key=False, default=None, ddl='varchar(50)'):\n\t\t#same as StringField.\n\t\tsuper().__init__(name, ddl, primary_key, default)\n\nclass FloatField(Field):\n\n\tdef __init__(self, name=None, primary_key=False, default=None, ddl='varchar(50)'):\n\t\tsuper().__init__(name, ddl, primary_key, default)\n\nclass TextField(Field):\n\n\tdef __init__(self, name=None, primary_key=False, default=None, ddl='varchar(500)'):\n\t\tsuper().__init__(name, ddl, primary_key, default)\n\n\n\n\n\nif __name__ == '__main__':\n\tpass","sub_path":"src/definemodels.py","file_name":"definemodels.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"311586853","text":"#! /usr/bin/env python\n\nfrom filter_lib import filter_branch\nfrom sys import argv\nfrom dendropy import Tree\n\nfrom os.path import splitext\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-i','--input',required=True,help=\"input file\")\nparser.add_argument('-o','--outfile',required=True,help=\"output file\")\nparser.add_argument('-u','--unit',required=False,help=\"unit-length for unit-based filter\")\nparser.add_argument('-l','--lowthres',required=False,help=\"low threshold\")\nparser.add_argument('-g','--highthres',required=False,help=\"high threshold\")\nparser.add_argument('-f','--factor',required=False,help=\"factor\")\nparser.add_argument('-r','--rootMethod',required=False,help=\"rooting method (MP,MV00,MVDF)\")\n\nargs = vars(parser.parse_args())\n\ninfile = args['input']\noutfile = args['outfile']\na_tree = Tree.get_from_path(infile,\"newick\",preserve_underscores=True)\nunit=args['unit'] if args['unit'] else None\nlow = float(args['lowthres']) if args['lowthres'] else 0\nhigh = float(args['highthres']) if args['highthres'] else 1\nfactor = float(args['factor']) if args['factor'] else 1\nroot=args['rootMethod'] if args['rootMethod'] else None\n\nfilter_branch(a_tree,unit_length=unit,low_percentile=low,high_percentile=high,factor=factor,root_method=root)\n\na_tree.write_to_path(outfile,\"newick\")\n","sub_path":"unrooted_filter.py","file_name":"unrooted_filter.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"631934848","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom random import randint\n\nimport xml.etree.ElementTree as ET\n\nfrom Color import Color\nfrom Money import Money\nfrom Player import Player\nfrom Version import Version\nfrom Resource import Resource\n\nclass Parser:\n def __init__(self, filename_param = \"\", debug = False):\n self.filename = filename_param\n self.debug = debug\n self.game_name = \"\"\n self.game_versions = []\n self.money_name = \"\"\n self.money_number = \"\"\n self.n_min_players = \"\"\n self.n_max_players = \"\"\n self.ressources = []\n self.color_players = []\n self.setup_castle = []\n self.last_neutral_building = \"\"\n self.n_all_except_last_neutral_buildings = []\n self.players = None\n self.phases = [] \n\n #############\n ## Getters ##\n #############\n def getFilename(self):\n return self.filename\n\n def getDebug(self):\n return self.debug\n\n def getGameName(self):\n return self.game_name\n\n def getNMinPlayers(self):\n return self.n_min_players\n\n def getNMaxPlayers(self):\n return self.n_max_players\n\n def getMoneyName(self):\n return self.money_name\n\n def getNaelnd(self):\n return self.n_all_except_last_neutral_buildings\n\n def getPlayersConf(self):\n return self.players\n\n def getPhases(self):\n return self.phases\n\n #############\n ## Setters ##\n #############\n def setFilename(self, new_filename):\n self.filename = new_filename\n\n def setDebug(self, new_debug):\n self.debug = new_debug\n\n ##############################################################\n ## Parsing: parse the filepath stored in filename attribute ##\n ##############################################################\n def parsing(self):\n tree = ET.parse(self.filename)\n root = tree.getroot()\n\n # save variables initialization\n # game_name = \"\"\n # game_versions = []\n # money_name = \"\"\n # money_number = \"\"\n # n_min_players = \"\"\n # n_max_players = \"\"\n # ressources = []\n # color_players = []\n # setup_castle = []\n # last_neutral_building = \"\"\n # n_all_except_last_neutral_buildings = []\n # players = None\n # phases = []\n\n for pb in root.iter():\n \n # game name\n if (pb.tag == \"game_name\"):\n self.game_name = pb.text\n\n # versions\n if (pb.tag == \"versions\"):\n versions_child = pb.getchildren()\n for vc in versions_child:\n if (vc[0].tag == \"name\"):\n self.game_versions.append(vc[0].text)\n\n # money\n if (pb.tag == \"money\"):\n money_child = pb.getchildren()\n for mc in money_child:\n if (mc.tag == \"name\"):\n self.money_name = mc.text\n if (mc.tag == \"number\"):\n self.money_number = mc.text\n\n # min and max players\n if (pb.tag == \"n_min_players\"):\n self.n_min_players = pb.text\n if (pb.tag == \"n_max_players\"):\n self.n_max_players = pb.text\n\n # ressources\n if (pb.tag == \"resources\"):\n ressources_child = pb.getchildren()\n for rc in ressources_child:\n tmp_name_r = \"\"\n tmp_numb_r = \"\"\n for r in rc.iter():\n if (r.tag == \"name\"):\n tmp_name_r = r.text\n if (r.tag == \"number\"):\n tmp_numb_r = r.text\n self.ressources.append((tmp_name_r, tmp_numb_r))\n \n # color players\n if (pb.tag == \"color_players\"):\n color_children = pb.getchildren()\n for cc in color_children:\n if (cc.tag == \"color_player\"):\n self.color_players.append(cc.text)\n\n # setup castle\n if (pb.tag == \"setup_castle\"):\n castle_part = pb.getchildren()\n for cp in castle_part:\n cp_children = cp.getchildren()\n tmp_cp_name = \"\"\n tmp_cp_front_color = \"\"\n tmp_cp_n_prestige_pts = \"\"\n tmp_n_pre_tokens = []\n for cpc in cp_children:\n if (cpc.tag == \"name\"):\n tmp_cp_name = cpc.text\n if (cpc.tag == \"front_color\"):\n tmp_cp_front_color = cpc.text\n if (cpc.tag == \"n_prestige_pts\"):\n tmp_cp_n_prestige_pts = cpc.text\n if (cpc.tag == \"n_castle_tokens\"):\n castle_tokens = cpc.getchildren()\n for ct in castle_tokens:\n tmp_n_pre_tokens.append((ct.tag, ct.text))\n self.setup_castle.append((tmp_cp_name, tmp_cp_front_color, tmp_cp_n_prestige_pts, tmp_n_pre_tokens))\n\n # setup road\n if (pb.tag == \"setup_road\"):\n road_children = pb.getchildren()\n for rc in road_children:\n if (rc.tag == \"last_neutral_building\"):\n self.last_neutral_building = rc.text\n if (rc.tag == \"n_all_except_last_neutral_buildings\"):\n naelnd_children = rc.getchildren()\n for naelndc in naelnd_children:\n self.n_all_except_last_neutral_buildings.append((naelndc.tag, naelndc.text))\n\n #setup player\n if (pb.tag == \"setup_player\"):\n player_children = pb.getchildren()\n n_cards_in_hand = \"\"\n n_possibilities_to_discard_cards = \"\"\n n_workers = \"\"\n n_deniers = \"\"\n n_food_cubes = \"\"\n n_wood_cubes = \"\"\n n_stone_cubes = \"\"\n n_gold_cubes = \"\"\n n_prestige_pts = \"\"\n for pc in player_children:\n if (pc.tag == \"n_cards_in_hand\"):\n n_cards_in_hand = pc.text\n if (pc.tag == \"n_possibilities_to_discard_cards\"):\n n_possibilities_to_discard_cards = pc.text\n if (pc.tag == \"n_workers\"):\n n_workers = pc.text\n if (pc.tag == \"n_deniers\"):\n n_deniers = pc.text\n if (pc.tag == \"n_food_cubes\"):\n n_food_cubes = pc.text\n if (pc.tag == \"n_wood_cubes\"):\n n_wood_cubes = pc.text\n if (pc.tag == \"n_stone_cubes\"):\n n_stone_cubes = pc.text\n if (pc.tag == \"n_gold_cubes\"):\n n_gold_cubes = pc.text\n if (pc.tag == \"n_prestige_pts\"):\n n_prestige_pts = pc.text\n\n self.players = (n_cards_in_hand, n_possibilities_to_discard_cards,\n n_workers, n_deniers, n_food_cubes, n_wood_cubes, n_stone_cubes,\n n_gold_cubes, n_prestige_pts)\n\n # phases\n if (pb.tag == \"phases\"):\n phases_children = pb.getchildren()\n for phc in phases_children:\n phases_details = phc.getchildren()\n tmp_begin_vers = \"\"\n tmp_numero = \"\"\n tmp_name_ph = \"\"\n for phd in phases_details:\n if (phd.tag == \"belongs_to_beginner_version\"):\n tmp_begin_vers = phd.text\n if (phd.tag == \"numero\"):\n tmp_numero = phd.text\n if (phd.tag == \"name\"):\n tmp_name_ph = phd.text\n self.phases.append((tmp_begin_vers, tmp_numero, tmp_name_ph))\n\n # DEBUG print\n if (self.debug == True):\n print(\"game_name = \" + self.game_name)\n print(\"game_versions = \", self.game_versions)\n print(\"money_name = \" + self.money_name)\n print(\"money_number = \" + self.money_number)\n print(\"n_min_players = \" + self.n_min_players)\n print(\"n_max_players = \" + self.n_max_players)\n print(\"ressources = \", self.ressources)\n print(\"color players = \", self.color_players)\n print(\"setup castle = \", self.setup_castle)\n print(\"last_neutral_building = \", self.last_neutral_building)\n print(\"n_all_except_last_neutral_buildings = \", self.n_all_except_last_neutral_buildings)\n print(\"players = \", self.players)\n print(\"phases = \", self.phases)\n\n ########################\n ## Objects generation ##\n ########################\n def generate_ressources(self):\n ressources = []\n for name,number in self.ressources:\n if len(name) <= 0:\n continue\n ressources.append(Resource(name, int(number)))\n return ressources\n\n def generate_money(self):\n return Money(self.money_name, int(self.money_number)) if len(self.money_name) > 0 else None\n\n def generate_versions(self):\n versions = []\n for v in self.game_versions:\n versions.append(Version(v))\n return versions\n\n def generate_pcolors(self):\n pcolors = []\n for c in self.color_players:\n pcolors.append(Color(c))\n return pcolors\n\n def generate_players(self, nb, pcolors_array, h_color):\n if (nb > len(pcolors_array)):\n print(\"bad player number\")\n sys.exit()\n\n # players = ('3', '1', '4', '4', '2', '2', '0', '0', '0')\n # self.players = (n_cards_in_hand, n_possibilities_to_discard_cards, n_workers, n_deniers, n_food_cubes, n_wood_cubes, n_stone_cubes, n_gold_cubes, n_prestige_pts)\n players = []\n human_ok = False\n # human = randint(0,nb-1)\n for i in range(0, nb):\n # print(\"i = \" + str(i) + \" / pcolors list len = \" + str(len(pcolors_array)))\n # if i == human:\n if pcolors_array[i].getName().lower() == h_color.lower():\n human_ok = True\n players.append(Player(pcolors_array[i],\n int(self.players[8]),\n int(self.players[2]),\n int(self.players[0]),\n Money(self.money_name, int(self.players[3])),\n True,\n []\n ))\n else:\n players.append(Player(pcolors_array[i],\n int(self.players[8]),\n int(self.players[2]),\n int(self.players[0]),\n Money(self.money_name, int(self.players[3])),\n False,\n []\n ))\n\n if human_ok == False:\n print(\"Color specified in parameters doesn't exist in XML file\")\n sys.exit()\n return players","sub_path":"src/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":11547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"440792074","text":"import time\nimport numpy as np\nimport argparse\n\nfrom ledPixels import *\n\nnPix = 43\nspeed = 4\n\n# get number of pixels from the command line\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-f\", \"--freq\", default=1, type=float, help = \"Frequency\")\nparser.add_argument(\"-p\", \"--phase\", default=0, type=float, help = \"Phase\")\nparser.add_argument(\"-c\", \"--color\", default=\"(0,20,0)\", type=str, help = \"Color: 3 values, comma separated. E.g.: 20,0,0\")\nparser.add_argument(\"-o\", \"--offset\", default=0, type=float, help = \"Offset: Scales result somewhat. Best from 0 and 1\")\n\nargs = parser.parse_args()\n\ncolor = args.color\ncolor = color.strip()\ncolor = color.replace(\" \",\"\")\ncolor = color.split(\",\")\nr = float(color[0])\ng = float(color[1])\nb = float(color[2])\ncolor = (r, g, b)\nprint(\"freq:\", args.freq)\nprint(\"phase:\", args.phase)\nprint(\"color:\", color)\nprint(\"offset:\", args.offset)\n\n\nledPix = ledPixels(nPix, board.D18)\nphase = 0.0\n#for phase in np.arange(0, 2*np.pi, 0.01):\nledPix.sinFunc(args.freq,args.phase,color, args.offset)\nledPix.sinFunc(1,np.pi,(20,0,0), 0)\nledPix.pixels.show()\n","sub_path":"pyLED/sin/sinTestSup.py","file_name":"sinTestSup.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"198101101","text":"#!/usr/bin/env python\n\"\"\"\n\n DESCRIPTION\n Extract a single lat/lon from a RACMO file with rotated grid\n\n assume that the data is layed out as follows:\n double lon(rlat, rlon) ;\n double lat(rlat, rlon) ;\n float tskin(time, height, rlat, rlon) ;\n we would like to select the rlat/rlon associated to given lat/lon\n requires cdo and nco to be installed\n\n AUTHOR\n L.vankampenhout@uu.nl\n\n DATE\n 2016/01/14\n\n\"\"\"\nimport numpy as np\nimport math as math\nimport netCDF4 as netcdf4\nimport subprocess as sp\n\nmy_lat = -90.\nmy_lon = 0.\n\n\nifile='tskin.KNMI-2011.ANT27.ERAIN_r490.6H.nc'\nofile='tskin.SouthPole-2013.ANT27.ERAIN_r490.6H.nc'\n\nf1 = netcdf4.Dataset(ifile, 'r', format='NETCDF4')\n\nlat = np.asarray(f1.variables['lat'])\nlon = np.asarray(f1.variables['lon'])\n\nnrlat = np.shape(lat)[0]\nnrlon = np.shape(lat)[1]\n\nmindist = 1e5\nfor rlat in range(0,nrlat):\n for rlon in range(0,nrlon):\n dist = math.sqrt(math.pow(lat[rlat,rlon]-my_lat,2) + math.pow(lon[rlat,rlon]-my_lon,2))\n if dist < mindist:\n mindist = dist\n idx1 = rlat\n idx2 = rlon\n\n#print(np.min(lat))\n#print(np.min(lon))\n\n\n#idx1 = np.abs(lat-my_lat).argmin() # find rlat index\n#print(idx1)\n#idx2 = np.abs(lon[:,0]-my_lon).argmin() # find rlon index\n\nprint(\"requested lat = \"+str(my_lat)+\", closest lat = \"+str(lat[idx1,idx2]))\nprint(\"requested lon = \"+str(my_lon)+\", closest lon = \"+str(lon[idx1,idx2]))\n#print(idx1)\n#print(idx2)\nmy_rlat = f1.variables['rlat'][idx1]\nmy_rlon = f1.variables['rlon'][idx2]\nprint('rlat='+str(my_rlat))\nprint('rlon='+str(my_rlon))\n\neps = 1e-2\narg = ['ncea']\narg.extend(['-d','rlat,'+str(my_rlat-eps)+','+str(my_rlat+eps)])\narg.extend(['-d','rlon,'+str(my_rlon-eps)+','+str(my_rlon+eps)])\narg.append(ifile)\narg.append('tmp1.nc')\nsp.check_call(arg)\n\narg = ['cdo']\narg.extend(['selyear,2011','tmp1.nc',ofile])\nsp.check_call(arg)\n\narg = ['rm','tmp1.nc']\nsp.check_call(arg)\n\n","sub_path":"extract_lonlat.py","file_name":"extract_lonlat.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"404612820","text":"import builtins\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n isna,\n)\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize(\"agg_func\", [\"any\", \"all\"])\n@pytest.mark.parametrize(\"skipna\", [True, False])\n@pytest.mark.parametrize(\n \"vals\",\n [\n [\"foo\", \"bar\", \"baz\"],\n [\"foo\", \"\", \"\"],\n [\"\", \"\", \"\"],\n [1, 2, 3],\n [1, 0, 0],\n [0, 0, 0],\n [1.0, 2.0, 3.0],\n [1.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [True, True, True],\n [True, False, False],\n [False, False, False],\n [np.nan, np.nan, np.nan],\n ],\n)\ndef test_groupby_bool_aggs(agg_func, skipna, vals):\n df = DataFrame({\"key\": [\"a\"] * 3 + [\"b\"] * 3, \"val\": vals * 2})\n\n # Figure out expectation using Python builtin\n exp = getattr(builtins, agg_func)(vals)\n\n # edge case for missing data with skipna and 'any'\n if skipna and all(isna(vals)) and agg_func == \"any\":\n exp = False\n\n exp_df = DataFrame([exp] * 2, columns=[\"val\"], index=Index([\"a\", \"b\"], name=\"key\"))\n result = getattr(df.groupby(\"key\"), agg_func)(skipna=skipna)\n tm.assert_frame_equal(result, exp_df)\n\n\ndef test_any():\n df = DataFrame(\n [[1, 2, \"foo\"], [1, np.nan, \"bar\"], [3, np.nan, \"baz\"]],\n columns=[\"A\", \"B\", \"C\"],\n )\n expected = DataFrame(\n [[True, True], [False, True]], columns=[\"B\", \"C\"], index=[1, 3]\n )\n expected.index.name = \"A\"\n result = df.groupby(\"A\").any()\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"bool_agg_func\", [\"any\", \"all\"])\ndef test_bool_aggs_dup_column_labels(bool_agg_func):\n # 21668\n df = DataFrame([[True, True]], columns=[\"a\", \"a\"])\n grp_by = df.groupby([0])\n result = getattr(grp_by, bool_agg_func)()\n\n expected = df\n tm.assert_frame_equal(result, expected)\n","sub_path":"pandas/tests/groupby/test_any_all.py","file_name":"test_any_all.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"378820359","text":"from classes import Room, Item, Weapon, Food, Creature, Player\nimport random\n\n\n#-----------ITEMS----------------------------\necho = Item(\"echo\", \"an amazon echo, it se\")\necho_dot = Item(\"echo dot\", \"an amazon echo\")\necho_show = Item()\nbutton = Item()\npaper = Item()\nkindle = Item()\ncomputer = Item()\ntorch = Item()\ntree = Item()\ngloves = Item()\nclimbing_shoes = Item()\nbody = Item()\nrock = Item()\ncar = Item()\nbackpack = Item()\nmacbook = Item()\nhollowed_tree = Item()\n\n\n\n\n#----------WEAPONS----------------------------\nsword = Weapon()\nknife = Weapon()\nmachete = Weapon()\npistol = Weapon()\nrifle = Weapon()\n\n\n\n\n#---------FOOD--------------------------------\nchocolate = Food()\nnoodles = Food()\nbanana = Food()\napple = Food()\nenergy_drink = Food()\ncoffee = Food()\nbeer = Food()\nwater = Food()\npizza = Food()\navocado = Food()\nmedicine = Food()\n\n\n\n#--------CREATURES----------------------------\nmutant = Creature()\ndrone = Creature()\ncyborg_jeff_bezos = Creature()\n\n\n\n\ninitItems = [echo, echo_dot, echo_show, button, switch, keypad, paper, kindle, computer, torch, medicine]\n\ninitWeapons = [sword, knife, machete, pistol, rifle]\n\ninitFood = [chocolate, noodles, banana, apple, energy_drink, coffee, beer, water]\n\ninitCreatures = [mutant, drone, cyborg_jeff_bezos]\n\n\n\ndef generate_creatures():\n creatures = []\n i = random.randint(0,3)\n if i == 2:\n creatures.append(mutant)\n elif i == 3:\n creatures.append(drone)\n return creatures\n \n\n\n\n\n#------------REGION 1: THE JUNGLE------------\nwarehouse = Room(\"Warehouse\", [0,0,0], [], \"\"\"You are in what appears to be a large abandoned amazon fulfilment centre. \n Rows of shelves stretch along the warehouse. The floor is littered with long-dead package retrieval robots.\n There is no sound, and almost no light, save for a faint glow from a large green message scrawled\n on the north wall. The message reads: if you seek answers, journey north and find headquarters. \n Under the text, you can see a door, slightly ajar. There do not appear to be any other exits\"\"\", [shelves, boxes, torch], True)\n \njungle_SW = Room(\"Southwest Jungle\",[0,1,0],\"\",[machete], [], False)\n#machete is needed to cut through from jungle into forest\n\njungle_SE = Room(\"Southeast Jungle\",[1,1,0],\"\",[tree, rope], [], False)\n#tree can be used as a vantage point to see the next area\n\njungle_NE = Room(\"Northeast Jungle\",[1,2,0],\"\",[pistol], generate_creatures(), False)\n#pistol is a weapon\n\njungle_NW = Room(\"Northwest Jungle\",[0,2,0],\"\",[body, coat, medicine], generate_creatures(), False)\n#coat is needed to survive in the northern half of the forest\n\n\n#-----------REGION 2: THE FOREST-------------\nforest_SW = Room(\"Southwest Forest\",[0,3,0],\"\",[kindle], generate_creatures(), False)\n\nforest_SE = Room(\"Southeast Forest\",[1,3,0],\"\",[gloves], generate_creatures(), False)\n#gloves are needed to protect fingers from frostbite in the mountain region\n\nforest_NE = Room(\"Northeast Forest\",[1,4,0],\"\",[echo_dot], generate_creatures(), False)\n\nforest_NW = Room(\"Northwest Forest\",[0,4,0],\"\",[hollowed_tree, climbing_shoes], generate_creatures(), False)\n#climbing shoes are needed to move from south mountain area to north mountain area\n\n\n#-----------REGION 3: THE MOUNTAINS----------\nmountains_SW = Room(\"Southwest Mountains\",[2,4,0],\"\",[body, paper], generate_creatures(), False)\n#paper has code needed to gain entry to the headquarters later on\n\nmountains_SE = Room(\"Southeast Mountains\",[3,4,0],\"\",[coffee], generate_creatures(), False)\n#rope is needed to climb down the mountains to the city\n\nmountains_NE = Room(\"Northeast Mountains\",[3,5,0],\"\",[], generate_creatures(), False)\n\nmountains_NW = Room(\"Northwest Mountains\",[2,5,0],\"\",[rock, rifle], generate_creatures(), False)\n\n\n#-----------REGION 4: THE CITY--------------\ncity_SW = Room(\"Southwest City\",[3,6,0],\"\",[body, kindle, chocolate], generate_creatures(), False)\n\ncity_SE = Room(\"Southeast City\",[4,6,0],\"\",[car, echo], generate_creatures(), False)\n\ncity_NE = Room(\"Northeast City\",[4,7,0],\"\",[backpack, macbook], generate_creatures(), False)\n#keypad is used to access headquarters\n\ncity_NW = Room(\"Northwest City\",[3,7,0],\"\",[water], generate_creatures(), False)\n\n\n#-----------REGION 5: HEADQUARTERS----------\nreception = Room(\"Headquarters Reception\",[4,8,0],\"\",[desk, computer], [drone], True)\n\nfood_court = Room(\"Headquarters Food Court\", [4,8,1], \"\", [beer, pizza], [drone], True)\n\nroof_garden = Room(\"Headquarters Roof Garden\", [4,8,2], \"\", [], [cyborg_jeff_bezos], True)\n\n\n\n\n \n\n\n\n\ninitRooms = [\n warehouse,\n jungle_SW, jungle_SE, jungle_NE, jungle_NW,\n forest_SW, forest_SE, forest_NE, forest_NW,\n mountains_SW, mountains_SE, mountains_NE, mountains_NW,\n city_SW, city_SE, city_NE, city_NW,\n reception, food_court, roof_garden\n]\n\n\n\n","sub_path":".~c9_invoke_NF92h2.py","file_name":".~c9_invoke_NF92h2.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"198113686","text":"# Copyright (c) 2009 Andrew Wilkins \n# \n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use,\n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n# \n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n\n__all__ = [\"ImpacketPopen\"]\n\nimport impacket.smb\n\nclass PushySMB(impacket.smb.SMB):\n def __init__(self, *args, **kwargs):\n impacket.smb.SMB.__init__(self, *args, **kwargs)\n\nclass SMBFile:\n def __init__(self, server, tid, fid):\n self.__lock = threading.Lock()\n self.__server = server\n self.__tid = tid\n self.__fid = fid\n\n def __del__(self):\n self.close()\n\n def flush(self):\n pass\n\n def close(self):\n if self.__server is not None:\n self.__lock.acquire()\n try:\n if self.__server is not None:\n self.__server.close(self.__tid, self.__fid)\n self.__server = None\n finally:\n self.__lock.release()\n\n def write(self, data):\n self.__lock.acquire()\n try:\n self.__server.write_raw(self.__tid, self.__fid, data)\n finally:\n self.__lock.release()\n\n def read(self, size):\n self.__lock.acquire()\n try:\n data = self.__server.read(self.__tid, self.__fid, 0, size)\n if data is None:\n data = \"\"\n return data\n finally:\n self.__lock.release()\n\n def readlines(self):\n data = \"\"\n p = self.read(8192)\n while len(p):\n data += p\n p = self.read(8192)\n return data.splitlines()\n\nclass ImpacketPopen:\n \"\"\"\n SMB transport implementation which uses Impacket for connecting to a\n remote named pipe.\n \"\"\"\n\n def __init__(self, hostname, username, password, domain):\n \"\"\"\n @param hostname: The hostname of the target machine.\n @param username: The username to authenticate with.\n @param password: The password to authenticate with.\n @param domain: The domain to authenticate with.\n \"\"\"\n\n # Create SMB connection, authenticate user.\n # TODO make port configurable\n server = PushySMB(\"*SMBSERVER\", hostname)\n server.login(username, password, domain)\n\n # Connect to IPC$ share.\n tid_ipc = server.tree_connect_andx(r\"\\\\*SMBSERVER\\IPC$\")\n\n # Open Pushy service's named pipes.\n fid = server.open(tid_ipc, r\"\\pipe\\pushy\",\n impacket.smb.SMB_O_OPEN,\n impacket.smb.SMB_ACCESS_READWRITE)[0]\n\n # Create file-like objects for stdin/stdout/stderr.\n self.stdin = SMBFile(server, tid_ipc, fid)\n self.stdout = self.stdin\n self.server = server\n\n def close(self):\n self.stdin.close()\n self.stdout.close()\n\n","sub_path":"pushy/transport/smb/impacket_transport.py","file_name":"impacket_transport.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"97316813","text":"# Copyright (c) 2009-2010 Six Apart Ltd.\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 are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of Six Apart Ltd. nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport os.path\nfrom django.conf.urls.defaults import *\n\napp_path = os.path.dirname(__file__)\nmedia_dir = os.path.join(app_path, 'static')\n\nhandler500 = 'typepadapp.views.exception.server_error'\nhandler404 = 'typepadapp.views.exception.page_not_found'\n\n# auth pages\nurlpatterns = patterns('typepadapp.views.auth',\n url(r'^login/?$', 'login', name='login'),\n url(r'^register/?$', 'register', name='register'),\n url(r'^authorize/?$', 'authorize', name='authorize'),\n url(r'^logout/?$', 'logout', name='logout'),\n url(r'^synchronize/?$', 'synchronize', name='synchronize'),\n)\n\nurlpatterns += patterns('typepadapp.views.admin',\n url(r'^admin/export/members/?$', 'export_members', name='export_members'),\n)\n\nurlpatterns += patterns('typepadapp.views.feedsub',\n url(r'^feedsub/callback/(?P.*)$', 'callback', name='callback'),\n)\n\nurlpatterns += patterns('',\n url(r'^static/typepadapp/(?P.*)/?$', 'django.views.static.serve',\n kwargs={ 'document_root': media_dir }),\n)\n","sub_path":"typepadapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"651368806","text":"def collision_prob(numBuckets, numInsertions):\n '''\n Given the number of buckets and the number of items to insert, \n calculates the probability of a collision.\n '''\n prob = 1.0\n for i in range(1, numInsertions):\n prob = prob * ((numBuckets - i) / float(numBuckets))\n return 1 - prob\n \ndef largest_noncol(y):\n x = 365\n while collision_prob(x, y) > 0.99:\n y -= 1\n return y","sub_path":"lect3_prob5.py","file_name":"lect3_prob5.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"61937941","text":"\"\"\" Factory function(s) for spheres \"\"\"\n\nfrom dipy.data import get_sphere\n\ndef sphere_vf_from(input):\n \"\"\" Return sphere vertices and faces from a variety of inputs\n\n Parameters\n ----------\n input : str or tuple or dict\n * str - a named sphere from dipy.data.get_sphere\n * tuple - the vertex, face tuple all ready to go\n * dict - with keys 'vertices', 'faces'\n\n Returns\n -------\n vertices : ndarray\n N,3 ndarray of sphere vertex coordinates\n faces : ndarray\n Indices into `vertices`\n \"\"\"\n if hasattr(input, 'keys'):\n return input['vertices'], input['faces']\n if isinstance(input, basestring):\n return get_sphere(input)\n return input\n","sub_path":"dipy/utils/spheremakers.py","file_name":"spheremakers.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"147150458","text":"# coding=utf-8\nimport requests\n\nfrom pychroner import PluginMeta, PluginType\n\n@PluginMeta(PluginType.Schedule, multipleMinute=30)\ndef do(pluginApi):\n with open(f\"{pluginApi.dirs.api}/nicolive_closed.json\", \"w\") as f:\n f.write(requests.get(\n \"http://live.nicovideo.jp/api/getindexstreamlist?status=closed&zpage=1\"\n ).text)\n","sub_path":"plugins/Information/NicoliveClosed.py","file_name":"NicoliveClosed.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"632752028","text":"import json\nimport time\nimport threading \nimport requests\nimport datetime\n\nfrom logger import log\nfrom eosrpcexecutor import EOSRPCExecutor\n\nclass TestScenarios(object):\n def __init__(self, _nodeos_addres, _nodeos_port, _wallet_address, _wallet_port, _scenarios_file_name, _append_start_block, _master_wallet_name):\n self.append_block_numbers = _append_start_block\n self.summary_file = \"Scenarios_summary_\"+str(datetime.datetime.now())[:-7]\n self.scenarios_file = _scenarios_file_name\n self.actions = []\n self.after_block = {}\n self.scenarios = None\n self.scenariosNr = None\n self.blockNumber = 0\n self.join_block_number = 0\n self.after_block_result = {}\n self.called_actions_result = {}\n self.scenarios_status_summary = {}\n self.eos_rpc = EOSRPCExecutor(_nodeos_addres, _nodeos_port, _wallet_address, _wallet_port, _master_wallet_name)\n self.load_scenarios()\n\n self.blockGetter = threading.Thread(target=self.block_id_getter)\n self.blockGetter.setDaemon(daemonic=True)\n self.user_status_getter = threading.Thread(target=self.check_user_status_after_block)\n self.user_status_getter.setDaemon(daemonic=True)\n self.runScenarios = threading.Event()\n self.runScenarios.set()\n self.askForBlockNumber = threading.Event()\n self.blockGetter.start()\n self.user_status_getter.start()\n \n\n def __iter__(self):\n return self\n\n \n def __next__(self):\n if self.scenariosNr == None:\n self.scenariosNr = 0\n else:\n self.scenariosNr += 1\n if self.scenariosNr == len(self.scenarios):\n raise StopIteration\n return self\n\n\n def get_current_scenario(self):\n if self.scenarios:\n return self.scenarios[self.scenariosNr][\"name\"]\n else:\n return \"Scenarios was not even inited.\"\n\n \n def block_id_getter(self):\n try:\n while self.runScenarios.is_set():\n while self.askForBlockNumber.is_set():\n blockNumber = self.eos_rpc.get_info()\n self.blockNumber = int(blockNumber[\"head_block_num\"])\n time.sleep(0.25)\n self.blockNumber = 0\n except Exception as _ex:\n log.exception(\"Exception `%s` while getting block id.\"%(str(_ex)))\n self.stop_scenarios()\n exit(1)\n\n\n def load_scenarios(self):\n try:\n with open(self.scenarios_file) as scenarios:\n self.scenarios = json.load(scenarios)[\"scenarios\"]\n except Exception as _ex:\n log.exception(\"Exception `%s` while loading scenarios \"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def comare_expected_messages(self, _expected_result, _details ):\n same_status = False\n same_message = False\n expected_status = _expected_result[\"status\"]\n #at this level, only errors have messages\n if \"message\" in _expected_result:\n if expected_status == False:\n same_status = True\n else:\n if expected_status == True:\n same_status = True\n\n expected_messag = _expected_result[\"message\"] if \"message\" in _expected_result else \"\"\n if expected_messag:\n for detail in _details:\n msg = detail[\"message\"]\n if expected_messag.lower() in msg.lower():\n same_message = True\n break\n else:\n same_message = True\n\n return (same_status, same_message, expected_messag)\n\n\n def get_action_calls_summary(self, _file):\n try:\n actions = self.eos_rpc.get_actions_call_summary()\n _file.writelines(\"[INFO] CHECKING ACTION CALL SUMMARY \\n\")\n error = False\n for action in actions:\n act = action[0]\n expected = action[1]\n status = action[2]\n if not isinstance(status, bool):\n same_status, same_message, message = self.comare_expected_messages(expected, status)\n if same_status:\n if same_message:\n _file.writelines(\"[OK] action `%s` status call `%d` and message `%s` are as expected.\"%(act, expected[\"status\"], message))\n else:\n _file.writelines(\"[ERROR] action `%s` status call is as expected `%d` but message `%s` is not.\"%(act, expected[\"status\"], message))\n error = True\n else:\n if same_message:\n _file.writelines(\"[ERROR] action `%s` status call `%d` is not as expected `%d` but message `%s` is.\"%(act, not expected[\"status\"],expected[\"status\"], message))\n error = True\n else:\n _file.writelines(\"[ERROR] action `%s` status call `%d` is not as expected `%d` as well as `%s`.\"%(act,not expected[\"status\"], expected[\"status\"], message))\n error = True\n else:\n if expected[\"status\"] == status:\n _file.writelines(\"[OK] action `%s` status call is as expected `%d`.\"%(act, expected[\"status\"]))\n else:\n _file.writelines(\"[ERROR] action `%s` status call `%d` is not as expected `%d`.\"%(act, status ,expected[\"status\"]))\n error = True\n _file.writelines('\\n')\n _file.writelines(\"###################################\\n\")\n self.eos_rpc.clear_actions_call_summary()\n return error\n except Exception as _ex:\n log.exception(\"Exception `%s` while getting scenarios action calls summary\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def get_at_end_summary(self, _file, _symbol):\n try:\n expected_result_for_user = self.scenarios[self.scenariosNr][\"expected_results\"]\n error = False\n for expected in expected_result_for_user:\n user = expected[\"user\"]\n balance = self.eos_rpc.get_currency_balance(user, _symbol)\n result = self.eos_rpc.get_account(user)\n voter_info = result[\"voter_info\"] if \"voter_info\" in result else None\n total_resources = result[\"total_resources\"] if \"total_resources\" in result else None\n total_resources[\"core_liquid_balance\"] = result[\"core_liquid_balance\"] if \"core_liquid_balance\" in result else \"\"\n total_resources[\"balance\"]=balance[\"balance\"]\n at_end = expected[\"at_end\"] if \"at_end\" in expected else None\n if total_resources and at_end:\n _file.writelines(\"[INFO] CHECKING `AT END` VALUES FOR ACCOUNT %s\\n\"%(user))\n for key, value in at_end[\"resources\"].items():\n if at_end[\"resources\"][key] == total_resources[key]:\n _file.writelines(\"[OK] VALUE FOR `%s` IS AS EXPECTED %s\\n\"%(key, value))\n else:\n _file.writelines(\"[ERROR] VALUE `%s` FOR `%s` DOES NOT MATCH EXPECTED ONE `%s`\\n\"%( total_resources[key], key, at_end[\"resources\"][key]))\n error = True\n if voter_info and \"voter_info\" in at_end:\n for key, value in at_end[\"voter_info\"].items():\n if at_end[\"voter_info\"][key] == voter_info[key]:\n _file.writelines(\"[OK] VALUE FOR `%s` IS AS EXPECTED `%s`\\n\"%(key, value))\n else:\n _file.writelines(\"[ERROR] VALUE `%s` FOR `%s` DOES NOT MATCH EXPECTED ONE `%s`\\n\"%( voter_info[key], key, at_end[\"voter_info\"][key]))\n error = True\n else:\n if not total_resources and not at_end:\n _file.writelines(\"[OK] BOTH `AT_END` AND `TOTAL_RESOURCES` ARE NOT AVAILABLE FOR `%s` \\n\"%(user))\n if total_resources:\n error = True\n _file.writelines(\"[ERROR] `AT_END` IS NOT DEFINED FOR USER `%s` WHILE `TOTAL_RESOURCES` IS AVAILABLE\\n\"%(user))\n if at_end:\n error = True\n _file.writelines(\"[ERROR] `TOTAL_RESOURCES` IS NOT DEFINED FOR USER `%s` WHILE `AT_END` IS AVAILABLE\\n\"%(user))\n\n if not error:\n _file.writelines(\"[OK] ALL VALUES FOR `%s` ARE OK\\n\"%(user))\n _file.writelines(\"###################################\\n\")\n return error\n except Exception as _ex:\n log.exception(\"Exception `%s` while getting scenarios end summary\"%str(_ex))\n self.stop_scenarios()\n exit(1) \n\n\n def get_after_block_summary(self, _file):\n try:\n error = False\n expected_result_for_user = self.scenarios[self.scenariosNr][\"expected_results\"]\n for expected in expected_result_for_user:\n user = expected[\"user\"]\n if \"after_block\" in expected:\n _file.writelines(\"[INFO] CHECKING `AFTER BLOCKS` VALUES FOR ACCOUNT %s\\n\"%(user))\n for expected_after_block in expected[\"after_block\"]:\n _file.writelines(\"###################################\\n\")\n _file.writelines(\"[INFO] CHECKING VALUES FOR `AFTER BLOCK` %d (%d)\\n\"%(expected_after_block[\"after_block\"],expected_after_block[\"after_block\"]+self.join_block_number))\n _file.writelines(\"###################################\\n\")\n for actual_after_block in self.after_block_result[user]:\n if expected_after_block[\"after_block\"] == actual_after_block[\"after_block\"]:\n log.info(\"expected_after_block %s\"%expected_after_block)\n log.info(\"actual_after_block %s\"%actual_after_block)\n for key, value in expected_after_block[\"resources\"].items():\n if actual_after_block[\"resources\"][key] == expected_after_block[\"resources\"][key]:\n _file.writelines(\"[OK] VALUE FOR `%s` IS AS EXPECTED `%s`\\n\"%(key,value))\n else:\n _file.writelines(\"[ERROR] VALUE `%s` FOR `%s` DOES NOT MATCH EXPECTED ONE `%s`\\n\"%( actual_after_block[\"resources\"][key], key, expected_after_block[\"resources\"][key]))\n error = True\n if \"voter_info\" in expected_after_block and \"voter_info\" in actual_after_block:\n for key, value in expected_after_block[\"voter_info\"].items():\n if actual_after_block[\"voter_info\"][key] == expected_after_block[\"voter_info\"][key]:\n _file.writelines(\"[OK] VALUE FOR `%s` IS AS EXPECTED `%s`\\n\"%(key,value))\n else:\n _file.writelines(\"[ERROR] VALUE `%s` FOR `%s` DOES NOT MATCH EXPECTED ONE `%s`\\n\"%( actual_after_block[\"voter_info\"][key], key, expected_after_block[\"voter_info\"][key]))\n error = True\n\n _file.writelines(\"###################################\\n\")\n self.after_block.clear()\n self.after_block_result.clear()\n return error\n except Exception as _ex:\n log.exception(\"Exception `%s` while getting scenarios after block summary\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def get_scenario_summary(self, _symbol=\"BTS\"):\n try:\n self.askForBlockNumber.clear()\n with open(self.summary_file,\"a+\") as sf:\n scenario_name = self.scenarios[self.scenariosNr][\"name\"]\n sf.writelines(\"[SCENARIO] :%s\\n\"%(scenario_name))\n sf.writelines(\"############# SUMMARY #############\\n\")\n actions_error = self.get_action_calls_summary(sf)\n after_block_error = self.get_after_block_summary(sf)\n at_end_error = self.get_at_end_summary(sf, _symbol)\n if actions_error or after_block_error or at_end_error:\n self.scenarios_status_summary[scenario_name] = False\n return True\n else :\n self.scenarios_status_summary[scenario_name] = True\n return False\n except Exception as _ex:\n log.exception(\"Exception `%s` while getting scenarios summary\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def add_scenario_status_to_summary_file(self):\n try:\n with open(self.summary_file,\"a+\") as sf:\n temp_len_scen = len(\" Scenario name \") \n max_scenario_name = max(len(name) for name in self.scenarios_status_summary )\n sf.writelines(\" Scenario name \" + (max_scenario_name-temp_len_scen)*' ' + \"| status \\n\")\n sf.writelines( max_scenario_name*'-' + '|' + len(\"+ status \")*'-' +'\\n')\n for scenario, status in self.scenarios_status_summary.items():\n log_status = \"| {0}\".format(\"OK\" if status else \"ERROR\")\n sf.writelines(scenario + (max_scenario_name-len(scenario))*' ' + log_status + '\\n')\n except Exception as _ex:\n log.exception(\"Exception `%s` while adding scenarios status to summary file.\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def wait_for_end(self):\n scenario_block = self.scenarios[self.scenariosNr][\"scenario_blocks\"]\n log.info(\"This scenario wait till blocks %d\"%(scenario_block+self.join_block_number))\n while (scenario_block + self.join_block_number) >= self.blockNumber:\n time.sleep(0.5)\n if not self.askForBlockNumber.is_set():\n break\n\n\n def set_scenario_params(self):\n try:\n scenario_params = self.scenarios[self.scenariosNr][\"params\"]\n nr = self.join_block_number if self.join_block_number != None else 0\n params=list()\n params.append({\n \"authorized_by\":\"beos.init\",\n \"code\":\"beos.init\",\n \"action\":\"changeparams\",\n \"args\":{\n \"new_params\":[\"0.0000 BTS\", scenario_params[\"starting_block_for_initial_witness_election\"]+nr]\n }\n })\n params.append({\n \"authorized_by\":\"beos.distrib\",\n \"code\":\"beos.distrib\",\n \"action\":\"changeparams\",\n \"args\":{\n \"new_params\":[\n [ scenario_params[\"starting_block_for_beos_distribution\"]+nr,\n 0,\n scenario_params[\"ending_block_for_beos_distribution\"]+nr,\n scenario_params[\"distribution_payment_block_interval_for_beos_distribution\"],\n scenario_params[\"trustee_reward_beos\"] ],\n [ scenario_params[\"starting_block_for_ram_distribution\"]+nr,\n 0,\n scenario_params[\"ending_block_for_ram_distribution\"]+nr,\n scenario_params[\"distribution_payment_block_interval_for_ram_distribution\"],\n scenario_params[\"trustee_reward_ram\"] ],\n scenario_params[\"distrib_ram_leftover\"]\n ]\n }\n })\n self.eos_rpc.prepare_and_push_transaction(params)\n except Exception as _ex:\n log.exception(\"Exception `%s` while setting scenarios params\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def make_scenario_actions(self):\n try:\n self.set_scenario_params()\n return self.execute_scenatio_actions()\n except Exception as _ex:\n log.exception(\"Exception `%s` while making scenarios actions\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def stop_scenarios(self):\n try:\n self.runScenarios.clear()\n self.askForBlockNumber.clear()\n self.eos_rpc.clear_action_flag()\n except Exception as _ex:\n log.exception(\"Exception `%s` while stoping scenarios\"%str(_ex))\n exit(1)\n\n\n def check_user_status_after_block(self, _symbol=\"BTS\"):\n try:\n while self.runScenarios.is_set():\n while self.askForBlockNumber.is_set():\n if self.after_block:\n for user, after_blocks in self.after_block.items():\n if after_blocks and self.blockNumber > (after_blocks[0][\"after_block\"] + self.join_block_number ):\n after_block = (after_blocks[0][\"after_block\"] )\n after_blocks.pop(0)\n if self.blockNumber >= (self.scenarios[self.scenariosNr][\"scenario_blocks\"] + self.join_block_number ):\n return\n balance = self.eos_rpc.get_currency_balance(user, _symbol)\n account_after_block = self.eos_rpc.get_account(user)\n result = {}\n result[\"resources\"] = account_after_block[\"total_resources\"] if \"total_resources\" in account_after_block else {}\n result[\"resources\"][\"core_liquid_balance\"] = account_after_block[\"core_liquid_balance\"] if \"core_liquid_balance\" in account_after_block else \"\"\n voter_info = account_after_block[\"voter_info\"] if \"voter_info\" in account_after_block else {}\n if result and \"owner\" in result[\"resources\"]:\n result[\"resources\"].pop(\"owner\")\n result[\"resources\"][\"balance\"]=balance[\"balance\"]\n result[\"voter_info\"] = voter_info\n result[\"after_block\"] = (after_block )\n if user in self.after_block_result:\n self.after_block_result[user].append(result)\n else:\n self.after_block_result[user] = [result]\n except Exception as _ex:\n log.exception(\"Exception `%s` while checking user status after block\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def execute_scenatio_actions(self):\n try:\n if not self.askForBlockNumber.is_set():\n self.askForBlockNumber.set()\n if self.actions:\n for action in self.actions:\n if isinstance(action, list):\n startBlock = (action[0].pop(\"start_block\") )\n else:\n startBlock = (action.pop(\"start_block\") )\n while startBlock and (startBlock + self.join_block_number) >= (self.blockNumber ):\n if self.blockNumber >= (self.scenarios[self.scenariosNr][\"scenario_blocks\"] + self.join_block_number):\n return\n if not self.askForBlockNumber.isSet():\n break\n time.sleep(0.1)\n if self.blockNumber >= (self.scenarios[self.scenariosNr][\"scenario_blocks\"] + self.join_block_number):\n return\n\n self.eos_rpc.push_action(action)\n else:\n log.info(\"There are no actions.\")\n exit(0)\n except Exception as _ex:\n log.exception(\"Exception `%s` while executing scenarios actions\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def prepare_actions(self):\n try:\n self.actions.clear()\n all_actions = self.scenarios[self.scenariosNr][\"actions\"]\n many_actions = []\n for action in all_actions:\n if isinstance(action, list):\n many_actions.append(action)\n else:\n self.actions.append(action)\n self.actions = sorted(self.actions, key=lambda k: k['start_block'])\n if many_actions:\n many_actions = sorted(many_actions, key=lambda k: k[0]['start_block'])\n many_actions = many_actions[0]\n start_block = many_actions[0]['start_block']\n inserted = False\n for index, action in enumerate(self.actions):\n if action['start_block'] >= start_block:\n self.actions.insert(index, many_actions)\n inserted = True\n break\n if not inserted:\n self.actions.append(many_actions)\n except Exception as _ex:\n log.exception(\"Exception `%s` while preparing actions.\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def prepare_after_block(self):\n try:\n after_block = self.scenarios[self.scenariosNr][\"expected_results\"]\n log.info(\"after block %s\"%after_block)\n if after_block:\n for after in after_block:\n if after[\"user\"] in self.after_block:\n if \"after_block\" in after:\n for a in after[\"after_block\"]:\n self.after_block[after[\"user\"]].append(a) \n else:\n if \"after_block\" in after:\n self.after_block[after[\"user\"]]=after[\"after_block\"]\n if self.after_block:\n for key, value in self.after_block.items():\n self.after_block[key] = sorted(value, key=lambda k:k['after_block'])\n except Exception as _ex:\n log.exception(\"Exception `%s` while preparing after blocks.\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n\n def prepare_data(self):\n try:\n if self.append_block_numbers:\n self.join_block_number = int(self.eos_rpc.get_info()[\"head_block_num\"])\n log.info(\"self.join_block_number: %d\"%self.join_block_number)\n self.prepare_actions()\n self.prepare_after_block()\n except Exception as _ex:\n log.exception(\"Exception `%s` while preparing scenario data\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n\n def restore_node_params(self,\n _starting_block_for_initial_witness_election,\n _distribution_params):\n try:\n params=list()\n params.append({\n \"authorized_by\":\"beos.init\",\n \"code\":\"beos.init\",\n \"action\":\"changeparams\",\n \"args\":{\n \"new_params\":[\"0.0000 BTS\", _starting_block_for_initial_witness_election]\n }\n })\n params.append({\n \"authorized_by\":\"beos.distrib\",\n \"code\":\"beos.distrib\",\n \"action\":\"changeparams\",\n \"args\":{\n \"new_params\":_distribution_params\n }\n })\n\n self.eos_rpc.prepare_and_push_transaction(params)\n except Exception as _ex:\n log.exception(\"Exception `%s` while restoring node original data\"%str(_ex))\n self.stop_scenarios()\n exit(1)\n","sub_path":"tests/beos_plugin_tests/testscenarios.py","file_name":"testscenarios.py","file_ext":"py","file_size_in_byte":24252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"617874952","text":"import queue\nfrom GeeksForGeeks.Tree.BinaryTree import BinaryTree\n\ndef create_mirror(node):\n \"\"\"\n Non - recursive implementation\n :param node:\n :return:\n \"\"\"\n\n if not node :\n return\n else :\n que = queue.Queue()\n que.put(node)\n while not que.empty():\n node = que.get()\n if node.left :\n que.put(node.left)\n if node.right :\n que.put(node.right)\n\n node.left, node.right = node.right, node.left\n\ndef _create_mirror(node):\n \"\"\"\n Recursive implementation\n :param node:\n :return:\n \"\"\"\n if not node :\n return None\n else :\n _create_mirror(node.left)\n _create_mirror(node.right)\n node.left,node.right = node.right, node.left\n\n\n\nif __name__=='__main__':\n tree = BinaryTree()\n for i in range(1,10):\n tree.add_node(i)\n create_mirror(tree.root)\n tree.print_levelorder()\n _create_mirror(tree.root)\n tree.print_levelorder()","sub_path":"GeeksForGeeks/Tree/Convert2Mirror.py","file_name":"Convert2Mirror.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"640541676","text":"# Copying binary files\n# Error : reading the binary files in ASCII mode will\n# throw exception - UnicodeDecodeError: 'charmap' codec can't decode byte 0x81\n# Solution : Use the file modes - rb+ and wb+ to read & write binary content\n# This works for ASCII text file content as well\n\nfrom sys import argv\nfrom os.path import exists\n\n# Input from and to file names as Argument Values\nscript, from_file, to_file = argv\nrootpath = \"./files/\"\n\ntarget_file = open(rootpath + to_file, \"wb+\")\ntarget_file.write(open(rootpath + from_file, \"rb+\").read())\n\nprint(\"File copied successfully!\")\ntarget_file.close()","sub_path":"ex17_2.py","file_name":"ex17_2.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"303139823","text":"import argparse\nimport os\n\nclass Options():\n\n def __init__(self):\n self.parser = argparse.ArgumentParser()\n self.initalized = False\n\n def initalize(self):\n self.parser.add_argument('--rotation', required=True, help='the rotation angle of camera')\n\n def parse(self):\n if not self.initalized:\n self.initalize()\n self.opt = self.parser.parse_args()\n\nif __name__ == '__main__':\n op = Options()\n op.parse()\n print (op.opt)\n","sub_path":"options/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"386129269","text":"import os\nimport cv2\nimport numpy as np\nimport random\nglobal dstfolder\nfrom tqdm import tqdm\nfilename=\"unzip/\"\nmse_fa=500\n\ndef mse(a,b):\n try:\n err = np.sum((a.astype(\"float\")-b.astype(\"float\"))**2)\n err /= float(a.shape[0]* a.shape[0])\n except:\n err=0\n\n return err\n\n\ndef judgement_class(objlocation,picture_name,output_name):\n im = cv2.imread(picture_name)\n h, w, _ = im.shape\n objlocation = [float(i) for i in objlocation]\n x1 = int((float(objlocation[0]) * w))\n y1 = int((float(objlocation[1]) * h))\n xw = int((float(objlocation[2])) * w / 2)\n xh = int((float(objlocation[3])) * h / 2)\n crop_img = im[y1 - xh:y1 + xh, x1 - xw:x1 + xw]\n cv2.imwrite(output_name, crop_img)\n\ndef return_picture(context_2,picture_name):\n im = cv2.imread(picture_name)\n h, w, _ = im.shape\n if type(context_2) ==str:\n objlocation = context_2.split(\" \")[1:]\n else:\n objlocation=context_2\n objlocation = [float(i) for i in objlocation]\n x1 = int((float(objlocation[0]) * w))\n y1 = int((float(objlocation[1]) * h))\n xw = int((float(objlocation[2])) * w / 2)\n xh = int((float(objlocation[3])) * h / 2)\n crop_img = im[y1 - xh:y1 + xh, x1 - xw:x1 + xw]\n return crop_img, objlocation\n\n\n\n\nfor root,dir,files in os.walk(filename):\n for d in tqdm(dir):\n if d[-4:]=='data':\n continue\n if d.split('_')[3][0] in ['1', '4']:\n dstfolder = \"location_dataset/1-4/\"\n if d.split('_')[3][0] in ['2', '3', '6']:\n dstfolder = \"location_dataset/2-3-6/\"\n if d.split('_')[3][0] == '5':\n dstfolder = \"location_dataset/5/\"\n if d[-4:]=='data':\n continue\n orign_lid=[]\n orign_sink=[]\n '''start set orign'''\n with open(filename+ d + '/obj_train_data/frame_000000.txt') as orign_txt:\n orign_contexts = orign_txt.readlines()\n for orign_context in orign_contexts:\n if orign_context[0] in ['0','1','3']:\n orign_lid.append(return_picture(orign_context,filename+ d + '/obj_train_data/frame_000000.PNG'))\n if orign_context[0] in ['2','4']:\n orign_sink.append(return_picture(orign_context,filename + d + '/obj_train_data/frame_000000.PNG'))\n # print(len(orign_sink))\n # print(orign_lid)\n \"\"\"start all folder\"\"\"\n # print(orign_sink)\n mse_lid_list_same=[]\n mse_lid_list_diff=[]\n mse_sink_list_same = []\n mse_sink_list_diff = []\n for r, d1, f in os.walk(filename+ d+'/obj_train_data'):\n\n for f1 in f:\n if f1[-1] == 'G':\n if orign_sink:\n for orign_sink_location in orign_sink:\n # print(orign_sink_location)\n crop_img,objlocation=return_picture(orign_sink_location[1],\n filename+ d+'/obj_train_data/'+f1)\n mse_sink_result=mse(orign_sink_location[0],crop_img)\n if mse_sink_result <= mse_fa:\n mse_sink_list_same.append([mse_sink_result,crop_img,f1])\n else:\n mse_sink_list_diff.append([mse_sink_result,crop_img,f1])\n if orign_lid:\n for orign_lid_location in orign_lid:\n crop_img,objlocation=return_picture(orign_lid_location[1],\n filename + d + '/obj_train_data/' + f1)\n mse_lid_result=mse(orign_lid_location[0],crop_img)\n if mse_lid_result <= mse_fa:\n mse_lid_list_same.append([mse_lid_result,crop_img,f1])\n else:\n mse_lid_list_diff.append([mse_lid_result,crop_img,f1])\n\n if len(mse_sink_list_same)>=20:\n mse_sink_list_same=random.sample(mse_sink_list_same,20)\n if len(mse_sink_list_diff)>=40:\n mse_sink_list_diff=random.sample(mse_sink_list_diff,40)\n\n if len(mse_lid_list_same)>=20:\n mse_lid_list_same=random.sample(mse_lid_list_same,20)\n if len(mse_lid_list_diff)>=40:\n mse_lid_list_diff=random.sample(mse_lid_list_diff,40)\n\n for sink_output in mse_sink_list_same+mse_sink_list_diff:\n # print('location_dataset/sink/'+d+sink_output[2])\n cv2.imwrite('location_dataset/sink/'+d+sink_output[2],sink_output[1])\n for lid_output in mse_lid_list_same+mse_lid_list_diff:\n cv2.imwrite(dstfolder + d + lid_output[2], lid_output[1])\n # list1=random.sample(list(filter(lambda x:x[0]>3000,mse_sink_list)),10)\n # print(list1)\n # print(len(mse_lid_list))\n # sinkresult=random.sample((filter(lambda x:x[0]>3000,mse_sink_list)),10)\n # print(len(sinkresult))\n\n\n # for r, d1, f in os.walk(\"unzip/\" + d + '/obj_train_data'):\n # for f1 in f:\n # if f1[-1] == 't':\n # with open(\"unzip/\" + d + '/obj_train_data/' + f1) as txt:\n # contexts_2 = txt.readlines()\n #\n # # if d.split('_')[3][0] not in ['1','2','3','4','5','6']:\n # # print(d)\n # if not os.path.isdir(dstfolder):\n # os.mkdir(dstfolder)\n # for context_2 in contexts_2:\n # if context_2[0] in ['0','1','3']:\n #\n # if len( flag_init_lib) == 0:\n # flag_init_lib=judgement_class(context_2,\"unzip/\"+d+'/obj_train_data/'+f1[0:-4]+'.PNG',dstfolder+d+'_lidopen_'+f1[0:-4]+'.PNG')\n #\n #\n # else:\n # now_lib=return_picture(context_2,\"unzip/\"+d+'/obj_train_data/'+f1[0:-4]+'.PNG')\n # mse_lib_list.append([f1[0:4],mse(origin_lib,now_lib)])\n #\n # if context_2[0] in ['2','4']:\n # sinklocation='location_dataset/sink/'\n # if not os.path.isdir(sinklocation):\n # os.mkdir(sinklocation)\n #\n # if len(flag_init_sink) == 0:\n # flag_init_sink=judgement_class(context_2,\"unzip/\"+d+'/obj_train_data/'+f1[0:-4]+'.PNG',sinklocation+d+'_lidopenwithobj_'+f1[0:-4]+'.PNG')\n #\n # else:\n # now_sink = return_picture(context_2,\"unzip/\" + d + '/obj_train_data/' + f1[0:-4] + '.PNG')\n # mse_sink_list.append([f1[0:4], mse(origin_lib, now_sink)])\n # flag+=1\n # print(float(flag)/float(len(dir)))\n # # print(d.split('_')[3][0])\n # if d.split('_')[3][0] in ['1', '4']:\n # dstfolder = \"location_dataset/1-4/\"\n # if d.split('_')[3][0] in ['2', '3', '6']:\n # dstfolder = \"location_dataset/2-3-6/\"\n # if d.split('_')[3][0] == '5':\n # dstfolder = \"location_dataset/5/\"\n # if d.split('_')[3][0] not in ['1', '2', '3', '4', '5', '6']:\n # continue","sub_path":"pythonProject/creat_to_efficent_and_yolo/unzip4.py","file_name":"unzip4.py","file_ext":"py","file_size_in_byte":7338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"126655829","text":"quantidade=4\nlista=[]\nsoma=[]\nfor i in range(quantidade):\n lista.append(int(input(\"Digite um número = \")))\nprint(lista)\n\nfor i in range(len(lista)-1):\n \n soma.append(lista[i]+lista[i+1])\n\nsoma.append(lista[-1])\n\nprint(soma)\n","sub_path":"Lista-IP-9-Danilo Soares/Exercício - LISTAS/Exerício - 3.py","file_name":"Exerício - 3.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"418169844","text":"import numpy as np\nimport os\nimport cv2\nimport itertools \n#data_dir=r\"/home/ml/python/data/Market-1501-v15.09.15/bounding_box_train\"\ndata_dir=r\"D:\\work\\ignore\\data\\Market-1501-v15.09.15\\bounding_box_train\"\n#tf_file=data_dir+\".tfrecord\"\n\nmean,std=np.array([ 98.71386688, 99.6363764 , 106.03737987],dtype=np.float32),np.array([53.37228331, 53.43603813, 55.46276128],np.float32)\n\nH,L=384,192\n\nimg_shape = (L,H)\n\nmax_id=751\n\ndef get_img_with_id():\n img_files=os.listdir(data_dir)\n np.random.shuffle(img_files)\n for file_name in img_files:\n persion_id=file_name.split('_')[0]\n img=cv2.imread(data_dir+\"\\\\\"+file_name)\n if img is None:\n print(\"can't read file:%s\" % file_name)\n continue\n img=cv2.resize(img,img_shape)\n img=(img-mean)/std\n persion_id=int(persion_id)\n yield [img,persion_id]\n \ndef get_batch(batch_size):\n data=get_img_with_id()\n group_mask=itertools.cycle([True]*batch_size+[False]*batch_size)\n return map(lambda x:[[xx[i] for xx in x] for i in range(2)],map(lambda x:list(x[1]),itertools.groupby(data,lambda _ :next(group_mask))))\n\n# \n#def to_example(data):\n# global max_id\n# for img,persion_id in data:\n# max_id=max(max_id,persion_id)\n# example = tf.train.Example(features=tf.train.Features(\n# feature={\n# 'label_': tf.train.Feature(int64_list = tf.train.Int64List(value=[persion_id])), \n# 'img_':tf.train.Feature(float_list = tf.train.FloatList(value=img.reshape(-1)))\n# }))\n# yield example\n#\n#def show_user(data):\n# for img,persion_id in data:\n# cv2.imshow(str(persion_id),img)\n# cv2.waitKey(0)\n#\n#def write_to_tfrecord():\n# with tf.python_io.TFRecordWriter(tf_file) as writer:\n# data=get_img_with_id()\n# data=to_example(data)\n# for i,ex in enumerate(data):\n# if i%100==0:\n# print(\"write:%s\" % i)\n# if i%1000==0:\n# writer.flush()\n# writer.write(ex.SerializeToString())\n\nif __name__=='__main__':\n current_id=-1\n id_set={}\n \n img_files=os.listdir(data_dir)\n for file_name in img_files:\n if '_' not in file_name:\n print(\"can't read file:%s\" % file_name)\n continue\n persion_id,fix=file_name.split('_',1)\n current_id += persion_id not in id_set\n new_id=id_set.get(persion_id,current_id)\n id_set[persion_id]=new_id\n new_file=str(new_id)+'_'+fix;\n print(\"rename %s to %s\" % (file_name,new_file))\n os.rename(\"%s\\\\%s\"%(data_dir,file_name),\"%s\\\\%s\"%(data_dir,new_file))\n ","sub_path":"python/spyder/ml/body_track/PCB/read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"237066193","text":"from __future__ import division, print_function, absolute_import\nfrom builtins import range, map\nfrom math import floor, sqrt, pi\nimport pytest\n\nimport sys\nimport os\nsys.path.append(os.path.realpath(os.path.dirname(__file__)+\"/..\"))\n\nimport numpy as np\nimport dorado.lagrangian_walker as lw\nimport dorado.particle_track as pt\n\n# defining some of the geometric/walk values up top\njwalk = np.array([[-1, -1, -1],\n [0, 0, 0],\n [1, 1, 1]])\n\niwalk = np.array([[-1, 0, 1],\n [-1, 0, 1],\n [-1, 0, 1]])\n\ndistances = np.array([[np.sqrt(2), 1, np.sqrt(2)],\n [1, 1, 1],\n [np.sqrt(2), 1, np.sqrt(2)]])\n\nivec = np.array([[-np.sqrt(0.5), 0, np.sqrt(0.5)],\n [-1, 0, 1],\n [-np.sqrt(0.5), 0, np.sqrt(0.5)]])\n\njvec = np.array([[-np.sqrt(0.5), -1, -np.sqrt(0.5)],\n [0, 0, 0],\n [np.sqrt(0.5), 1, np.sqrt(0.5)]])\n\nangles = np.array([[3*pi/4, pi/2, pi/4],\n [pi, 0, 0],\n [5*pi/4, 3*pi/2, 7*pi/4]])\n\n# set up a set of model parameters that the test functions can use\nparams = pt.modelParams()\n# define a bunch of expected values\nparams.stage = np.ones((5, 5))\nparams.cell_type = np.zeros_like(params.stage)\nparams.qy = params.stage.copy()\nparams.qx = np.zeros((5, 5))\nparams.ivec = ivec\nparams.jvec = jvec\nparams.distances = distances\nparams.dry_depth = 0.1\nparams.gamma = 0.02\nparams.theta = 1\nparams.steepest_descent = True\nparams.depth = params.stage.copy()\nparams.depth[2, 2] = 10.0 # define index 8 as the deepest\nparams.seed_xloc = [1]\nparams.seed_yloc = [1]\nparams.Np_tracer = 1\nparams.dx = 1\nparams.model = 'DeltaRCM'\n\n\n# defining the unit tests, one per function in the particle_tools.py\ndef test_random_pick_seed():\n '''\n Test for function random_pick_seed\n '''\n choices = [0]\n probs = 1\n # should return the only option from the choices input\n assert lw.random_pick_seed(choices, probs) == choices[0]\n\n\ndef test_get_weight():\n '''\n Test for function get_weight\n '''\n # set the current index\n ind = (1,1)\n # set seed\n np.random.seed(0)\n # define particles class\n params.depth = params.stage.copy()\n particles = pt.Particles(params)\n # make assertion\n assert lw.get_weight(particles, ind) == 5\n\n\ndef test_calculate_new_ind():\n '''\n Test for function calculate_new_ind within Tools class\n '''\n # assign old index\n old_ind = [1, 1]\n # assign new cell location\n new_cell = 0\n # expect new cell to be in location (0,0)\n assert lw.calculate_new_ind(old_ind, new_cell, iwalk, jwalk) == (0,0)\n\n\ndef test_step_update_straight():\n '''\n Test for function step_update within Tools class\n '''\n # set cell size to 1\n dx = 1.\n # define new cell location\n new_cell = 1\n # expect distance between new and old locations to be 1\n # would expect sqrt(2) if the step was diagonal instead of vertical\n assert lw.step_update(new_cell, distances, dx) == 1\n\n\ndef test_step_update_diagonal():\n '''\n Test for function step_update within Tools class\n '''\n # set cell size to 1\n dx = 1.\n # define new cell location\n new_cell = 2\n # expect distance between new and old locations to be sqrt(2)\n # would expect 1 if the step was vertical instead of diagonal\n assert lw.step_update(new_cell, distances, dx) == sqrt(2)\n\n\ndef test_calc_travel_times():\n '''\n Test for function calc_travel_times within Tools class\n '''\n # define particles\n params.diff_coeff = 0\n params.depth = np.ones_like(params.stage)\n params.qx = np.zeros_like(params.stage)\n params.qy = np.ones_like(params.stage)\n particle = pt.Particles(params)\n # define old ind\n old_ind = [1,1]\n # define new ind\n new_ind = [0,1]\n # hardset angles/velocities to make computation more obvious\n particle.velocity = np.ones_like(particle.velocity)\n particle.velocity[0, 0:2] = 3\n particle.velocity_angle = np.ones_like(particle.velocity_angle)\n # get time\n trav_time = lw.calc_travel_times(particle, 1, old_ind, new_ind, 1)\n # expect to return the value 0.5 (inverse of the avg velocity 2)\n assert trav_time == pytest.approx(0.5609806565385976)\n\n\ndef test_check_for_boundary():\n '''\n Test for function check_for_boundary within Tools class\n '''\n # define padded cell types for tools class\n cell_type = np.ones((3,3))\n # define an edge (type==-1)\n cell_type[0,0:2] = -1\n # define new ind\n new_ind = [[0,1]]\n # define current ind\n current_ind = [[1,1]]\n # expect to return the current ind because proposed new ind is an edge\n assert lw.check_for_boundary(new_ind,current_ind,cell_type) == current_ind\n\n\ndef test_random_pick():\n '''\n Test for function random_pick within Tools class\n '''\n # define probs array of zeros with a single 1 value\n probs = np.zeros((8,))\n probs[0] = 1\n # should return first index\n assert lw.random_pick(probs) == 0\n\n\ndef test_get_weight_norm():\n '''\n Test for function get_weight within Tools class\n '''\n # define particles\n params.qy = np.ones_like(params.stage)\n params.qx = np.zeros_like(params.stage)\n params.stage[1,1] = 100.0\n particles = pt.Particles(params)\n # set the current index\n ind = (1,1)\n # set seed\n np.random.seed(0)\n # make assertion\n assert lw.get_weight(particles, ind) == 5\n\n\ndef test_get_weight_deep():\n '''\n Test for function get_weight within Tools class\n '''\n tools = pt.modelParams()\n # define a bunch of expected values\n tools.stage = np.ones((5,5))\n tools.cell_type = np.zeros_like(tools.stage)\n tools.qy = tools.stage.copy()\n tools.qx = np.zeros((5,5))\n tools.ivec = ivec\n tools.jvec = jvec\n tools.distances = distances*np.nan\n tools.dry_depth = 0.1\n tools.gamma = 0.02\n tools.theta = 1\n tools.steepest_descent = True\n tools.depth = tools.stage.copy()\n tools.depth[2,2] = 10.0 # define index 8 as the deepest\n tools.seed_xloc = [1]\n tools.seed_yloc = [1]\n tools.Np_tracer = 1\n tools.dx = 1\n # define particles\n particles = pt.Particles(tools)\n # set the current index\n ind = (1,1)\n # set seed\n np.random.seed(0)\n # make assertion\n assert lw.get_weight(particles, ind) == 8\n","sub_path":"tests/test_lagrangian_walker.py","file_name":"test_lagrangian_walker.py","file_ext":"py","file_size_in_byte":6344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"96074330","text":"class Solution:\n def threeSum(self, nums):\n # Make a table save the -sum of each two\n # for for and for\n # if found -sum + List[i] = 0 then return the set\n \n table = [[9999]*len(nums)]*len(nums)\n print(table)\n # table = []\n for i in range(len(nums)):\n j = i+1\n while j float\n \n uses the ideal gas law to calculate density of an air parcel at fixed pressure of 80 kPa\n \n P = rho * Rd * T # Stull, pg 14, eqn 1.18\n \n in: list of temperatures (K)\n \n out: list of densities of dry air (kg.m^-3)\n \n \"\"\"\n P = 80e+3 # Pressure, Pa\n Rd = 287.05 # gas constant for dry air, J mole^-1 K^-1\n \n list_of_rho = [(P / (Rd * temp)) for temp in listoftemps]\n \n return list_of_rho\n\n\ntemps = [280, 290, 300]\n\nrho = eqstate(temps)\n\nresults = zip(temps,rho)\n\n[print('At temp: %2.1f K, density of dry air = %2.8f kg.m^-3' %(t,r)) for (t,r) in (results)]\n\nplt.plot(temp, rho, label='density at 80kPa')\nplt.xlabel('Temperature $K$')\nplt.ylabel('Density $(kg.m^{-3})$')\nplt.legend()\n\n","sub_path":"notebooks/python/hadleigh_eqstate.py","file_name":"hadleigh_eqstate.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"242221307","text":"# -*- coding: utf-8 -*-\n\nimport fixpath\nfrom google.appengine.ext import ndb\nfrom google.appengine.ext.ndb import model\nfrom google.appengine.api import mail\nfrom webapp2_extras import jinja2\nfrom aefabric.models.migrating import MigratingModel\nimport config\n\n\nclass Message(MigratingModel):\n\n sender = model.KeyProperty(required=True)\n reciever = model.KeyProperty(required=True)\n message = model.TextProperty(required=True)\n\n action = model.StringProperty(required=True)\n\n data = model.StringProperty()\n data_key = model.KeyProperty()\n\n date_created = model.DateTimeProperty(auto_now_add=True)\n date_updated = model.DateTimeProperty(auto_now=True)\n _last_migration = 1\n\n @classmethod\n def contact_message(cls, sender, reciever, message):\n\n data = {\n 'sender': sender.key,\n 'reciever': reciever.key,\n 'message': message,\n\n 'action': 'contact',\n 'data_key': None,\n 'data': None\n }\n\n entity = cls(**data)\n entity.put()\n\n context = {}\n context['sender'] = sender\n context['reciever'] = reciever\n context['message'] = message\n context['subject'] = 'New message from %s' % sender.name\n context['config'] = config.settings\n\n rv = jinja2.get_jinja2().render_template('mail/contact.html', **context)\n\n email = mail.EmailMessage(sender=\"Gullibear \", subject=context['subject'])\n email.reply_to = sender.email\n email.to = reciever.email\n email.html = rv\n email.send()\n\n @classmethod\n def contribution_message(cls, sender, idea, content):\n\n reciever = idea.creator\n\n data = {\n 'sender': sender.key,\n 'reciever': reciever.key,\n 'message': content,\n\n 'action': 'contribution-idea',\n 'data_key': idea.key,\n 'data': idea.title\n }\n\n entity = cls(**data)\n entity.put()\n\n context = {}\n context['sender'] = sender\n context['reciever'] = reciever\n context['message'] = content\n context['idea'] = idea\n context['subject'] = '%s contributed to your idea' % sender.name\n context['config'] = config.settings\n\n rv = jinja2.get_jinja2().render_template('mail/contributed_idea.html', **context)\n\n email = mail.EmailMessage(sender=\"Gullibear \", subject=context['subject'])\n email.to = reciever.email\n email.html = rv\n email.send()\n\n @classmethod\n def notify_contribution(cls, subscriber, contribution, idea):\n\n data = {\n 'sender': contribution.author_key,\n 'reciever': subscriber.key,\n 'message': contribution.content,\n\n 'action': 'notify-contribution',\n 'data_key': contribution.key,\n 'data': None\n }\n\n entity = cls(**data)\n entity.put()\n\n context = {}\n context['sender'] = contribution.author\n context['reciever'] = subscriber\n context['message'] = contribution.content\n context['idea'] = idea\n context['subject'] = 'New contribution to %s' % idea.title\n context['config'] = config.settings\n\n rv = jinja2.get_jinja2().render_template('mail/notify_contribution.html', **context)\n\n email = mail.EmailMessage(sender=\"Gullibear \", subject=context['subject'])\n email.to = subscriber.email\n email.html = rv\n email.send()\n","sub_path":"app/models/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"259053494","text":"# команда для ссылки на дискорд канал\nimport command_system\n\n\ndef discord(token, user_id, stroka='', peer_id=''):\n message = 'Ссылочка на дискорд канал: https://discord.gg/Hv47uYA'\n return message, ''\n\n\ndiscord_command = command_system.Command()\n\ndiscord_command.keys = ['!дискорд']\ndiscord_command.description = 'Подскажу ссылку на дискорд канал'\ndiscord_command.process = discord\n","sub_path":"commands/discord.py","file_name":"discord.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"336371626","text":"#!/bin/env python\n# coding:utf-8\n\n# ネガポジを判定しカウントする\n#import psycopg2\nimport sqlite3\nimport os\nimport MeCab\nimport re\nimport gensim\nimport argparse\nimport CaboCha\n\nclass VerbDict:\n def __init__(self,args):\n self.dict_nega={}\n self.dict_posi={}\n with open(args.verb_dict,\"r\") as f:\n for l in f.readlines():\n items=l.replace(\"\\n\",\"\").split(\"\\t\")\n if items[0].startswith(\"ネガ\"):\n dict=self.dict_nega\n else:\n dict=self.dict_posi\n if len(items)==1:\n continue\n if len(items[0])==0:\n continue\n lst=items[1].split(\" \")\n\n if len(lst[0])==0:\n continue\n if lst[0] not in dict:\n dict[lst[0]]=[]\n\n dict[lst[0]].append(lst)\n\n def check(self,sentences,i):\n if self.__check_dict(sentences,i,self.dict_nega):\n return \"n\"\n elif self.__check_dict(sentences,i,self.dict_posi):\n return \"p\"\n return None\n\n def __check_dict(self,sentences,i,dict):\n moji=sentences[i][0]\n if self.__check_dict_with_moji(sentences,i,dict,moji):\n return True\n kihon_moji=sentences[i][1]\n if self.__check_dict_with_moji(sentences,i,dict,kihon_moji):\n return True\n return False\n\n def __check_dict_with_moji(self,sentences,i,dict,moji):\n if moji in dict:\n lst=dict[moji]\n for l in lst:\n okflg=True\n for j in range(len(l)):\n if len(sentences)>i+j:\n if sentences[i+j][0] != l[j] and sentences[i+j][1] != l[j]:\n okflg=False\n break\n else:\n okflg=False\n break\n if okflg:\n print(l)\n return True\n\n\nclass NounDict:\n def __init__(self,args):\n self.dict={}\n with open(args.noun_dict,\"r\") as f:\n for l in f.readlines():\n items=l.replace(\"\\n\",\"\").split(\"\\t\")\n self.dict[items[0]]=items[1]\n\n def check(self,s):\n if s in self.dict:\n res=self.dict[s]\n if res in (\"n\",\"p\"):\n return res\n return None\n\nclass NegaPosi:\n\n def __init__(self,args):\n self.args=args\n self.mecab = MeCab.Tagger('-Ochasen')\n #self.conn = psycopg2.connect(dbname=\"board\", host=os.environ[\"DBHOST\"], user=os.environ[\"DBUSER\"],password=os.environ[\"PGPASSWORD\"])\n self.conn = sqlite3.connect(os.environ[\"DATA\"]+\"/board/board.db\")\n self.cabo=CaboCha.Parser()\n\n self.noun_dict=NounDict(self.args)\n self.verb_dict=VerbDict(self.args)\n\n def __del__(self):\n self.conn.close()\n\n def run(self):\n for i in range(1301,9998):\n if i % 10 == self.args.code_suffix:\n self.run_code(i)\n\n def run_code(self,code):\n with open(self.args.outdir+\"/np\"+str(code)+\".dat\", \"w\") as f:\n self.__run_and_write(f,code)\n\n def __run_and_write(self,f,code):\n limit=\"\"\n if self.args.debug:\n limit=\"limit 20\"\n cur=self.conn.cursor()\n cur.execute(\"select code,tno,mno,body from board where code=? and date >= ? and date < ? \"+limit,(code, self.args.fmdate, self.args.todate,))\n\n for row in cur.fetchall():\n sentences=[]\n noun_nega=0\n noun_posi=0\n verb_nega=0\n verb_posi=0\n nodes = self.mecab.parse(row[3])\n\n for node in nodes.split(\"\\n\"):\n if node == \"EOS\":\n break\n items = node.split(\"\\t\")\n moji = items[0]\n katakana = items[1]\n kihon_moji = items[2]\n hinshi = items[3]\n #print(moji,kihon_moji)\n sentences.append((moji,kihon_moji,hinshi))\n\n for i in range(len(sentences)):\n\n hinshi=sentences[i][2]\n if hinshi.startswith(\"名詞\"):\n np=self.noun_dict.check(sentences[i][0])\n if np == \"n\":\n noun_nega+=1\n elif np == \"p\":\n noun_posi+=1\n\n np=self.verb_dict.check(sentences,i)\n if np == \"n\":\n verb_nega+=1\n elif np == \"p\":\n verb_posi+=1\n\n if noun_posi>0 or noun_nega>0 or verb_posi>0 or verb_nega>0:\n f.write(str(row[0])+\"\\t\"+str(row[1])+\"\\t\"+str(row[2])+\"\\t\"+str(noun_posi)+\"\\t\"+str(noun_nega)+\"\\t\"+str(verb_posi)+\"\\t\"+str(verb_nega)+\"\\n\")\n\n \"\"\"\n str=self.cabo.parseToString(row[0])\n print(str)\n\n\n tree=self.cabo.parse(row[0])\n print(\"chunk_size:\",tree.chunk_size())\n for i in range(tree.chunk_size()):\n chunk = tree.chunk(i)\n print('Chunk:', i)\n print(' Score:', chunk.score)\n print(' Link:', chunk.link)\n print(' Size:', chunk.token_size)\n print(' Pos:', chunk.token_pos)\n print(' Head:', chunk.head_pos) # 主辞\n print(' Func:', chunk.func_pos) # 機能語\n s=\"\"\n for j in range(chunk.feature_list_size):\n s+=chunk.feature_list(j)+\",\"\n print(' Features:'+s)\n\n\n\n for i in range(tree.token_size()):\n token = tree.token(i)\n print('Surface:', token.surface)\n print(' Normalized:', token.normalized_surface)\n print(' Feature:', token.feature)\n print(' NE:', token.ne ) # 固有表現\n print(' Info:', token.additional_info)\n print(' Chunk:', token.chunk)\n \"\"\"\n\n cur.close()\n\ndef main():\n parser = argparse.ArgumentParser(description='calculate board score')\n parser.add_argument('--verb_dict',type=str, default=os.environ[\"DATA\"]+\"/board/npdic/wago.121808.pn.data\")\n parser.add_argument('--noun_dict',type=str, default=os.environ[\"DATA\"]+\"/board/npdic/pn.csv.m3.120408.trim.data\")\n parser.add_argument('--code_suffix',type=int, default=1)\n parser.add_argument('--outdir',type=str, default=os.environ[\"DATA\"]+\"/board/negaposi\")\n parser.add_argument('--fmdate',type=str,default=\"2015-01-01\")\n parser.add_argument('--todate',type=str,default=\"2017-01-01\")\n parser.add_argument('--debug',type=bool,default=False)\n args = parser.parse_args()\n\n NegaPosi(args).run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"theme/src2/12_negaposi_calc.py","file_name":"12_negaposi_calc.py","file_ext":"py","file_size_in_byte":6833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"453049156","text":"import stack\nclass MyQueue:\n def __init__(self):\n self.s1 = stack.Stack()\n self.s2 = stack.Stack()\n self.nElems = 0\n\n def push(self, value):\n self.s1.push(value)\n self.nElems += 1\n \n def pop(self):\n if(self.s2.isEmpty()):\n while(self.s1.isEmpty() == False):\n self.s2.push(self.s1.pop().value)\n self.nElems -= 1\n return(self.s2.pop())\n else:\n self.nElems -= 1\n return(self.s2.pop())\n\n\nqueue = MyQueue()\nqueue.push(30)\nqueue.push(18)\nprint(queue.pop().value)\nprint(queue.pop().value)\n","sub_path":"Queues/myQueue.py","file_name":"myQueue.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"369208496","text":"from datetime import timedelta, datetime, date\n\nfrom django.core.management.base import BaseCommand\nfrom django.db.models import Q, Max\nimport pytz\n\nfrom dltapi.models import Customer, Sku, Product, Offer, OfferProduct, Subscription, Brand, Vendor\n\nfrom swipedeals.models import (\n Subscription as SD_Subscription,\n Customer as SD_Customer,\n Deal as SD_Deal\n)\n\n\nEPOCH = datetime(2011, 12, 31, 0, 0, 0, 0, pytz.UTC)\n\n_t = date.today()\nTODAY = datetime(_t.year, _t.month, _t.day, 0, 0, 0, 0, pytz.UTC)\n\n\nclass Command(BaseCommand):\n\n CUSTOMERS = {} # { sd customer id : balto customer object }\n DEAL_TO_OFFERS = {} # { sd deal id : balto offer object }\n\n def make_new_sku(self, name):\n # make new number\n max_number = Sku.objects.all().aggregate(Max('number'))\n number = int(max_number['number__max']) + 1\n # make new sku\n brand = Brand(name=name)\n try:\n brand.save()\n except:\n brand = Brand.objects.get(name=name)\n vendor = Vendor(name=name)\n try:\n vendor.save()\n except:\n vendor = Vendor.objects.get(name=name)\n sku = Sku(name=name, weight=1, number=number, brand=brand, vendor=vendor)\n try:\n sku.save()\n except:\n sku = Sku.objects.get(name=name)\n # return sku\n return sku\n\n @staticmethod\n def get_token(customer_id):\n sd_customer = SD_Customer.objects.get(id=customer_id)\n return sd_customer.braintree_token\n\n def get_or_create_customer(self, customer_id):\n # check dict\n if customer_id in self.CUSTOMERS:\n return self.CUSTOMERS[customer_id]\n # create customer\n try:\n sd_customer = SD_Customer.objects.get(id=customer_id)\n except Exception as e:\n self.stderr.write(str(e))\n return None\n customer = Customer(braintree_id=sd_customer.braintree_id, date_joined=sd_customer.created_at)\n customer.save()\n self.stdout.write('got or created new customer {}'.format(customer.id))\n # add to dict\n self.CUSTOMERS[customer_id] = customer\n # return customer\n return customer\n\n def get_or_create_offer(self, deal_id):\n # check dict\n if deal_id in self.DEAL_TO_OFFERS:\n offer = self.DEAL_TO_OFFERS[deal_id]\n self.stdout.write('got offer {}'.format(offer.id))\n return offer\n # get sd deal\n sd_deal = SD_Deal.objects.get(id=deal_id)\n skus_per = sd_deal.skus_per_deal or 1\n # process deal into s-p-o\n sku = self.make_new_sku(sd_deal.abbreviated_title)\n self.stdout.write('created new sku {}'.format(sku.id))\n product = Product(sku=sku, skus_per=skus_per)\n try:\n product.save()\n except:\n product = Product.objects.get(sku=sku, skus_per=skus_per)\n self.stdout.write('created new product {}'.format(product.id))\n offer = Offer(title=sd_deal.abbreviated_title, price=sd_deal.offer_price)\n try:\n offer.save()\n except:\n offer = Offer.objects.get(title=sd_deal.abbreviated_title, price=sd_deal.offer_price)\n self.stdout.write('created new offer {}'.format(offer.id))\n op = OfferProduct(offer=offer, product=product)\n try:\n op.save()\n except:\n op = OfferProduct.objects.get(offer=offer, product=product)\n self.stdout.write('created new offer_product {}'.format(op.id))\n # add to dict\n self.DEAL_TO_OFFERS[deal_id] = offer\n # return offer\n self.stdout.write('using offer {}'.format(offer.title))\n return offer\n\n def handle(self, *args, **options):\n\n ## get totm\n totm = SD_Subscription.objects.filter(deal__abbreviated_title='toy of the month', state='perfect')\n self.stdout.write('totm: {}'.format(len(totm)))\n for sub in totm:\n self.stdout.write('working with sd subscription {}'.format(sub.id))\n # build subscription\n customer = self.get_or_create_customer(sub.customer.id)\n if customer is None:\n continue\n offer = self.get_or_create_offer(sub.deal.id)\n token = self.get_token(sub.customer.id)\n subscription = Subscription(\n customer=customer,\n braintree_token=token,\n offer=offer,\n quantity=sub.quantity,\n starts_on=sub.created_at,\n is_totm=True\n )\n subscription.save()\n\n self.stdout.write('')\n\n ## get trotm\n trotm = SD_Subscription.objects.filter(deal__abbreviated_title='treat of the month', state='perfect')\n self.stdout.write('trotm: {}'.format(len(trotm)))\n for sub in trotm:\n self.stdout.write('working with sd subscription {}'.format(sub.id))\n # build subscription\n customer = self.get_or_create_customer(sub.customer.id)\n if customer is None:\n continue\n offer = self.get_or_create_offer(sub.deal.id)\n token = self.get_token(sub.customer.id)\n subscription = Subscription(\n customer=customer,\n braintree_token=token,\n offer=offer,\n quantity=sub.quantity,\n starts_on=sub.created_at,\n is_trotm=True\n )\n subscription.save()\n\n self.stdout.write('')\n\n ## get chotm\n chotm = SD_Subscription.objects.filter(deal__abbreviated_title='chew of the month', state='perfect')\n self.stdout.write('chotm: {}'.format(len(chotm)))\n for sub in chotm:\n self.stdout.write('working with sd subscription {}'.format(sub.id))\n # build subscription\n customer = self.get_or_create_customer(sub.customer.id)\n if customer is None:\n continue\n offer = self.get_or_create_offer(sub.deal.id)\n token = self.get_token(sub.customer.id)\n subscription = Subscription(\n customer=customer,\n braintree_token=token,\n offer=offer,\n quantity=sub.quantity,\n starts_on=sub.created_at,\n is_chotm=True\n )\n subscription.save()\n\n self.stdout.write('')\n\n ## get ~x_otm\n others = SD_Subscription.objects.filter(\n ~Q(deal__abbreviated_title__icontains='of the month'), state='perfect'\n ).values_list('deal__abbreviated_title', flat=True).distinct()\n\n ## iterate others\n for title in others:\n sd_subscriptions = SD_Subscription.objects.filter(deal__abbreviated_title=title, state='perfect')\n self.stdout.write('{}: {}'.format(title, len(sd_subscriptions)))\n\n for sub in sd_subscriptions:\n # build subscription\n customer = self.get_or_create_customer(sub.customer.id)\n if customer is None:\n continue\n offer = self.get_or_create_offer(sub.deal.id)\n token = self.get_token(sub.customer.id)\n subscription = Subscription(\n customer=customer,\n braintree_token=token,\n offer=offer,\n quantity=sub.quantity,\n starts_on=sub.created_at\n )\n\n orders = sorted(\n [order for order in sub.orders.all() if order.state == 'purchased'],\n key=lambda o: o.purchased_at,\n reverse=True\n )\n\n if len(orders) == 1:\n first = orders[0].purchased_at\n offset = 1\n while 1:\n second = first + timedelta(days=offset)\n diff = second - EPOCH\n if diff.days % sub.interval == sub.offset:\n break\n else:\n offset += 1\n while offset % 7 != 0:\n offset += 1\n self.stdout.write(str(offset))\n\n elif not len(orders):\n first = TODAY\n # set first process date\n while 1:\n diff = first - EPOCH\n if diff.days % sub.interval == sub.offset:\n break\n else:\n first += timedelta(days=1)\n # set second date\n offset = 1\n while 1:\n second = first + timedelta(days=offset)\n diff = second - EPOCH\n if diff.days % sub.interval == sub.offset:\n break\n else:\n offset += 1\n while offset % 7 != 0:\n offset += 1\n self.stdout.write(str(offset))\n\n else:\n diffs = []\n for i, order in enumerate(orders[:4]):\n try:\n diff = order.purchased_at - orders[i+1].purchased_at\n except IndexError:\n break\n diffs.append(diff.days)\n offset = sum(diffs) // len(diffs)\n while offset % 7 != 0:\n offset += 1\n self.stdout.write(str(offset))\n\n # apply offset and save\n subscription.send_every_n_days = offset\n subscription.save()\n\n self.stdout.write('')\n","sub_path":"swipedeals/management/commands/swipedeals-migrate-subscriptions.py","file_name":"swipedeals-migrate-subscriptions.py","file_ext":"py","file_size_in_byte":9868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"175712894","text":"#%%\nfrom flask import Flask,request \nfrom flask_cors import CORS,cross_origin\nimport json\nimport requests\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/negocios',methods=['GET', 'POST'])\ndef hello_world():\n print(request.data )\n return 'hi'\n\n@app.route('/trades',methods=['POST'])\n@cross_origin()\ndef saveTrades():\n data = json.loads(request.data)\n with open(f'inputs/{data[\"quoteTrade\"][\"M\"]}_trades.json', 'a+') as outfile:\n offers = data[\"L\"]\n for offer in offers:\n print(offer)\n outfile.write(json.dumps(offer)+\",\")\n return 'ok'\n\n@app.route('/quote/',methods=['GET'])\ndef getMarketData(ativo):\n bot = requests.session()\n r = bot.post('http://webfeeder.cedrotech.com/SignIn?login=dudarenz&password=102030')\n dados = bot.get(f'http://webfeeder.cedrotech.com/services/quotes/quote/{ativo}')\n return dados.json()\n\nprint(__name__)\n\n# %%\nif __name__ == '__main__':\n app.run(debug=True, port=5001) ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"262315098","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 15 10:34:48 2021\r\n\r\n@author: oislen\r\n\"\"\"\r\n\r\nimport os\r\nimport sys\r\nscripts_dir = os.path.dirname(os.getcwd())\r\nsys.path.append(scripts_dir)\r\n\r\nimport cons\r\n\r\n# This Python 3 environment comes with many helpful analytics libraries installed\r\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\r\n# For example, here's several helpful packages to load\r\n\r\n# linear algebra\r\nimport numpy as np \r\n# data processing, CSV file I/O (e.g. pd.read_csv)\r\nimport pandas as pd \r\n\r\n# Input data files are available in the read-only \"../input/\" directory\r\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\r\n\r\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \r\n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\r\n \r\nimport fastai\r\nfastai.__version__ \r\n\r\nfrom fastai import *\r\nfrom fastai.tabular.all import *\r\n\r\n# set pandas behaviour\r\npd.options.display.max_rows = 20\r\npd.options.display.max_columns = None\r\n\r\n# load in train and test sets\r\ndf = pd.read_csv(cons.train_data_fpath, low_memory=False)\r\ndf_test = pd.read_csv(cons.test_data_fpath, low_memory=False)\r\n\r\n# RF does not need `Normalize`\r\nprocs = [Categorify, FillMissing] \r\n\r\nsplits = RandomSplitter(valid_pct=0.2)(range_of(df))\r\n\r\ndep_var='Survived'\r\n\r\ncont,cat = cont_cat_split(df, 1, dep_var=dep_var)\r\n\r\ncont\r\n\r\ncat\r\n\r\nto = TabularPandas(df, procs, cat, cont, y_names=dep_var, splits=splits, y_block=CategoryBlock())\r\n\r\nto.show(3)\r\n\r\nX_train, y_train = to.train.xs,to.train.y\r\nX_valid, y_valid = to.valid.xs,to.valid.y\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nm = RandomForestClassifier(n_estimators=100, n_jobs=-1)\r\n\r\nm.fit(X_train,y_train)\r\n\r\nfrom sklearn.metrics import accuracy_score\r\n\r\ny_pred=m.predict(X_valid)\r\n\r\naccuracy_score(y_valid, y_pred)\r\n\r\nto_test = TabularPandas(df_test, procs, cat, cont)\r\n\r\n# remove reduntant columns (training did not use this col)\r\npredicted_result = m.predict(to_test.xs.drop('Fare_na', axis=1)) \r\n\r\noutput= pd.DataFrame({'PassengerId':df_test.PassengerId, 'Survived': predicted_result.astype(int)})\r\noutput.to_csv('submission_titanic.csv', index=False)\r\noutput.head()","sub_path":"competitions/Titanic/scripts/misc/fastai_mod.py","file_name":"fastai_mod.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"390881328","text":"import copy\n\n# 桌面的坐标系,单位\"pace\"\nDIM = (-900000, 900000, 0, 1000000)\n# 最大时间,单位\"tick\",每个回合3600tick,200回合\nTMAX = 800000\n# 球的初始坐标(x,y),在west中间\nBALL_POS = (DIM[0], (DIM[3] - DIM[2]) // 2)\n# 球的初速度,(vx,vy),单位\"p/t\",向东北飞行\nBALL_V = (1000, 1000)\n# 球拍的生命值,100个回合以上\nRACKET_LIFE = 100000\n# 迎球和跑位扣减距离除以系数的平方(LIFE=0-1000)\nFACTOR_DISTANCE = 30000\n# 加速则扣减速度除以系数结果的平方(LIFE=0-400)\nFACTOR_SPEED = 50\n# 游戏方代码\nPL = {'West': 'W', 'East': 'E'}\n# 游戏结束原因代码\nRS = {'invalid_bounce': 'B', 'miss_ball': 'M', 'life_out': 'L', 'time_out': 'T'}\n\n\ndef sign(n): # 返回n的符号,小于0为-1,否则为1\n return -1 if n < 0 else 1\n\n\nclass Vector: # 矢量\n def __init__(self, x, y=None):\n if y is None and isinstance(x, tuple):\n self.x, self.y = x\n else:\n self.x, self.y = x, y\n\n def __add__(self, other):\n return self.__class__(self.x + other.x, self.y + other.y)\n\n def __eq__(self, other): # 判定相等,考虑误差+/-1\n return abs(self.x - other.x) <= 1 and abs(self.y - other.y) <= 1\n\n def __str__(self):\n return \"<%s,%s>\" % (self.x, self.y)\n\n\nclass Position(Vector): # 位置\n pass\n\n\nclass Ball: # 球\n def __init__(self, extent, pos, velocity):\n # 球所在的坐标系参数extent,球的位置坐标pos,球的运动速度矢量velocity\n self.extent, self.pos, self.velocity = extent, pos, velocity\n\n def bounce_wall(self): # 球在墙壁上反弹\n self.velocity.y = -self.velocity.y\n\n def bounce_racket(self): # 球在球拍反弹\n self.velocity.x = -self.velocity.x\n\n def update_velocity(self, acc_vector): # 给球加速,球桌坐标系\n # 球改变速度,仅垂直方向\n self.velocity.y += acc_vector\n\n def fly(self, ticks): # 球运动,更新位置,并返回触壁次数\n # x方向的位置\n self.pos.x += self.velocity.x * ticks\n\n # 以下是李逸飞同学的简短新算法\n # ===========NEW!=============\n Y = self.velocity.y * ticks + self.pos.y # Y是没有墙壁时到达的位置\n if Y % self.extent[3] != 0: # case1:未在边界\n count = Y // self.extent[3] # 穿过了多少次墙(可以是负的,最后取绝对值)\n\n # 两种情形:a) 穿过偶数次墙,这时没有对称变换,速度保持不变。到达的位置就是Y0=Y-self.extent[3]*count\n # b) 穿过奇数次墙,是一次对称和一次平移的复合,速度反向。先做平移,到达Y0=Y-self.extent[3]*count,再反射,到self.extent[3]-Y0\n # 综合两种情形,奇数时Y0是负的,多一个self.extent[3];偶数时Y0是正的,没有self.extent[3]。综上,ynew=Y0*(-1)^count+(1-(-1)^count)/2*self.extent[3]\n # 因不清楚负数能不能做任意整指数幂,所以用取余来表示奇偶性。\n\n self.pos.y = (Y - count * self.extent[3]) * (1 - 2 * (count % 2)) + self.extent[3] * (count % 2)\n self.velocity.y = self.velocity.y * ((count + 1) % 2 * 2 - 1)\n return abs(count)\n else: # case2: 恰好在边界\n\n # 两种情形:a) 向上穿墙,穿了1 - Y // self.extent[3] 次(代入Y = 0验证)\n # b) 向下穿墙,穿了 Y // self.extent[3] 次(代入Y = self.extent[3] 验证)\n # 无论怎样,实际位置要么在0,要么在self.extent[3]。直接模( 2 * self.extent[3] )即可。\n # 速度只和count奇偶有关,同上。\n\n count = (Y // self.extent[3]) if (Y > 0) else (1 - Y // self.extent[3])\n self.pos.y = Y % (2 * self.extent[3])\n self.velocity.y = self.velocity.y * ((count + 1) % 2 * 2 - 1)\n return count\n # ===========END==============\n\n\n'''\n # y方向速度为0\n if self.velocity.y == 0:\n return 0 # y坐标不改变,触壁次数为0\n elif self.velocity.y > 0: # 向上y+飞\n # y方向的位置,考虑触壁反弹\n bounce_ticks = (self.extent[3] - self.pos.y) / self.velocity.y\n if bounce_ticks >= ticks: # 没有触壁\n self.pos.y += self.velocity.y * ticks\n return 0\n else: # 至少1次触壁\n # 计算后续触壁\n ticks -= bounce_ticks\n count, remain = divmod(ticks, ((self.extent[3] - self.extent[2]) / self.velocity.y))\n if count % 2 == 0: # 偶数,则是速度改变方向\n self.pos.y = self.extent[3] - remain * self.velocity.y\n self.velocity.y = -self.velocity.y\n else: # 奇数,速度方向不变\n self.pos.y = self.extent[2] + remain * self.velocity.y\n return count + 1\n else: # 向下y-飞\n # y方向的位置,考虑触壁反弹\n bounce_ticks = (self.extent[2] - self.pos.y) / self.velocity.y\n if bounce_ticks >= ticks: # 没有触壁\n self.pos.y += self.velocity.y * ticks\n return 0\n else: # 至少1次触壁\n # 计算后续触壁\n ticks -= bounce_ticks\n count, remain = divmod(ticks, ((self.extent[2] - self.extent[3]) / self.velocity.y))\n if count % 2 == 0: # 偶数,则是速度改变方向\n self.pos.y = self.extent[2] - remain * self.velocity.y\n self.velocity.y = -self.velocity.y\n else: # 奇数,速度方向不变\n self.pos.y = self.extent[3] + remain * self.velocity.y\n return count + 1\n'''\n\n\nclass RacketAction: # 球拍动作\n def __init__(self, tick, bat_vector, acc_vector, run_vector):\n # self.t0 = tick # tick时刻的动作,都是一维矢量,仅在y轴方向\n self.bat = bat_vector # t0~t1迎球的动作矢量(移动方向及距离)\n self.acc = acc_vector # t1触球加速矢量(加速的方向及速度)\n self.run = run_vector # t1~t2跑位的动作矢量(移动方向及距离)\n\n\nclass Racket: # 球拍\n def __init__(self, side, pos): # 选边'West'/'East'和位置\n self.side, self.pos = side, pos\n self.life = RACKET_LIFE\n self.name = self.serve = self.play = self.action = self.datastore = None\n\n def bind_play(self, name, serve, play): # 绑定玩家名称和serve, play函数\n self.name = name\n self.serve = serve\n self.play = play\n\n def set_action(self, action): # 设置球拍动作\n self.action = action\n\n def set_datastore(self, ds): # 设置数据存储,一个字典\n self.datastore = ds\n\n def get_velocity(self):\n # 球拍的全速是球X方向速度,按照体力值比例下降,当体力值下降到55%,将出现死角\n return int((self.life / RACKET_LIFE) * BALL_V[1])\n\n def update_pos_bat(self, tick_step):\n # 如果指定迎球的距离大于最大速度的距离,则采用最大速度距离\n bat_distance = sign(self.action.bat) * min(abs(self.action.bat), self.get_velocity() * tick_step)\n self.pos.y += bat_distance\n # 减少生命值\n self.life -= int(abs(bat_distance) ** 2 / FACTOR_DISTANCE ** 2)\n\n def update_pos_run(self, tick_step):\n # 如果指定跑位的距离大于最大速度的距离,则采用最大速度距离\n run_distance = sign(self.action.run) * min(abs(self.action.run), self.get_velocity() * tick_step)\n self.pos.y += run_distance\n # 减少生命值\n self.life -= int(abs(run_distance) ** 2 / FACTOR_DISTANCE ** 2)\n\n def update_acc(self):\n # 按照给球加速度的指标减少生命值\n self.life -= int(abs(self.action.acc) ** 2 / FACTOR_SPEED ** 2)\n\n\nclass TableData: # 球桌信息,player计算用\n def __init__(self, tick, tick_step, side, op_side, ball):\n self.tick = tick\n self.step = tick_step\n self.side = side # 字典,迎球方信息\n self.op_side = op_side # 字典,跑位方信息\n self.ball = ball # 字典,球的信息\n\n\nclass RacketData: # 球拍信息,记录日志用\n def __init__(self, racket):\n self.side, self.name, self.life = racket.side, racket.name, racket.life\n self.pos, self.action = copy.copy(racket.pos), copy.copy(racket.action)\n\n\nclass BallData: # 球的信息,记录日志用\n def __init__(self, ball_or_pos, velocity=None):\n if velocity is None:\n self.pos, self.velocity = copy.copy(ball_or_pos.pos), \\\n copy.copy(ball_or_pos.velocity)\n else:\n self.pos, self.velocity = ball_or_pos, velocity\n\n\nclass Table: # 球桌\n def __init__(self):\n # 桌面坐标系的范围,单位\"pace\"\n self.xmin, self.xmax, self.ymin, self.ymax = DIM\n self.tick = 0\n self.ball = None\n # tick增加的步长\n self.tick_step = (self.xmax - self.xmin) // BALL_V[0] # 这是水平方向速度\n\n # 球拍,位置是球拍坐标系\n self.players = {'West': Racket('West', Position(self.xmin, self.ymax // 2)),\n 'East': Racket('East', Position(self.xmax, self.ymax // 2))}\n self.side = 'West' # 球的初始位置在西侧的中央,发球的首先是West\n self.op_side = 'East'\n self.players['West'].set_action(RacketAction(self.tick, 0, 0, 0))\n self.players['East'].set_action(RacketAction(self.tick, 0, 0, 0))\n\n # 是否结束\n self.finished = False\n self.winner = None\n self.reason = None\n\n def change_side(self): # 换边\n self.side, self.op_side = self.op_side, self.side\n\n def serve(self): # 发球,始终是West发球\n self.tick = 0 # 当前的时刻tick\n player = self.players[self.side] # 现在side是West\n pos_y, velocity_y = player.serve(player.datastore) # 只提供y方向的位置和速度\n self.ball = Ball(DIM, Position(BALL_POS[0], pos_y),\n Vector(BALL_V[0], velocity_y)) # 球的初始化\n self.change_side() # 换边迎球\n return\n\n def time_run(self): # 球跑一趟\n # t0时刻调用在t1时刻击球的一方\n # 1,首先让球从t0飞到t1时刻(确定轨迹)\n count_bounce = self.ball.fly(self.tick_step)\n if count_bounce not in (1, 2): # 反弹没有在1、2次,对方输了\n self.finished = True\n self.winner = self.side\n self.reason = \"invalid_bounce\"\n return\n\n # 2,调用迎球方的算法\n # 参数:t0时刻双方位置和体力值,以及跑位方的跑位方向;\n # 参数:球在t1时刻的位置和速度\n player = self.players[self.side]\n op_player = self.players[self.op_side]\n dict_side = {'position': copy.copy(player.pos),\n 'life': player.life}\n dict_op_side = {'position': copy.copy(op_player.pos),\n 'life': op_player.life,\n 'accelerate': -1 if op_player.action.acc < 0 else 1,\n 'run_vector': -1 if op_player.action.run < 0 else 1}\n dict_ball = {'position': copy.copy(self.ball.pos),\n 'velocity': copy.copy(self.ball.velocity)}\n # 调用,返回迎球方的动作\n player_action = player.play(TableData(self.tick, self.tick_step,\n dict_side, dict_op_side, dict_ball),\n player.datastore)\n player.set_action(player_action)\n\n # 执行迎球方的两个动作:迎球和加速\n player.update_pos_bat(self.tick_step)\n if not (player.pos == self.ball.pos):\n # 没接上球\n print(player.pos, self.ball.pos)\n self.finished = True\n self.winner = self.op_side\n self.reason = \"miss_ball\"\n return\n player.update_acc()\n if player.life <= 0:\n # 生命值用尽,失败\n self.finished = True\n self.winner = self.op_side\n self.reason = \"life_out\"\n return\n self.ball.update_velocity(player.action.acc)\n self.ball.bounce_racket() # 球在球拍反弹\n\n # 执行跑位方的一个动作:跑位\n op_player.update_pos_run(self.tick_step)\n if op_player.life <= 0:\n # 生命值用尽,失败\n self.finished = True\n self.winner = self.side\n self.reason = \"life_out\"\n return\n\n self.tick += self.tick_step # 时间从t0到t1\n if self.tick >= TMAX:\n # 时间到,生命值高的胜出\n self.finished = True\n self.winner = self.side if (player.life > op_player.life) else self.op_side\n self.reason = \"time_out\"\n return\n\n self.change_side() # 换边迎球\n return\n\n\nclass LogEntry:\n def __init__(self, tick, side, op_side, ball):\n self.tick = tick\n self.side = side\n self.op_side = op_side\n self.ball = ball\n","sub_path":"table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":13438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"82564400","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponse\nimport json\nfrom django.views.decorators.cache import cache_control\n#--------------------------------------------------\nwith open('data.json','r') as fh:\n data=json.load(fh)\nflights=data[\"flights\"]\ntickets=data[\"tickets\"]\ndescription={}\nfor fid,flight in data['flights'].items():\n description[fid]=0 \ncurrent_user={\"username\":\"\",\"password\":\"\"}\ncurrent_page={\"page\":\"\",\"argument\":{}}\ndisplayflights={}\nlength=len(flights)\nEdit={}\nfor fid,flight in flights.items():\n Edit[fid]=0\nadd=0\n\ndef user_loggedin():\n if request.session.get(\"username\") is not None:\n return True\n else:\n return False\ndef login(request):\n if request.method==\"GET\":\n return render(request,\"user/index.html\",{'page':'index'})\ndef index(request):\n if request.session.get(\"username\"):\n if request.session.get(\"page\") is not None:\n return redirect(request.session.get(\"page\"))\n elif request.POST.get(\"username\") is not None:\n if {'username':request.POST[\"username\"],'password':request.POST['password']} in data[\"userid\"]:\n request.session[\"username\"]=request.POST[\"username\"]\n request.session[\"password\"]=request.POST[\"password\"]\n return redirect(\"booking\") \n else:\n error=\"Wrong Credentials\"\n return render(request,\"user/index.html\", {\"error\":error})\n else:\n return redirect(\"booking\")\ndef register(request):\n if request.method==\"GET\":\n return render(request,\"user/index.html\",{'newuser':'yes'})\n elif request.POST.get(\"newusername\") is not None:\n if {\"username\":request.POST[\"newusername\"],\"password\":request.POST[\"newpassword\"]} in data[\"userid\"]:\n return render(request,\"user/index.html\",{'newuser':'yes','error':\"User already exists\"})\n else:\n data[\"userid\"].append({\"username\":request.POST[\"newusername\"],\"password\":request.POST[\"newpassword\"]})\n request.session[\"username\"]=request.POST[\"newusername\"]\n request.session[\"password\"]=request.POST[\"newpassword\"]\n data[\"tickets\"][request.session[\"username\"]]={\"ticketid\": \"1\",\"bookings\": {}}\n with open ('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n return redirect(\"booking\")\ndef logout(request):\n if request.session.get(\"username\"):\n del request.session[\"username\"]\n del request.session[\"password\"]\n else:\n return redirect(\"errorpage\")\n return redirect(\"login\")\n\ndef errorpage(request):\n return render(request,\"user/errorpage.html\")\n\n@cache_control(no_store=True, user_loggedin=True)\ndef adminpage(request):\n with open('data.json','r') as fh:\n data=json.load(fh)\n flights=data['flights']\n if request.method==\"GET\":\n if request.session.get(\"username\") ==\"durbar\":\n return render(request, \"admin.html\",{'flights':data['flights'],'add':add,'edit':Edit})\n else:\n return render(request,\"user/errorpage.html\",{'user':'durbar'})\n if request.session.get(\"username\") ==\"durbar\":\n #return render(request, \"admin.html\",{'flights':data['flights'],'add':add,'edit':Edit})\n if request.POST.get(\"addflight\") is not None:\n globals()['add']=(globals()['add']+1)%2\n #return Httprequest('',{'add':add})\n return render(request, \"admin.html\",{'flights':flights,'add':add,'edit':Edit})\n elif request.POST.get(\"add\") is not None:\n #globals()['add']=0\n if request.POST[\"id\"] in flights.keys():\n flight={\n \"id\":request.POST[\"id\"],\n \"source\":request.POST[\"source\"],\n \"destination\":request.POST[\"destination\"],\n \"deptime\":request.POST[\"deptime\"],\n \"depdate\":request.POST[\"depdate\"],\n \"arrtime\":request.POST[\"arrtime\"],\n \"arrdate\":request.POST[\"arrdate\"],\n \"capacity\":int(request.POST[\"remain\"]),\n \"remain\":int(request.POST[\"remain\"]),\n \"price\":int(request.POST[\"price\"])}\n return render(request,\"admin.html\",{'flights':flights,'flight':flight,'add':add,'edit':Edit,'error':'ERROR: This flight id aready exists'})\n remainingseats=[]\n for i in range(1,int(request.POST[\"remain\"])+1):\n remainingseats.append(str(i))\n flights[request.POST[\"id\"]]={\n \"id\":request.POST[\"id\"],\n \"source\":request.POST[\"source\"],\n \"destination\":request.POST[\"destination\"],\n \"deptime\":request.POST[\"deptime\"],\n \"depdate\":request.POST[\"depdate\"],\n \"arrtime\":request.POST[\"arrtime\"],\n \"arrdate\":request.POST[\"arrdate\"],\n \"capacity\":int(request.POST[\"remain\"]),\n \"remain\":int(request.POST[\"remain\"]),\n \"remainingseats\":remainingseats,\n \"price\":int(request.POST[\"price\"])}\n data[\"flights\"]=flights\n with open('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n Edit[request.POST[\"id\"]]=0\n return render(request,\"admin.html\",{'flights':flights,'add':add,'edit':Edit})\n elif request.POST.get(\"editbutton\") is not None:\n Edit[request.POST[\"editbutton\"]]=(Edit[request.POST[\"editbutton\"]]+1)%2\n return render(request, \"admin.html\", {'flights':flights,'add':add,'edit':Edit})\n elif request.POST.get(\"editdetailsbtn\") is not None:\n del flights[request.POST[\"editdetailsbtn\"]]\n del Edit[request.POST[\"editdetailsbtn\"]]\n remainingseats=[]\n for i in range(1,int(request.POST[\"remain\"])+1):\n remainingseats.append(str(i))\n flights[request.POST[\"id\"]]={ \n \"id\":request.POST[\"id\"],\n \"source\":request.POST[\"source\"],\n \"destination\":request.POST[\"destination\"],\n \"deptime\":request.POST[\"deptime\"],\n \"depdate\":request.POST[\"depdate\"],\n \"arrtime\":request.POST[\"arrtime\"],\n \"arrdate\":request.POST[\"arrdate\"],\n \"capacity\":int(request.POST[\"remain\"]),\n \"remain\":int(request.POST[\"remain\"]),\n \"remainingseats\":remainingseats,\n \"price\":int(request.POST[\"price\"])}\n data[\"flights\"]=flights\n Edit[request.POST[\"id\"]]=0\n with open('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n return render(request, \"admin.html\",{'flights':flights,'add':add,'edit':Edit})\n elif request.POST.get(\"deletebutton\") is not None:\n flight=flights[request.POST[\"deletebutton\"]]\n cancelled_tickets={}\n for user in data[\"userid\"]:\n cancelled_tickets[user[\"username\"]]=[]\n for user, tickets in data[\"tickets\"].items():\n for tickid, booking in tickets[\"bookings\"].items():\n if booking[\"fid\"]==request.POST[\"deletebutton\"]:\n cancelled_tickets[user].append(tickid)\n for user,ticks in cancelled_tickets.items():\n for ticketid in ticks:\n data[\"tickets\"][user][\"bookings\"][ticketid][\"status\"]=\"flight_cancelled\"\n data[\"tickets\"][user][\"bookings\"][ticketid][\"flightdetails\"]=flight[\"source\"]+\" (\"+flight[\"depdate\"]+\" at \"+flight[\"deptime\"]+\")\"+\" to \"+flight[\"destination\"]+\" (\"+flight[\"arrdate\"]+\" at \"+flight[\"arrtime\"]+\")\"\n del flights[request.POST[\"deletebutton\"]]\n del Edit[request.POST[\"deletebutton\"]]\n data[\"flights\"]=flights\n with open('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n return render(request, \"admin.html\",{'flights':flights,'add':add,'edit':Edit})\n#@cache_control(no_store=True, user_loggedin=True)\ndef booking(request):\n request.session[\"page\"]=\"booking\"\n with open ('data.json',\"r\") as json_file:\n data=json.load(json_file)\n flights= data[\"flights\"]\n request.session[\"pagehtml\"]=\"user/booking.html\"\n request.session[\"pageargument\"]={'flights':flights,'description':description,'user':request.session.get(\"username\")}\n #Booking another ticket after payment (from payment page)\n if request.POST.get(\"anotherbooking\") is not None:\n tickets=data[\"tickets\"]\n ticketid=tickets[request.session[\"username\"]][\"ticketid\"]\n fid=tickets[request.session[\"username\"]][\"bookings\"][ticketid][\"fid\"]\n data[\"flights\"][fid]=tickets[request.session[\"username\"]][\"bookings\"][ticketid][\"flight\"]\n del data[\"tickets\"][request.session[\"username\"]][\"bookings\"][ticketid][\"flight\"]\n tickets[request.session[\"username\"]][\"ticketid\"]=str(int(ticketid)+1)\n data[\"tickets\"]=tickets\n description[fid]=0\n with open('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n return render(request,\"user/booking.html\",{'flights':flights,'description':description,'user':request.session[\"username\"]})\n #Cancel payment on payment page and go back to booking page\n elif request.POST.get(\"cancelpayment\") is not None:\n ticketid=request.POST[\"cancelpayment\"]\n fid=data[\"tickets\"][request.session[\"username\"]][\"bookings\"][ticketid][\"fid\"]\n seatdetails=data[\"tickets\"][request.session[\"username\"]][\"bookings\"][ticketid][\"seatdetails\"]\n for seat,tick in seatdetails.items():\n data[\"flights\"][fid][\"remainingseats\"].append(seat)\n data[\"flights\"][fid][\"remain\"]+=1\n del data[\"tickets\"][request.session[\"username\"]][\"bookings\"][ticketid][\"seatdetails\"]\n data[\"flights\"][fid][\"price\"]/=1.05**(int((data[\"flights\"][fid][\"capacity\"]-flights[fid][\"remain\"])/10))\n del data[\"tickets\"][request.session[\"username\"]][\"bookings\"]\n data[\"tickets\"][request.session[\"username\"]][\"bookings\"]={}\n description[fid]=0\n with open('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n return render(request,\"user/booking.html\",{'flights':flights,'description':description,'user':request.session[\"username\"]})\n #Description button-click\n elif request.POST.get(\"description\") is not None:\n fid=request.POST[\"description\"]\n description[fid]=(description[fid]+1)%2\n if len(displayflights)==0:\n return render(request,\"user/booking.html\",{'flights':flights,'description':description,'user':request.session.get(\"username\")})\n else:\n return render(request,\"user/booking.html\",{\"flights\":displayflights,'description':description,'user':request.session.get(\"username\")})\n #Go back from My bookings page\n elif request.POST.get(\"goback\") is not None:\n if len(displayflights)==0:\n return render(request,\"user/booking.html\",{'flights':flights,'description':description,'user':request.session[\"username\"]})\n else:\n return render(request,\"user/booking.html\",{\"flights\":displayflights,'description':description,'user':request.session[\"username\"]})\n # Search for Flights\n elif request.POST.get(\"sourcesearch\") is not None:\n displayflights.clear()\n if request.POST.get(\"sourcesearch\")!=\"\" and request.POST.get(\"destinationsearch\")!=\"\":\n for fid,flight in flights.items():\n if flight[\"source\"]==request.POST.get(\"sourcesearch\") and flight[\"destination\"]==request.POST.get(\"destinationsearch\"):\n displayflights[fid]=flight\n if displayflights:\n return render(request, \"user/booking.html\",{'flights':displayflights,'description':description,'user':request.session[\"username\"]})\n else:\n return render(request, \"user/booking.html\",{'message':\"No flights for your search\"})\n return render(request, \"user/booking.html\",{'flights':displayflights})\n elif request.POST.get(\"sourcesearch\")==\"\" and request.POST.get(\"destinationsearch\")==\"\":\n return render(request, \"user/booking.html\",{'flights':flights,'message':\"ERROR: Please type something\",'description':description,'user':request.session[\"username\"]})\n else:\n for fid,flight in flights.items():\n if flight[\"source\"]==request.POST.get(\"sourcesearch\") or flight[\"destination\"]==request.POST.get(\"destinationsearch\"):\n displayflights[fid]=flight \n return render(request, \"user/booking.html\",{'flights':displayflights,'description':description,'user':request.session[\"username\"]})\n #DO NOT BOOK\n elif request.POST.get(\"donotbook\") is not None:\n ticketid=data[\"tickets\"][request.session[\"username\"]][\"ticketid\"]\n del data[\"tickets\"][request.session[\"username\"]][\"bookings\"][ticketid]\n with open('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n return render(request,\"user/booking.html\",{'flights':flights,'description':description,'user':request.session[\"username\"]})\n #Directly enetring into bookings\n else:\n return render(request,request.session[\"pagehtml\"],request.session[\"pageargument\"])\n@cache_control(no_store=True, user_loggedin=True)\ndef payment(request):\n request.session[\"page\"]=\"payment\"\n if request.session.get(\"username\") is None:\n return redirect(\"errorpage\")\n elif request.POST.get(\"submitdetails\"):\n with open ('data.json',\"r+\") as json_file:\n data=json.load(json_file)\n tickets=data[\"tickets\"]\n flights=data[\"flights\"]\n ticketid=data[\"tickets\"][request.session[\"username\"]][\"ticketid\"]\n ticket=data[\"tickets\"][request.session[\"username\"]][\"bookings\"][ticketid]\n seatdetails={}\n fid=ticket[\"fid\"]\n flight=data[\"flights\"][fid]\n totalcost=flights[fid][\"price\"]*int(request.POST[\"submitdetails\"])\n for h in range(1,1+int(request.POST[\"submitdetails\"])):\n tempdict={\"name\":request.POST[\"name\"+str(h)],\"age\":request.POST[\"age\"+str(h)],\"gender\":request.POST[\"gender\"+str(h)],\"meals\":request.POST[\"meals\"+str(h)]}\n tempdict[\"ticketcost\"]=flights[fid][\"price\"]\n if request.POST[\"meals\"+str(h)]==\"yes\":\n tempdict[\"ticketcost\"]+=500\n totalcost+=500\n seatdetails[flight[\"remainingseats\"].pop(0)]=tempdict\n ticket[\"seatdetails\"]=seatdetails\n ticket[\"cost\"]=totalcost\n ticket[\"no\"]=int(request.POST[\"submitdetails\"])\n flight[\"remain\"]-=int(request.POST[\"submitdetails\"])\n flight[\"price\"]*=1.05**(int((flights[fid][\"capacity\"]-flights[fid][\"remain\"])/10))\n ticket[\"flight\"]=flight\n tickets[request.session[\"username\"]][\"bookings\"][ticketid]=ticket\n flightdetails=flight[\"source\"]+\" (\"+flight[\"depdate\"]+\" at \"+flight[\"deptime\"]+\")\"+\" to \"+flight[\"destination\"]+\" (\"+flight[\"arrdate\"]+\" at \"+flight[\"arrtime\"]+\")\"\n data[\"tickets\"]=tickets\n with open('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n request.session[\"pagehtml\"]=\"user/payment.html\"\n request.session[\"pageargument\"]={'flightdetails':flightdetails,'ticket':ticket,'tickets':json.dumps(tickets),'tickid':ticketid}\n return render(request,\"user/payment.html\",{'flightdetails':flightdetails,'ticket':ticket,'tickets':json.dumps(tickets),'tickid':ticketid})\n else:\n if request.session.get(\"username\") is not None:\n return render(request,request.session[\"pagehtml\"],request.session[\"pageargument\"])\n\n@cache_control(no_store=True, user_loggedin=True)\ndef ticketbooking(request):\n request.session[\"page\"]=\"ticketbooking\"\n if request.session.get(\"username\") is None:\n return redirect(\"errorpage\")\n elif request.POST.get(\"bookticket\"):\n with open ('data.json',\"r\") as json_file:\n data=json.load(json_file)\n ticketid=data[\"tickets\"][request.session[\"username\"]][\"ticketid\"]\n data[\"tickets\"][request.session[\"username\"]][\"bookings\"][ticketid]={\"fid\":request.POST[\"bookticket\"]}\n with open ('data.json',\"w\") as json_file:\n json.dump(data,json_file,indent=4)\n request.session[\"pagehtml\"]=\"user/ticketbooking.html\"\n request.session[\"pageargument\"]={\"numberofpassengers\":request.POST[\"number\"]}\n return render(request,\"user/ticketbooking.html\",{\"numberofpassengers\":request.POST[\"number\"]})\n else:\n if request.session.get(\"username\"):\n return render(request,request.session[\"pagehtml\"],request.session[\"pageargument\"])\n@cache_control(no_store=True, user_loggedin=True)\ndef mybookings(request):\n request.session[\"page\"]=\"mybookings\"\n if request.session.get(\"username\") is None:\n return redirect(\"errorpage\")\n with open ('data.json',\"r\") as json_file:\n data=json.load(json_file)\n flights= data[\"flights\"]\n tickets=data[\"tickets\"]\n request.session[\"pagehtml\"]=\"user/Mybookings.html\"\n if request.POST.get(\"goback\"):\n return render(request, \"user/mtbookings.html\",{'tickets':tickets[request.session[\"username\"]][\"bookings\"]})\n else:\n if request.session[\"username\"]:\n request.session[\"pageargument\"]={'tickets':tickets[request.session[\"username\"]][\"bookings\"],'number':1}\n return render(request,request.session[\"pagehtml\"],{'tickets':tickets[request.session[\"username\"]][\"bookings\"],'flights':flights,'message':\"You have no bookings\"})\n@cache_control(no_store=True, user_loggedin=True)\ndef cancelbooking(request):\n request.session[\"page\"]=\"cancelbooking\"\n if request.session.get(\"username\") is None:\n return redirect(\"errorpage\")\n request.session[\"pagehtml\"]=\"user/cancelbooking.html\"\n with open ('data.json',\"r+\") as json_file:\n data=json.load(json_file)\n flights= data[\"flights\"]\n tickets=data[\"tickets\"]\n if request.POST.get(\"cancelbooking\") is not None:\n return render(request, \"user/cancelbooking.html\", {'tickid':request.POST[\"cancelbooking\"],'seatdetails':tickets[request.session[\"username\"]][\"bookings\"][request.POST[\"cancelbooking\"]][\"seatdetails\"]})\n\n elif request.POST.get(\"cancelticket\"):\n string=request.POST[\"cancelticket\"].split(\"-\")\n ticketid=string[1]\n fid=tickets[request.session[\"username\"]][\"bookings\"][ticketid][\"fid\"] \n tickets[request.session[\"username\"]][\"bookings\"][ticketid][\"cost\"]-=tickets[request.session[\"username\"]][\"bookings\"][ticketid][\"seatdetails\"][string[0]][\"ticketcost\"]\n tickets[request.session[\"username\"]][\"bookings\"][ticketid][\"no\"]-=1\n del tickets[request.session[\"username\"]][\"bookings\"][ticketid][\"seatdetails\"][string[0]]\n flights[fid][\"remain\"]+=1\n flights[fid][\"remainingseats\"].append(string[0])\n flights[fid][\"price\"]/=1.05**(int((flights[fid][\"capacity\"]-flights[fid][\"remain\"])/10))\n data[\"tickets\"][request.session[\"username\"]][\"bookings\"][ticketid][\"flight\"]=data[\"flights\"][fid]\n if tickets[request.session[\"username\"]][\"bookings\"][ticketid][\"cost\"]==0:\n del tickets[request.session[\"username\"]][\"bookings\"][ticketid]\n data[\"tickets\"]=tickets\n data[\"flights\"]=flights\n with open('data.json','w') as fh:\n json.dump(data,fh,indent=4)\n request.session[\"pageargument\"]={'tickets':tickets[request.session[\"username\"]][\"bookings\"],'message':\"You have no bookings\"}\n return render(request,\"user/Mybookings.html\",{'tickets':tickets[request.session[\"username\"]][\"bookings\"],'message':\"You have no bookings\"})\n else:\n return render(request,request.session[\"pagehtml\"],request.session[\"pageargument\"])","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"422348563","text":"from scipy.optimize import minimize, Bounds\r\nimport numpy as np\r\nimport equadratures as eq\r\nfrom trustregion import TrustRegion \r\n\r\nnp.random.seed(0)\r\n\r\ndef compare_optimisation(fun, s0):\r\n dims = s0.size\r\n TR = TrustRegion(fun)\r\n s0 = np.zeros(dims)\r\n sopt, fopt = TR.trust_region(s0)\r\n print(\"Using our trust-region method, an optimal value of {} was found after {} function evaluations\".format(fopt, TR.num_evals))\r\n \r\n methods = ['COBYLA', 'trust-constr']\r\n for method in methods:\r\n if method == 'COBYLA':\r\n cons = []\r\n for factor in range(dims):\r\n l = {'type': 'ineq',\r\n 'fun': lambda s, lb=-1.0, i=factor: s[i] - lb}\r\n u = {'type': 'ineq',\r\n 'fun': lambda s, ub=1.0, i=factor: ub - s[i]}\r\n cons.append(l)\r\n cons.append(u)\r\n sol = minimize(fun, s0, method=method, constraints=cons)\r\n else:\r\n bounds = Bounds(-np.ones(dims), np.ones(dims))\r\n sol = minimize(fun, s0, method=method, bounds=bounds)\r\n print(\"Using {}, an optimal value of {} was found after {} function evaluations\".format(method, sol['fun'], sol['nfev']))\r\n","sub_path":"incomplete_notebooks/james/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"294440353","text":"# Write your code here\nclass CoffeeMachine:\n menu = {\"espresso\": {\"water\": 250, \"coffee beans\": 16, \"disposable cups\": 1, \"money\": -4},\n \"latte\": {\"water\": 350, \"milk\": 75, \"coffee beans\": 20, \"disposable cups\": 1, \"money\": -7},\n \"cappuccino\": {\"water\": 200, \"milk\": 100, \"coffee beans\": 12, \"disposable cups\": 1, \"money\": -6}}\n supplies = {}\n status = None\n index_supplies = 0\n order = None\n item = None\n cant = 0\n items = []\n # Como emulo un unum??\n\n def __init__(self):\n self.supplies = {\"water\": 400, \"milk\": 540, \"coffee beans\": 120, \"disposable cups\": 9, \"money\": 550}\n self.status = 0 # Idle\n self.index_supplies = 0\n self.print_message()\n\n def get_action(self, action):\n if self.status == 0:\n if action == \"buy\":\n self.status = 1\n elif action == \"fill\":\n self.index_supplies = 0\n self.status = 2\n elif action == \"take\":\n self.action_take()\n elif action == \"remaining\":\n self.print_status()\n elif action == \"exit\":\n return False\n else:\n print(\"INVALID ACTION\")\n elif self.status == 1:\n if action == 'back':\n self.order = action\n self.action_buy()\n else:\n self.order = self.items[int(action) - 1]\n self.action_buy()\n elif self.status == 2:\n self.cant = int(action)\n self.action_fill()\n self.print_message()\n return True\n\n def print_message(self):\n print()\n if self.status == 0:\n print(\"Write action (buy, fill, take, remaining, exit):\")\n elif self.status == 1: # Selling\n self.print_menu()\n elif self.status == 2: # Filling\n self.fill_item()\n\n def print_menu(self):\n print(\"What do you want to buy?\", end=\"\")\n self.items = []\n items_list = []\n i = 1\n for item in self.menu:\n self.items.append(item)\n items_list.append(\" \" + str(i) + \" - \" + item)\n i += 1\n print(','.join(items_list), end=\"\")\n print(\", back - to main menu:\")\n\n def print_status(self):\n print()\n print(\"The coffee machine has:\")\n for item, cant in self.supplies.items():\n print(f\"{cant} of {item}\")\n\n def action_take(self):\n amount = self.supplies.get(\"money\")\n print()\n print(f\"I gave you ${amount}\")\n self.supplies[\"money\"] = 0\n\n def action_fill(self):\n self.supplies[self.item] += self.cant\n if self.index_supplies >= len(self.supplies) - 1:\n self.status = 0\n\n def fill_item(self):\n index_item = 0\n for item in self.supplies:\n if index_item == self.index_supplies:\n cur_item = item\n if cur_item != \"money\":\n self.item = cur_item\n print(f\"Write how many {cur_item} do you want to add:\")\n index_item += 1\n self.index_supplies += 1\n\n def chek_items(self):\n ingredients = self.menu.get(self.order)\n for item in ingredients:\n if self.supplies[item] < ingredients.get(item):\n return item\n return None\n\n def action_buy(self):\n order = self.order\n if order == \"back\":\n self.status = 0\n return None\n item = self.chek_items()\n if item is not None:\n print(f\"Sorry, not enough {item}!\")\n self.status = 0\n return None\n print(\"I have enough resources, making you a coffee!\")\n self.prepare_order()\n self.status = 0\n\n def prepare_order(self):\n ingredients = self.menu.get(self.order)\n for item in ingredients:\n self.supplies[item] -= ingredients.get(item)\n\n\nmi_cafetera = CoffeeMachine()\nwhile True:\n if not mi_cafetera.get_action(input()):\n break\n\n\n","sub_path":"Coffee Machine/task/machine/coffee_machine.py","file_name":"coffee_machine.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"187228455","text":"import glob\nimport os\nimport sys\nimport re\nimport statistics\n\nexecution_times = list()\nvalues = list()\n\nfor filename in sys.argv[2:]:\n f = open(filename)\n trace = f.read()\n f.close()\n execution_times.append(\n float(re.search('Execution Time = (.*)', trace).group(1)))\n values.append(\n float(re.search('Expected Makespan = (.*)', trace).group(1)))\n\nf = open(sys.argv[1], 'w+')\n\nf.write('Best = '+str(min(values))+'\\n')\nf.write('Average = '+str(statistics.mean(values))+'\\n')\nf.write('Standard deviation = '+str(statistics.stdev(values))+'\\n')\nf.write('Average execution time = ' +\n str(statistics.mean(execution_times)/1000000)+'\\n')\n\nf.close()\n","sub_path":"scripts/stats/calculate_stats_fjsp.py","file_name":"calculate_stats_fjsp.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"178815883","text":"#encoding:utf-8\nfrom django.conf.urls import url\nfrom blog import views\n\n\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^archive/', views.archive,name = 'archive'),\n url(r'^tags/', views.archive,name = 'tags'),\n url(r'^article/', views.article,name = 'article'),\n url(r'^comment/post/$', views.comment_post,name = 'comment_post'),\n url(r'^logout', views.do_logout,name = 'logout'),\n url(r'^reg', views.do_reg,name = 'reg'),\n url(r'^login', views.do_login,name = 'login'),\n\n]","sub_path":"blog_project/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"239100577","text":"import os\nimport sys\nimport pathlib\nimport subprocess\n\nmissing_folders = [\n \"./content/Clinical Skills\",\n \"./content/Clinical Knowledge/5 Urology/7 Traumatic Injuries\",\n]\n\nif __name__ == \"__main__\":\n\n if((len(sys.argv) < 3 or len(sys.argv) > 4) or (len(sys.argv) == 3 and (sys.argv[1] == '-i' or sys.argv[1] == '--index' or sys.argv[1] == '-a' or sys.argv[1] == '--all'))):\n print(\"Run as \\\"python encrypt.py \\\"\")\n exit()\n\n if(len(sys.argv) == 3 and (sys.argv[2] == '--all' or sys.argv[2] == '-a')):\n # Encrypts all data\n root_dir = './content-source'\n for old_dir, subdirectories, files in os.walk(root_dir):\n for file in files:\n # print(os.path.join(old_dir, file))\n # print(old_dir + '/' + file)\n new_dir = old_dir.split('/')\n new_dir[1] = 'content'\n new_dir = '/'.join(new_dir)\n\n pathlib.Path(new_dir).mkdir(parents=True, exist_ok=True) \n old_file = os.path.join(old_dir, file)\n new_file = os.path.join(new_dir, file)\n\n # os.system('staticrypt \"' + old_file + '\" ' + str(sys.argv[1]) + ' -o \"' + new_file + '\" -f encrypt_template.html')\n subprocess.call([\"staticrypt\", old_file, str(sys.argv[1]), \"-o\", new_file, \"-f\", \"encrypt_template.html\"])\n\n # Puts in missing folders\n for folder in missing_folders:\n pathlib.Path(folder).mkdir(parents=True, exist_ok=True) \n\n if(len(sys.argv) == 3 and (sys.argv[2] == '--index' or sys.argv[2] == '-i') or len(sys.argv) == 3 and (sys.argv[2] == '--all' or sys.argv[2] == '-a')):\n # Encrypts index\n # os.system('staticrypt index-source.html ' + str(sys.argv[1]) + ' -o index.html -f index_template.html')\n subprocess.call([\"staticrypt\", \"index-source.html\", str(sys.argv[1]), \"-o\", \"index.html\", \"-f\", \"index_template.html\"])\n","sub_path":"amboss/encrypt.py","file_name":"encrypt.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"6580552","text":"#Get the list of trains running between two stations\nimport db\nimport json\n\ndef comes_after(train,source,dest):\n '''Checks that source comes before dest in the train's path'''\n\n with db.opendb(db.MAINDB) as stnlist:\n stnlist._exec(\"SELECT station from schedule WHERE train=(?)\",(train,))\n array=[]\n t=stnlist._fetchone()\n while(t!=None):\n array.append(t['station'])\n t=stnlist._fetchone()\n \n if(array==[]):\n return 0;\n \n try:\n a=array.index(source)\n b=array.index(dest)\n except ValueError:\n return 0\n\n if(a')\ndef uploaded_files(filename):\n path = app.config['UPLOADED_PATH']\n return send_from_directory(path, filename)\n\n\n@app.route('/static/upload', methods=['POST'])\ndef upload():\n f = request.files.get('upload')\n\n extension = f.filename.split('.')[1].lower()\n if extension not in ['jpg', 'gif', 'png', 'jpeg']:\n return upload_fail(message='Image only!')\n f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename+'1'))\n url = url_for('uploaded_files', filename=f.filename)\n return upload_success(url=url)\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n# def gen_rnd_filename():\n# filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n# return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))\n\n\n# @app.route('/ckupload/', methods=['POST'])\n# def ckupload():\n# \"\"\"CKEditor file upload\"\"\"\n# error = ''\n# url = ''\n# callback = request.args.get(\"CKEditorFuncNum\")\n# if request.method == 'POST' and 'upload' in request.files:\n# fileobj = request.files['upload']\n# fname, fext = os.path.splitext(fileobj.filename)\n# rnd_name = '%s%s' % (gen_rnd_filename(), fext)\n# filepath = os.path.join(app.static_folder, 'upload', rnd_name)\n# # 检查路径是否存在,不存在则创建\n# dirname = os.path.dirname(filepath)\n# if not os.path.exists(dirname):\n# try:\n# os.makedirs(dirname)\n# except:\n# error = 'ERROR_CREATE_DIR'\n# elif not os.access(dirname, os.W_OK):\n# error = 'ERROR_DIR_NOT_WRITEABLE'\n# if not error:\n# fileobj.save(filepath)\n# url = url_for('static', filename='%s/%s' % ('upload', rnd_name))\n# else:\n# error = 'post error'\n# res = \"\"\"\n#\n# \n#\n# \"\"\" % (callback, url, error)\n# response = make_response(res)\n# response.headers[\"Content-Type\"] = \"text/html\"\n# return response","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"312374782","text":"import socket\n\nHOST = '127.0.0.1'\nPORT = 7777\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n while True:\n try: \n input_data = input()\n s.sendall(input_data.encode())\n data = s.recv(1024)\n print('Received', data)\n except KeyboardInterrupt:\n break\n","sub_path":"exercises/python_exercises/client_m.py","file_name":"client_m.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"120242143","text":"import requests\nimport base64\nfrom celery import shared_task\nfrom django.conf import settings\n\nfrom momo_requests.models import MomoRequest\n\n\ndef create_basic_auth_header(api_user_id='', api_key=''):\n \"\"\"Creates a Basic Auth header for the MOMO Open API\"\"\"\n base64_encoded_header = base64.b64encode(\n '{api_user_id}:{api_key}'.format(api_user_id=api_user_id, api_key=api_key\n ).encode('utf-8'))\n return 'Basic {}'.format(base64_encoded_header.decode('utf-8'))\n\n\n@shared_task\ndef authenticate_with_momo():\n \"\"\"\n Authenticates with the MOMO API to return an\n {\n \"access_token\": \"string\",\n \"token_type\": \"string\",\n \"expires_in\": 0\n }\n \"\"\"\n endpoint_url = \"{}/collection/token/\".format(settings.MOMO_BASE_URL)\n basic_auth_header = create_basic_auth_header(\n api_user_id=settings.MOMO_API_USER_ID, api_key=settings.MOMO_API_KEY)\n headers = {\n 'Authorization': basic_auth_header,\n 'Ocp-Apim-Subscription-Key': settings.MOMO_SUBSCRIPTION_KEY_FOR_COLLECTIONS\n }\n response = requests.post(endpoint_url, headers=headers)\n if(response.ok):\n return response.json()\n\n\n@shared_task\ndef request_for_payment(momo_request_id):\n \"\"\"\n Makes a remote request to the MOMO API\n to request for payment from a payer\n \"\"\"\n auth_response = authenticate_with_momo()\n\n if auth_response:\n # get the MomoRequest\n # pylint: disable=no-member\n momo_request = MomoRequest.objects.get(id=momo_request_id)\n endpoint_url = '{}/collection/v1_0/requesttopay'.format(\n settings.MOMO_BASE_URL)\n\n headers = {\n 'Authorization': 'Bearer {}'.format(auth_response['access_token']),\n 'X-Reference-Id': str(momo_request.reference_id),\n 'X-Target-Environment': settings.MOMO_TARGET_ENVIRONMENT,\n 'Content-Type': 'application/json',\n 'Ocp-Apim-Subscription-Key': settings.MOMO_SUBSCRIPTION_KEY_FOR_COLLECTIONS\n }\n\n data = {\n 'amount': momo_request.amount,\n 'currency': momo_request.currency,\n 'externalId': str(momo_request.external_id),\n 'payer': {\n 'partyIdType': momo_request.payer_party_id_type,\n 'partyId': momo_request.payer_party_id,\n },\n 'payerMessage': momo_request.payer_message,\n 'payeeNote': momo_request.payee_note\n }\n\n payment_response = requests.post(\n endpoint_url, data=data, headers=headers)\n\n if not payment_response.ok:\n momo_request.status = 'FAILED'\n momo_request.save()\n else:\n raise Exception('Failed to authenticate with MOMO API')\n\n\ndef update_payment_status(momo_request):\n \"\"\"\n Calls the MOMO api to determine the status of \n the MomoRequest\n \"\"\"\n # poll only payments that have 'PENDING' status\n if momo_request.status != 'PENDING':\n return\n\n auth_response = authenticate_with_momo()\n if auth_response:\n endpoint_url = '{0}/collection/v1_0/requesttopay/{1}'.format(\n settings.MOMO_BASE_URL, str(momo_request.reference_id))\n headers = {\n 'Authorization': 'Bearer {}'.format(auth_response['access_token']),\n 'X-Target-Environment': settings.MOMO_TARGET_ENVIRONMENT,\n 'Content-Type': 'application/json',\n 'Ocp-Apim-Subscription-Key': settings.MOMO_SUBSCRIPTION_KEY_FOR_COLLECTIONS\n }\n\n api_response = requests.get(endpoint_url, headers=headers)\n parsed_response = api_response.json()\n status = parsed_response.get('status')\n\n if(api_response.status_code == 404):\n momo_request.status = parsed_response.get('code')\n momo_request.reason = parsed_response.get('message')\n momo_request.save()\n\n elif(api_response.ok and status != 'PENDING'):\n momo_request.status = status\n momo_request.reason = parsed_response.get(\n 'reason', {}).get('message', '')\n momo_request.financial_transaction_id = parsed_response.get(\n 'financialTransactionId')\n momo_request.save()\n\n else:\n raise Exception('Failed to authenticate with MOMO API')\n\n\n@shared_task\ndef update_status_for_all_pending_payments():\n \"\"\"\n Retrieves all MomoRequest instances that have pending\n status and loops through each updating the status\n \"\"\"\n # pylint: disable=no-member\n all_pending_momo_requests = MomoRequest.objects.filter(status='PENDING')\n for momo_request in all_pending_momo_requests:\n update_payment_status(momo_request)\n","sub_path":"momo_requests/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"626622494","text":"#!/usr/bin/env python\r\nfrom __future__ import print_function\r\nimport os\r\nimport re\r\nimport sys\r\nimport json\r\nimport time\r\nimport hashlib\r\nimport binascii\r\nimport tarfile\r\nimport ssl\r\nimport atexit\r\n\r\n#xunlei use self-signed certificate; on py2.7.9+\r\nif hasattr(ssl, '_create_unverified_context') and hasattr(ssl, '_create_default_https_context'):\r\n ssl._create_default_https_context = ssl._create_unverified_context\r\n\r\nrsa_mod = 0xD6F1CFBF4D9F70710527E1B1911635460B1FF9AB7C202294D04A6F135A906E90E2398123C234340A3CEA0E5EFDCB4BCF7C613A5A52B96F59871D8AB9D240ABD4481CCFD758EC3F2FDD54A1D4D56BFFD5C4A95810A8CA25E87FDC752EFA047DF4710C7D67CA025A2DC3EA59B09A9F2E3A41D4A7EFBB31C738B35FFAAA5C6F4E6F\r\nrsa_pubexp = 0x010001\r\nPY3K = sys.version.startswith('3')\r\nif not PY3K:\r\n import urllib2\r\n from cStringIO import StringIO as sio\r\n rsa_pubexp = long(rsa_pubexp)\r\nelse:\r\n import urllib.request as urllib2\r\n from io import BytesIO as sio\r\n\r\naccount_file_encrypted = '.swjsq.account'\r\naccount_file_plain = 'swjsq.account.txt'\r\nshell_file = 'swjsq_wget.sh'\r\nipk_file = 'swjsq_0.0.1_all.ipk'\r\n\r\ntry:\r\n from Crypto.PublicKey import RSA\r\nexcept ImportError:\r\n #slow rsa\r\n print('Warning: pycrypto not found, use pure-python implemention')\r\n rsa_result = {}\r\n def cached(func):\r\n def _(s):\r\n if s in rsa_result:\r\n _r = rsa_result[s]\r\n else:\r\n _r = func(s)\r\n rsa_result[s] = _r\r\n return _r\r\n return _\r\n # https://github.com/mengskysama/XunLeiCrystalMinesMakeDie/blob/master/run.py\r\n def modpow(b, e, m):\r\n result = 1\r\n while (e > 0):\r\n if e & 1:\r\n result = (result * b) % m\r\n e = e >> 1\r\n b = (b * b) % m\r\n return result\r\n\r\n def str_to_int(string):\r\n str_int = 0\r\n for i in range(len(string)):\r\n str_int = str_int << 8\r\n str_int += ord(string[i])\r\n return str_int\r\n\r\n @cached\r\n def rsa_encode(data):\r\n result = modpow(str_to_int(data), rsa_pubexp, rsa_mod)\r\n return \"{0:0256X}\".format(result) # length should be 1024bit, hard coded here\r\nelse:\r\n cipher = RSA.construct((rsa_mod, rsa_pubexp))\r\n def rsa_encode(s):\r\n if PY3K and isinstance(s, str):\r\n s = s.encode(\"utf-8\")\r\n _ = binascii.hexlify(cipher.encrypt(s, None)[0]).upper()\r\n if PY3K:\r\n _ = _.decode(\"utf-8\")\r\n return _\r\n\r\n\r\nTYPE_NORMAL_ACCOUNT = 0\r\nTYPE_NUM_ACCOUNT = 1\r\n\r\nUNICODE_WARNING_SHOWN = False\r\n\r\nheader_xl = {\r\n 'Content-Type':'',\r\n 'Connection': 'Keep-Alive',\r\n 'Accept-Encoding': 'gzip',\r\n 'User-Agent': 'android-async-http/1.4.3 (http://loopj.com/android-async-http)'\r\n}\r\nheader_api = {\r\n 'Content-Type':'',\r\n 'Connection': 'Keep-Alive',\r\n 'Accept-Encoding': 'gzip',\r\n 'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.0.1; SmallRice Build/LRX22C)'\r\n}\r\n\r\ndef get_mac(nic = '', to_splt = ':'):\r\n if os.name == 'nt':\r\n cmd = 'ipconfig /all'\r\n splt = '-'\r\n elif os.name == \"posix\":\r\n cmd = 'ifconfig %s' % (nic or '-a')\r\n splt = ':'\r\n else:\r\n return ''\r\n try:\r\n r = os.popen(cmd).read()\r\n if r:\r\n _ = re.findall('((?:[0-9A-Fa-f]{2}%s){5}[0-9A-Fa-f]{2})' % splt, r)\r\n if not _:\r\n return ''\r\n else:\r\n return _[0].replace(splt, to_splt)\r\n except:\r\n pass\r\n return '000000000000004V'\r\n\r\n\r\ndef long2hex(l):\r\n return hex(l)[2:].upper().rstrip('L')\r\n\r\n\r\ndef uprint(s, fallback = None, end = None):\r\n global UNICODE_WARNING_SHOWN\r\n while True:\r\n try:\r\n print(s, end = end)\r\n except UnicodeEncodeError:\r\n if UNICODE_WARNING_SHOWN:\r\n print('Warning: locale of your system may not be utf8 compatible, output will be truncated')\r\n UNICODE_WARNING_SHOWN = True\r\n else:\r\n break\r\n try:\r\n print(s.encode('utf-8'), end = end)\r\n except UnicodeEncodeError:\r\n if fallback:\r\n print(fallback, end = end)\r\n break\r\n\r\ndef http_req(url, headers = {}, body = None, encoding = 'utf-8'):\r\n req = urllib2.Request(url)\r\n for k in headers:\r\n req.add_header(k, headers[k])\r\n if sys.version.startswith('3') and isinstance(body, str):\r\n body = bytes(body, encoding = 'ascii')\r\n resp = urllib2.urlopen(req, data = body)\r\n ret = resp.read().decode(encoding)\r\n if sys.version.startswith('3') and isinstance(ret, bytes):\r\n ret = str(ret)\r\n return ret\r\n\r\ndef login_xunlei(uname, pwd_md5, login_type = TYPE_NORMAL_ACCOUNT):\r\n pwd = rsa_encode(pwd_md5)\r\n ct = http_req('https://login.mobile.reg2t.sandai.net:443/', body = json.dumps(\r\n {\r\n \"protocolVersion\": 101,\r\n \"sequenceNo\": 1000001,\r\n \"platformVersion\": 1,\r\n \"peerID\": MAC,\r\n \"businessType\": 68,\r\n \"clientVersion\": \"1.1\",\r\n \"isCompressed\": 0,\r\n \"cmdID\": 1,\r\n \"userName\": uname,\r\n \"passWord\": pwd,\r\n \"loginType\": login_type,\r\n \"sessionID\": \"\",\r\n \"verifyKey\": \"\",\r\n \"verifyCode\": \"\",\r\n \"appName\": \"ANDROID-com.xunlei.vip.swjsq\",\r\n \"rsaKey\": {\r\n \"e\": long2hex(rsa_pubexp),\r\n \"n\": long2hex(rsa_mod)\r\n },\r\n \"extensionList\": \"\"\r\n }), headers = header_xl, encoding = 'gbk'\r\n )\r\n return json.loads(ct)\r\n\r\ndef api_url():\r\n portal = json.loads(http_req(\"http://api.portal.swjsq.vip.xunlei.com:81/v2/queryportal\"))\r\n if portal['errno']:\r\n print('Error: get interface_ip failed')\r\n os._exit(3)\r\n return '%s:%s' % (portal['interface_ip'], portal['interface_port'])\r\n\r\ndef setup():\r\n global MAC\r\n global API_URL\r\n MAC = get_mac(to_splt = '').upper() + '004V'\r\n API_URL = api_url()\r\n\r\ndef api(cmd, uid, session_id = ''):\r\n url = 'http://%s/v2/%s?peerid=%s&userid=%s&user_type=1%s' % (\r\n API_URL,\r\n cmd,\r\n MAC,\r\n uid,\r\n ('&sessionid=%s' % session_id) if session_id else ''\r\n )\r\n return json.loads(http_req(url, headers = header_api))\r\n\r\ndef fast_d1ck(uname, pwd, login_type, save = True):\r\n if uname[-2] == ':':\r\n print('Error: sub account can not upgrade')\r\n os._exit(3)\r\n\r\n dt = login_xunlei(uname, pwd, login_type)\r\n if 'sessionID' not in dt:\r\n uprint('Error: login failed, %s' % dt['errorDesc'], 'Error: login failed')\r\n os._exit(1)\r\n elif ('isVip' not in dt or not dt['isVip']) and ('payId' not in dt or dt['payId'] not in [5, 702]):\r\n #FIX ME: rewrite if with payId\r\n print('Warning: you are probably not xunlei vip, buy buy buy!\\n[Debug] isVip:%s payId:%s payName:%s' % (\r\n 'None' if 'isVip' not in dt else dt['isVip'],\r\n 'None' if 'payId' not in dt else dt['payId'],\r\n 'None' if 'payName' not in dt else [dt['payName']]\r\n ))\r\n #os._exit(2)\r\n print('Login xunlei succeeded')\r\n if save:\r\n try:\r\n os.remove(account_file_plain)\r\n except:\r\n pass\r\n with open(account_file_encrypted, 'w') as f:\r\n f.write('%s,%s' % (dt['userID'], pwd))\r\n if not os.path.exists(shell_file):\r\n make_wget_script(dt['userID'], pwd)\r\n if not os.path.exists(ipk_file):\r\n update_ipk()\r\n\r\n _ = api('bandwidth', dt['userID'])\r\n if not _['can_upgrade']:\r\n uprint('Error: can not upgrade, so sad TAT %s' % _['message'], 'Error: can not upgrade, so sad TAT')\r\n os._exit(3)\r\n\r\n print(\"To Upgrade: \", end = '')\r\n uprint('%s%s ' % ( _['province_name'], _['sp_name']),\r\n '%s %s ' % ( _['province'], _['sp']),\r\n end = ''\r\n )\r\n print('Down %dM -> %dM, Up %dM -> %dM' % (\r\n _['bandwidth']['downstream']/1024,\r\n _['max_bandwidth']['downstream']/1024,\r\n _['bandwidth']['upstream']/1024,\r\n _['max_bandwidth']['upstream']/1024,\r\n ))\r\n \r\n #print(_)\r\n def _atexit_func():\r\n print(\"Sending recover request\")\r\n try:\r\n api('recover', dt['userID'], dt['sessionID'])\r\n except KeyboardInterrupt:\r\n print('Secondary ctrl+c pressed, exiting')\r\n atexit.register(_atexit_func)\r\n i = 0\r\n while True:\r\n try:\r\n if i % 6 == 0:#30min\r\n print('Initializing upgrade')\r\n if i:\r\n api('recover', dt['userID'], dt['sessionID'])\r\n time.sleep(5)\r\n dt = login_xunlei(uname, pwd, login_type)\r\n _ = api('upgrade', dt['userID'], dt['sessionID'])\r\n #print(_)\r\n if not _['errno']:\r\n print('Upgrade done: Down %dM, Up %dM' % (_['bandwidth']['downstream'], _['bandwidth']['upstream']))\r\n else:\r\n _ = api('keepalive', dt['userID'], dt['sessionID'])\r\n if _['errno']:\r\n print('Error: %s' % _['message'])\r\n if _['errno'] == 513:# TEST: re-upgrade when get 'not exist channel'\r\n i = 0\r\n continue\r\n else:\r\n time.sleep(300)#os._exit(4) \r\n except Exception as ex:\r\n import traceback\r\n _ = traceback.format_exc()\r\n print(_)\r\n with open('swjsq.log', 'a') as f:\r\n try:\r\n f.write('%s %s\\n' % (time.strftime('%X', time.localtime(time.time())), _))\r\n except UnicodeEncodeError:\r\n f.write('%s keepalive\\n' % (time.strftime('%X', time.localtime(time.time()))))\r\n i+=1\r\n time.sleep(270)#5 min\r\n\r\ndef make_wget_script(uid, pwd):\r\n open(shell_file, 'w').write(\r\n'''#!/bin/ash\r\nTEST_URL=\"https://baidu.com\"\r\nif [ ! -z \"`wget --no-check-certificate -O - $TEST_URL 2>&1|grep \"100%\"`\" ]\r\n then\r\n HTTP_REQ=\"wget --no-check-certificate -O - \"\r\n POST_ARG=\"--post-data=\"\r\nelse\r\n command -v curl >/dev/null 2>&1 && curl -kI $TEST_URL >/dev/null 2>&1 || { echo >&2 \"Xunlei-FastD1ck cannot find wget or curl installed with https(ssl) enabled in this system.\"; exit 1; }\r\n HTTP_REQ=\"curl -ks\"\r\n POST_ARG=\"--data \"\r\nfi\r\n\r\nuid='''+str(uid)+'''\r\npwd='''+rsa_encode(pwd)+'''\r\nnic=eth0\r\npeerid='''+MAC+'''\r\nuid_orig=$uid\r\n\r\nday_of_month_orig=`date +%d`\r\norig_day_of_month=`echo $day_of_month_orig|grep -oE \"[1-9]{1,2}\"`\r\nportal=`$HTTP_REQ http://api.portal.swjsq.vip.xunlei.com:81/v2/queryportal`\r\nportal_ip=`echo $portal|grep -oE '([0-9]{1,3}[\\.]){3}[0-9]{1,3}'`\r\nportal_port_temp=`echo $portal|grep -oE \"port...[0-9]{1,5}\"`\r\nportal_port=`echo $portal_port_temp|grep -oE '[0-9]{1,5}'`\r\nif [ -z \"$portal_ip\" ]\r\n then\r\n\t sleep 30\r\n\t portal=`$HTTP_REQ http://api.portal.swjsq.vip.xunlei.com:81/v2/queryportal`\r\n portal_ip=`echo $portal|grep -oE '([0-9]{1,3}[\\.]){3}[0-9]{1,3}'`\r\n portal_port_temp=`echo $portal|grep -oE \"port...[0-9]{1,5}\"`\r\n portal_port=`echo $portal_port_temp|grep -oE '[0-9]{1,5}'`\r\n\t if [ -z \"$portal_ip\" ]\r\n then\r\n portal_ip=\"119.147.41.210\"\r\n\t portal_port=80\r\n\t fi\r\nfi\r\napi_url=\"http://$portal_ip:$portal_port/v2\"\r\ni=6\r\nwhile true\r\ndo\r\n if test $i -ge 6\r\n then\r\n ret=`$HTTP_REQ https://login.mobile.reg2t.sandai.net:443/ $POST_ARG\"{\\\\\"userName\\\\\": \\\\\"\"$uid\"\\\\\", \\\\\"businessType\\\\\": 68, \\\\\"clientVersion\\\\\": \\\\\"1.1\\\\\", \\\\\"appName\\\\\": \\\\\"ANDROID-com.xunlei.vip.swjsq\\\\\", \\\\\"isCompressed\\\\\": 0, \\\\\"sequenceNo\\\\\": 1000001, \\\\\"sessionID\\\\\": \\\\\"\\\\\", \\\\\"loginType\\\\\": 1, \\\\\"rsaKey\\\\\": {\\\\\"e\\\\\": \\\\\"'''+long2hex(rsa_pubexp)+'''\\\\\", \\\\\"n\\\\\": \\\\\"'''+long2hex(rsa_mod)+'''\\\\\"}, \\\\\"cmdID\\\\\": 1, \\\\\"verifyCode\\\\\": \\\\\"\\\\\", \\\\\"peerID\\\\\": \\\\\"\"$peerid\"\\\\\", \\\\\"protocolVersion\\\\\": 101, \\\\\"platformVersion\\\\\": 1, \\\\\"passWord\\\\\": \\\\\"\"$pwd\"\\\\\", \\\\\"extensionList\\\\\": \\\\\"\\\\\", \\\\\"verifyKey\\\\\": \\\\\"\\\\\"}\"`\r\n session_temp=`echo $ret|grep -oE \"sessionID...[A-F,0-9]{32}\"`\r\n\t session=`echo $session_temp|grep -oE \"[A-F,0-9]{32}\"`\r\n uid_temp=`echo $ret|grep -oE \"userID..[0-9]{9}\"`\r\n\t uid=`echo $uid_temp|grep -oE \"[0-9]{9}\"`\r\n i=0\r\n\t if [ -z \"$session\" ]\r\n then\r\n echo \"session is empty\"\r\n i=6\r\n sleep 5\r\n continue\r\n else\r\n echo \"session is $session\"\r\n fi\r\n\r\n if [ -z \"$uid\" ]\r\n then\r\n\t echo \"uid is empty\"\r\n\t\t\tuid=$uid_orig\r\n else\r\n echo \"uid is $uid\"\t\t\t\r\n fi\r\n $HTTP_REQ \"$api_url/upgrade?peerid=$peerid&userid=$uid&user_type=1&sessionid=$session\"\r\n\r\n fi\r\n sleep 1\r\n\tday_of_month_orig=`date +%d`\r\n day_of_month=`echo $day_of_month_orig|grep -oE \"[1-9]{1,2}\"`\r\n if [[ -z $orig_day_of_month || $day_of_month -ne $orig_day_of_month ]]\r\n then\r\n orig_day_of_month=$day_of_month\r\n $HTTP_REQ \"$api_url/recover?peerid=$peerid&userid=$uid&user_type=1&sessionid=$session\"\r\n sleep 5\r\n\tfi\r\n ret=`$HTTP_REQ \"$api_url/keepalive?peerid=$peerid&userid=$uid&user_type=1&sessionid=$session\"`\r\n if [ ! -z \"`echo $ret|grep \"not exist channel\"`\" ]\r\n then\r\n i=6\r\n else\r\n let i=i+1\r\n sleep 270\r\n fi\r\ndone\r\n\r\n\r\n''')\r\n\r\ndef update_ipk():\r\n #FIXME: 3.X compatibility\r\n def get_sio(tar, name):\r\n return sio(tar.extractfile(name).read())\r\n\r\n def flen(fobj):\r\n pos = fobj.tell()\r\n fobj.seek(0)\r\n _ = len(fobj.read())\r\n fobj.seek(pos)\r\n return _\r\n\r\n def add_to_tar(tar, name, sio_obj, mode = 33279):\r\n info = tarfile.TarInfo(name = name)\r\n info.size = flen(sio_obj)\r\n info.mode = mode\r\n sio_obj.seek(0)\r\n tar.addfile(info, sio_obj)\r\n\r\n\r\n if os.path.exists(ipk_file):\r\n os.remove(ipk_file)\r\n ipk_fobj = tarfile.open(name = ipk_file, mode = 'w:gz')\r\n\r\n data_stream = sio()\r\n data_fobj = tarfile.open(fileobj = data_stream, mode = 'w:gz')\r\n data_content = open(shell_file, 'r')\r\n add_to_tar(data_fobj, './bin/swjsq', data_content)\r\n data_fobj.close()\r\n add_to_tar(ipk_fobj, './data.tar.gz', data_stream)\r\n data_stream.close()\r\n\r\n\r\n control_stream = sio()\r\n control_fobj = tarfile.open(fileobj = control_stream, mode = 'w:gz')\r\n control_content = sio('''Package: swjsq\r\nVersion: 0.0.1\r\nDepends: libc\r\nSource: none\r\nSection: net\r\nMaintainer: fffonion\r\nArchitecture: all\r\nInstalled-Size: %d\r\nDescription: Xunlei Fast Dick\r\n''' % flen(data_content))\r\n add_to_tar(control_fobj, './control', control_content)\r\n control_fobj.close()\r\n add_to_tar(ipk_fobj, './control.tar.gz', control_stream)\r\n control_stream.close()\r\n\r\n data_content.close()\r\n control_content.close()\r\n\r\n debian_binary_stream = sio('2.0\\n')\r\n add_to_tar(ipk_fobj, './debian-binary', debian_binary_stream)\r\n debian_binary_stream.close()\r\n\r\n ipk_fobj.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n setup()\r\n try:\r\n if os.path.exists(account_file_plain):\r\n uid, pwd = open(account_file_plain).read().strip().split(',')\r\n if PY3K:\r\n pwd = pwd.encode('utf-8')\r\n fast_d1ck(uid, hashlib.md5(pwd).hexdigest(), TYPE_NORMAL_ACCOUNT)\r\n elif os.path.exists(account_file_encrypted):\r\n uid, pwd_md5 = open(account_file_encrypted).read().strip().split(',')\r\n fast_d1ck(uid, pwd_md5, TYPE_NUM_ACCOUNT, save = False)\r\n else:\r\n print('Please create config file \"%s\", input account splitting with comma(,). Eg:\\nyonghuming,mima' % account_file_plain)\r\n except KeyboardInterrupt:\r\n pass\r\n\r\n \r\n \r\n","sub_path":"swjsq.py","file_name":"swjsq.py","file_ext":"py","file_size_in_byte":15710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"68518044","text":"#!/usr/bin/env python3\n\nimport argparse\nimport sys\nimport struct\n\nparser = argparse.ArgumentParser(description='Unpacks bytes into bits.')\nparser.add_argument('--bits', help='Bits per word', default=8, type=int)\nparser.add_argument('--big-endian', help='Use big endian for output', action='store_true')\nparser.add_argument('--lsb-first', help='Use less-significant-bit first for input', action='store_true')\nargs = parser.parse_args()\n\nif args.bits <= 8:\n\tformat = 'B'\n\treadlen = 1\nelif args.bits <= 16:\n\tformat = 'H'\n\treadlen = 2\nelif args.bits <= 32:\n\tformat = 'I'\n\treadlen = 4\n\nif args.big_endian:\n\tformat = '>' + format\n\nwhile True:\n\tdata = sys.stdin.buffer.read(readlen)\n\tif len(data) != readlen:\n\t\tbreak\n\n\tdata = struct.unpack(format, data)\n\tdata = data[0]\n\n\tif args.lsb_first:\n\t\tfor bit in range(args.bits):\n\t\t\tprint('1' if data & 1 else '0', end='')\n\t\t\tdata = data >> 1\n\telse:\n\t\tmask = (1 << args.bits - 1)\n\t\tfor bit in range(args.bits):\n\t\t\tprint('1' if data & mask else '0', end='')\n\t\t\tdata = data << 1\n\n\tprint(' ', end='')\nprint()\n","sub_path":"bytes2bits.py","file_name":"bytes2bits.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"419992572","text":"import numpy\nimport shutil\nimport os\nimport sys\nimport glob\n\nif __name__ == \"__main__\" :\n\n directory = str(sys.argv[1])\n dirname = directory.split(\"/\")[1].strip(\"/\")\n images = glob.glob(os.path.join(directory,\"images\",\"*.JPG\"))\n images = [image for image in images if os.stat(image).st_size > 0]\n json = glob.glob(os.path.join(directory,\"images_json\",\"*.json\"))\n json = json[0]\n for image in images:\n newimage = image.replace(\"IMGP\",dirname+\"_\")\n os.rename(image,newimage)\n newjson = newimage.split(\"/\")[-1].replace(\".JPG\",\".json\")\n newjson = os.path.join(directory,\"images_json\",newjson)\n try:\n shutil.copyfile(json, newjson)\n except:\n pass\n","sub_path":"scripts/dataprep/proData.py","file_name":"proData.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"614131589","text":"import logging\n\nfrom database.connection import DBConnection\n\nlogger = logging.getLogger(__name__)\n\n\nclass Postgre(object):\n\n def __init__(self, config):\n self.db = DBConnection(**config)\n\n editMsg_schema = {'tel_id'\t\t: 'INTEGER',\n 'user_msg_id'\t: 'INTEGER',\n 'bot_msg_id'\t: 'INTEGER',\n 'date'\t : 'INTEGER'\n }\n\n roomate_schema = {'id'\t\t\t : 'INTEGER NOT NULL UNIQUE',\n 'roomate_gender' : 'TEXT',\n 'starting_date' : 'DATE',\n 'notes' : 'TEXT'\n }\n\n user_schema = {'id'\t\t : 'INTEGER NOT NULL UNIQUE',\n 'name'\t\t : 'TEXT',\n 'username' : 'TEXT',\n 'gender' : 'TEXT',\n 'birthdate' : 'TEXT',\n 'is_student' : 'BOOLEAN',\n 'university' : 'TEXT',\n 'state' : 'TEXT',\n 'is_looking_for_roomate' : 'BOOLEAN',\n }\n\n # self.db.drop_table('EditMsg')\n # self.db.drop_table('Roomates')\n # self.db.drop_table('Users')\n self.db.create_table(table='EditMsg', schema=editMsg_schema)\n self.db.create_table(table='Roomates', schema=roomate_schema)\n self.db.create_table(table='Users', schema=user_schema)\n\n def getRecentAd(self, date):\n # output, query = self.db.select_one(table='Roomates', columns_target=[], conditions={'>=': {'starting_date': [date]}}, order_by=['starting_date'])\n query = f\"SELECT * from roomates WHERE starting_date >= '{date}'::date;\"\n output, query = self.db.custom(query)\n return output\n\n def getInfo(self, user_id, table, info=[]):\n conditions = {'IN': {'id': [user_id]}}\n output, query = self.db.select_one(table=table, columns_target=info, conditions=conditions)\n return output\n\n def updateInfo(self, message, table, updates={}):\n conditions = {'IN': {'id': [message.from_user.id]}}\n self.db.update(table=table, updates=updates, conditions=conditions)\n logger.info(f'{table} info updated.')\n\n def add_msgId(self, table, message, bot_message):\n\n msg_info = {'tel_id': message.from_user.id,\n 'user_msg_id': message.message_id,\n 'bot_msg_id': bot_message.message_id,\n 'date': message.date}\n self.db.insert(table=table, columns_val=msg_info)\n\n def update_state(self, message, state):\n conditions = {'IN': {'id': [message.from_user.id]}}\n updates = {'state': state}\n self.db.update(table='Users', updates=updates, conditions=conditions)\n\n def update_user(self, message):\n conditions = {'IN': {'id': [message.from_user.id]}}\n user_id, _ = self.db.select_one(table='Users', columns_target=['id'], conditions=conditions)\n\n first_name = message.from_user.first_name\n last_name = message.from_user.last_name\n name = f\"{first_name} {last_name if last_name else ''}\"\n\n if user_id:\n updates = {'name': name.strip(),\n 'username': message.from_user.username,\n }\n self.db.update(table='Users', updates=updates, conditions=conditions)\n logger.info('User login updated.')\n\n else:\n msg_info = {'id': message.from_user.id,\n 'name': name,\n 'username': message.from_user.username,\n }\n self.db.insert(table='Users', columns_val=msg_info)\n logger.info(f\"New login for user: {msg_info['username']}\")\n\n def update_roomate(self, message):\n conditions = {'IN': {'id': [message.from_user.id]}}\n user_id, _ = self.db.select_one(table='Roomates', columns_target=['id'], conditions=conditions)\n\n if not user_id:\n msg_info = {'id': message.from_user.id}\n self.db.insert(table='Roomates', columns_val=msg_info)\n logger.info(f\"New roomate add for user: {message.from_user.username}\")\n\n def update_msg_ids(self, message):\n \"\"\"\n This function removes expired message ids.\n \"\"\"\n current_date = message.date\n two_day = 2 * 24 * 60 * 60\n self.db._cur.execute('''\n DELETE FROM EditMsg WHERE (%s) - date > (%s)\n ''', (current_date, two_day))\n","sub_path":"edmontonbot/database/postgre.py","file_name":"postgre.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"225055","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport re\nfrom sklearn import metrics\n\nclass dpha:\n\t#calculate p and delta\n\tdef calcParams(self, dataVecs, dc, kl):\n\t\twordParam = {}\n #calculate p as param[0], neighbours as param[1]\n\t\tmaxp = 0\n\t\tmaxData = 0\n\t\tmaxDist = 0.0\n\t\tfor i in range(0, len(dataVecs)):\n\t\t\tcnt = 0\n\t\t\tneighbours = []\n\t\t\tfor j in range(0, len(dataVecs)):\n\t\t\t\tif i!=j:\n\t\t\t\t\ttmp = stpw.euclidean(dataVecs[i], dataVecs[j])\n\t\t\t\t\ttmpDist = 0.\n\t\t\t\t\tif tmp <= dc: \n\t\t\t\t\t\t#normal regularization\n\t\t\t\t\t\tif kl == 'nl':\n\t\t\t\t\t\t\tcnt += 1-(tmp**2/dc**2); neighbours.append(j)\n\t\t\t\t\t\t#gaussian kernel\n\t\t\t\t\t\telif kl == 'gs':\n\t\t\t\t\t\t\tcnt += np.exp(-tmp**2/dc**2); neighbours.append(j)\n\t\t\t\t\t\t#normal distance\n\t\t\t\t\t\telif kl == 'non': \n\t\t\t\t\t\t\tcnt += 1; neighbours.append(j)\n\t\t\t\t\tif tmp > maxDist: maxDist = tmp\n\t\t\twordParam[i] = [cnt, neighbours]\n\t\t\tif maxp < cnt: maxp = cnt; maxData = i\n\t\t#calculate delta as param[2], nearest higher density point j\n\t\tfor i in range(0, len(dataVecs)):\n\t\t\tminDelta = maxDist\n\t\t\taffiliate = -1\n\t\t\tfor j in range(0, len(dataVecs)):\n\t\t\t\tif wordParam[j][0] > wordParam[i][0]: \n\t\t\t\t\t#euclidean distance\n\t\t\t\t\ttmp = np.linalg.norm(np.array(dataVecs[i]) - np.array(dataVecs[j]))\n\t\t\t\t\tif minDelta > tmp: \n\t\t\t\t\t\tminDelta = tmp\n\t\t\t\t\t\taffiliate = j\n\t\t\twordParam[i].extend([minDelta, affiliate])\n\t\t\n\t\treturn wordParam\n\n\tdef calcDPHADist(self, aWords, bWords, clusterWord, wordParams, a, b, dc, dataVecs):\n\t\tpa = wordParams[a][0]\n\t\tpb = wordParams[b][0]\n\t\tflag = False\n\t\tpaAll = 0.\n\t\tpbAll = 0.\n\t\tfor itm in aWords: paAll += wordParams[itm][0]\n\t\tfor itm in bWords: pbAll += wordParams[itm][0]\n\t\tpaAverage = paAll/len(aWords)\n\t\tpbAverage = pbAll/len(bWords)\n\t\tfor word in aWords:\n\t\t\twordNeighbour = wordParams[word][1]\n\t\t\tfor neighbour in wordNeighbour:\n\t\t\t\tif neighbour in bWords: flag = True; break\n\t\tif flag == False: return 1000.\n\t\tpaSingle = []\n\t\tfor itm in aWords: \n\t\t\tpaB =0.\n\t\t\tcntA = 0\n\t\t\tpaB += wordParams[itm][0]\n\t\t\tcntA += 1\n\t\t\tfor point in wordParams[itm][1]:\n\t\t\t\tif point in clusterWord[a]:\n\t\t\t\t\tpaB += wordParams[point][0]\n\t\t\t\t\tcntA += 1\n\t\t\tpaSingle.append(paB/cntA)\n\t\tpbSingle = []\n\t\tfor itm in bWords: \n\t\t\tpbB =0.\n\t\t\tcntB =0\n\t\t\tpbB += wordParams[itm][0]\n\t\t\tcntB += 1\n\t\t\tfor point in wordParams[itm][1]:\n\t\t\t\tif point in clusterWord[b]:\n\t\t\t\t\tpbB += wordParams[point][0]\n\t\t\t\t\tcntB += 1\n\t\t\tpbSingle.append(pbB/cntB)\n\t\tdenseDist=1000.\n\t\tfor wid, word in enumerate(aWords):\n\t\t\tpword = wordParams[word][0]\n\t\t\twordNeighbour = wordParams[word][1]\n\t\t\tfor cid, cand in enumerate(bWords):\n\t\t\t\tif cand not in wordNeighbour: continue\n\t\t\t\tpcand = wordParams[cand][0]\n\t\t\t\tdist = stpw.euclidean(dataVecs[word], dataVecs[cand])\n\t\t\t\tif paAll > pbAll:\n\t\t\t\t\ttmp = ((dist*pa/(pword*dc))/2 + (dist*pb/(pcand*dc))/2) / np.exp(\n\t\t\t\t\t\tmin(\n\t\t\t\t\t\t\tabs(paAverage-pbAverage)/max(paAverage, pbAverage),\n\t\t\t\t\t\t\tabs(paSingle[wid]-pbAll)/max(paSingle[wid], pbAll)))\n\t\t\t\telse:\n\t\t\t\t\ttmp = ((dist*pa/(pword*dc))/2 + (dist*pb/(pcand*dc))/2) / np.exp(\n\t\t\t\t\t\tmin(\n\t\t\t\t\t\t\tabs(paAverage-pbAverage)/max(paAverage, pbAverage),\n\t\t\t\t\t\t\tabs(pbSingle[cid]-paAll)/max(pbSingle[cid], paAll)))\n\t\t\t\tif denseDist > tmp: denseDist = tmp\n\t\treturn denseDist\n\n\t#assign cluster in p's order, from high to low\n\t#if one cluster has a delta larger than dc, assign it a new cluster id\n\tdef assignCluster(self, wordParams, centers, dataVecs, dc, label, iter):\n\t\tboarders = set()\n\t\tclusterWord = {}\n\t\tmaxArs = 0.\n\t\tmaxAmi = 0.\n\t\t#coarsely assign cluster id based on centers\n\t\tpRank = [[wordParams[word][0], word] for word in wordParams]\n\t\tpRank.sort(reverse = True)\n\t\twordCluster = {word:-1 for word in wordParams}\n\t\tid = 0\n\t\tcentre2cluster = {}\n\t\tfor p in pRank:\n\t\t\tif wordCluster[p[1]] == -1: \n\t\t\t\tif p[1] in centers: wordCluster[p[1]] = p[1]; centre2cluster[p[1]] = p[1]\n\t\t\t\telse: \n\t\t\t\t\tif wordParams[p[1]][3] == -1: \n\t\t\t\t\t\tprint('error, increase dc and try again....\\n') \n\t\t\t\t\t\treturn maxArs, maxAmi, clusterWord\n\t\t\t\t\twordCluster[p[1]] = wordCluster[wordParams[p[1]][3]]\n\t\t#merge false clusters\n\n\t\tcluster2centre = {centre2cluster[itm]: itm for itm in centre2cluster}\n\t\tfor word in wordCluster:\n\t\t\tif wordCluster[word] in clusterWord: clusterWord[wordCluster[word]].append(word)\n\t\t\telse: clusterWord[wordCluster[word]] = [word]\n\n\t\tres = [wordCluster[itm] for itm in range(len(dataVecs))]\n\t\tmaxArs = metrics.adjusted_rand_score(label, res)\n\t\tmaxAmi = metrics.adjusted_mutual_info_score(label, res)\n\n\t\ttmpClusterWord = clusterWord\n\t\tcnt = 0\n\t\tdistList = []\n\t\t#distRecord = []\n\t\tfor i in clusterWord:\n\t\t\tfor j in clusterWord:\n\t\t\t\tif i == j: continue\n\t\t\t\ttmp = self.calcDPHADist(clusterWord[i], clusterWord[j], clusterWord, wordParams, i, j, dc, dataVecs)\n\t\t\t\t#distRecord.append([tmp,i,j])\n\t\t\t\tif tmp not in distList: distList.append(tmp)\n\t\tdistList.sort()\n\t\t#print(distList)\n\t\toldClusterWord = clusterWord.copy()\n\n\t\trelation = {i: [] for i in centers}\n\t\tfor dist in distList:\n\t\t\ta = -1\n\t\t\tb = -1\n\t\t\tcnt += 1\n\t\t\t#print(\"dist = \"+str(dist))\n\t\t\tfor i in oldClusterWord:\n\t\t\t\tfor j in oldClusterWord:\n\t\t\t\t\tif i == j: continue\n\t\t\t\t\ttmp = self.calcDPHADist(oldClusterWord[i], oldClusterWord[j], clusterWord, wordParams, i, j, dc, dataVecs)\n\t\t\t\t\tif dist == 1000.: continue\n\t\t\t\t\tif tmp <= dist:\n\t\t\t\t\t\ta = i\n\t\t\t\t\t\tb = j\n\t\t\t\t\t\tif a != -1 and b != -1:\n\t\t\t\t\t\t\trelation[a].append(b)\n\t\t\t\t\t\t\trelation[b].append(a)\n\t\t\t\t#print('merged cluster is: '+str(b)+' with: '+str(a))\n\t\t\tmergedList = []\n\t\t\t#print(relation)\n\t\t\tvisited = {id: -1 for id in centers}\n\t\t\tfor id in centers:\n\t\t\t\tif visited[id] == -1:\n\t\t\t\t\tvisited[id] = 1\n\t\t\t\t\tmergedSet = set()\n\t\t\t\t\tif len(relation[id]) != 0:\n\t\t\t\t\t\tmergedSet = set(relation[id])\n\t\t\t\t\t\tmergedSet.add(id)\n\t\t\t\t\telse: continue\n\t\t\t\t\tque = mergedSet.copy()\n\t\t\t\t\twhile len(que) != 0:\n\t\t\t\t\t\tnewQue = set()\n\t\t\t\t\t\tfor link in que:\n\t\t\t\t\t\t\tif visited[link] == 1: continue\n\t\t\t\t\t\t\tvisited[link] = 1\n\t\t\t\t\t\t\tmergedSet.add(link)\n\t\t\t\t\t\t\tif len(relation[link]) != 0:\n\t\t\t\t\t\t\t\tfor itm in relation[link]: [newQue.add(itm) for itm in relation[link] if itm not in mergedSet]\n\t\t\t\t\t\tque = newQue.copy()\n\t\t\t\t\ttmpList = []\n\t\t\t\t\t[tmpList.append(itm) for itm in mergedSet]\n\t\t\t\t\ttmpList.sort()\n\t\t\t\t\tmergedList.append(tmpList)\n\t\t\t#print(mergedList)\n\t\t\tclusterRel = {i: -1 for i in clusterWord.keys()}\n\t\t\tfor merge in mergedList:\n\t\t\t\tfor itm in merge:\n\t\t\t\t\tclusterRel[centre2cluster[itm]] = centre2cluster[merge[0]]\n\n\t\t\trealCluster = {word:-1 for word in wordParams}\n\t\t\t#self.plotClusterRes(wordCluster, dataVecs, centers, wordCluster, \"test\", 5)\n\t\t\tfor word in wordCluster:\n\t\t\t\tif clusterRel[wordCluster[word]] != -1: realCluster[word] = cluster2centre[clusterRel[wordCluster[word]]]\n\t\t\t\telse: realCluster[word] = cluster2centre[wordCluster[word]]\n\t\t\tres = []\n\t\t\tfor itm in range(len(realCluster)): res.append(realCluster[itm])\n\t\t\t#self.plotClusterRes(realCluster, dataVecs, centers, realCluster, \"test\", 5)\n\t\t\tarsTmp = metrics.adjusted_rand_score(label, res)\n\t\t\tamiTmp = metrics.adjusted_mutual_info_score(label, res)\n\t\t\tif arsTmp > maxArs and amiTmp > maxAmi: \n\t\t\t\tmaxArs = arsTmp\n\t\t\t\tmaxAmi = amiTmp\n\t\t\t\ttmpClusterWord = clusterWord\n\t\treturn maxArs, maxAmi, tmpClusterWord\n\n\tdef plotClusterRes(self, wordCluster, dataVecs, centres, finalRes, dir, num):\n\t\tcolors = cm.rainbow(np.linspace(0, 1, len(finalRes) + 1))\n\t\ttmp = {}\n\t\tfor i in range(num+1):\n\t\t\tif i%2 ==1: tmp[i] = i-1\n\t\t\telse: tmp[i] = i+4\n\t\tdpcolorMap2 = [colors[wordCluster[itm]] for itm in range(len(dataVecs))]\n\n\t\tdx = [dataVecs[i][0] for i in range(len(dataVecs))]\n\t\tdy = [dataVecs[i][1] for i in range(len(dataVecs))]\t\t\n\t\t\n\t\tcx = []\n\t\tcy = []\n\t\tcentreMap = ['r' for itm in centres]\n\t\tfor itm in centres:\n\t\t\tcx.append(dx[itm])\n\t\t\tcy.append(dy[itm])\n\t\tplt.scatter(cx, cy, c=centreMap, marker='+', s=250, zorder=2)\n\n\t\tplt.scatter(dx, dy, c=dpcolorMap2, marker='.', s=100, edgecolor='g', alpha=0.8, zorder=1)\n\t\t#plt.xlabel('X')\n\t\t#plt.ylabel('Y')\n\t\tplt.xticks([])\n\t\tplt.yticks([])\n\t\tplt.savefig(\"C:\\\\study\\\\8data\\\\\"+dir.split('.')[0]+\"_dpha.png\", bbox_inches='tight', pad_inches = 0)\n\t\tplt.show()\n\t\treturn\n\n\n\t#read dataset\n\tdef read(self, dir):\n\t\tfp = open('C:/study/clustering dataset/' + dir)\n\t\tdx = []\n\t\tdy = []\n\t\tid = []\n\t\tnum = 0\n\t\tclusters = []\n\t\tfor line in fp.readlines():\n\t\t\traw = re.split('[ |\\t]', line)\n\t\t\ttmp = [itm for itm in raw if itm != '']\n\t\t\tarr = [float(itm.replace('\\n', '')) for itm in tmp]\n\t\t\tdx.append(arr[0])\n\t\t\tdy.append(arr[1])\n\t\t\tif len(arr) == 3: \n\t\t\t\tid.append(int(arr[2]))\n\t\t\t\tif arr[2] not in clusters:\n\t\t\t\t\tclusters.append(arr[2])\n\t\t\t\t\tnum += 1\n\t\treturn dx, dy, id, num\n\n\tdef calcMaxDist(self, dataVecs, dc):\n\t\trawDists = set()\n\t\tfor i in range(len(dataVecs)):\n\t\t\tfor j in range(i + 1, len(dataVecs)):\n\t\t\t\tdist = stpw.euclidean(dataVecs[i], dataVecs[j])\n\t\t\t\trawDists.add(dist)\n\t\tdists = list(rawDists)\n\t\tdists.sort()\n\t\treturn dists\n\n\tdef getCenters(self, wordParams, dc):\n\t\tcenters = []\n\t\tpRank = []\n\t\tfor itm in wordParams:\n\t\t\tpRank.append([wordParams[itm][2], itm])\n\t\tpRank.sort()\n\t\tcenters = [itm[1] for itm in pRank if itm[0] > dc and len(wordParams[itm[1]][1]) >= 3]\n\t\treturn centers\n\n\n\t#density peak clustering flow\n\tdef run(self, dir, dc, lasso, kl):\n\t\tdx, dy, id, num = self.read(dir)\n\t\tdataVecs = [[dx[i], dy[i]] for i in range(len(dx))]\n\t\tdists = self.calcMaxDist(dataVecs, dc)\n\t\t#realDc = dists[round(dc*len(dists))]\n\t\trealDc = dists[-1]*dc\n\t\t#print('dc = ' + str(dc)+' realDc = '+str(realDc))\n\t\twordParams = self.calcParams(dataVecs, realDc, kl)\n\t\t#self.plotDG(wordParams, dx, dy)\n\t\tcenters = self.getCenters(wordParams, realDc)\n\t\tars, ami, wordCluster = self.assignCluster(wordParams, centers, dataVecs, realDc, id, iter)\n\t\t#self.plotCluster(rawCluster, wordCluster, dx, dy, id, num, centers, boarders)\n\t\t#self.plotCenter(rawCluster, wordCluster, dx, dy, id, num, centers, boarders, dc, kl)\n\t\t#self.plotClusterRes(wordCluster, dataVecs, centers, finalRes, dir, num)\n\t\t#print(ami)\n\t\treturn ars, ami, centers, wordCluster\n\n\t#for evaluation\n\tdef eval(self, dc, lasso, kl, dataVecs):\n\t\tdists = self.calcMaxDist(dataVecs, dc)\n\t\trealDc = dists[-1]*dc\n\t\twordParams = self.calcParams(dataVecs, realDc, kl)\n\t\tcenters = self.getCenters(wordParams, realDc)\n\t\trawCluster, wordCluster, boarders, finalRes, valid = self.assignCluster(wordParams, centers, dataVecs, realDc, lasso)\n\t\t#self.plotClusterRes(wordCluster, dataVecs, centers, finalRes)\n\t\tlabel = [wordCluster[i] for i in range(len(wordCluster))]\n\t\treturn label, valid, centers\n\n\n\tdef plotParams(self, params):\n\t\tp = []\n\t\tdelta = []\n\t\t#x = p, y = delta\n\t\tfor itm in params:\n\t\t\tp.append(params[itm][0])\n\t\t\tdelta.append(params[itm][1])\n\t\tplt.plot(p, delta, 'ro')\n\t\tplt.show()\n\t\treturn\n\nif __name__ == \"__main__\":\n\tinst = dpha()\n\t#correct\n\t#inst.run('flame.txt', 0.1, 0.65, 'nl')\n\t#clusters = inst.run('pathbased.txt', 0.085, 0.6, 'nl')\n\t#clusters = inst.run('jain.txt', 0.10, 0.5, 'nl')\n\t#clusters = inst.run('Aggregation.txt', 0.05, 1.5, 'nl')\n\t#clusters = inst.run('Compound.txt', 0.05, 1, 'nl')\n\t#clusters = inst.run('spiral.txt', 0.06, 0.5, 'nl')\n\t#inst.run('a3.txt', 0.020, 1.5, 'nl')\n\n\t#done Gaussian distance\n\t#clusters = inst.run('R15.txt', 0.040, 1000, 'gs')\n\t#inst.run('s1.txt', 0.035, 0.7, 'gs')\n\t#clusters = inst.run('D31.txt', 0.021, 10000, 'gs')\n\t#clusters = inst.run('s4.txt', 0.06, 7, 'gs')\n\t#end\n\tdatasets = [['pathbased.txt', 3, 'nl'],['Compound.txt', 6, 'nl'],['jain.txt', 2, 'nl'],['flame.txt', 2, 'nl'],['Aggregation.txt', 7, 'nl'],\n\t\t ['spiral.txt', 3, 'nl'],['R15.txt', 15, 'gs'],['D31.txt', 31, 'gs']]\n\tdatasets = [['pathbased.txt', 3, 'nl'],['Compound.txt', 6, 'nl'],['jain.txt', 2, 'nl'],['flame.txt', 2, 'nl'],['Aggregation.txt', 7, 'nl'],\n\t\t ['spiral.txt', 3, 'nl']]\n\ti = 0.01\n\tdataScore = {'pathbased':0., 'Compound':0., 'jain':0., 'flame':0., 'Aggregation':0., 'spiral':0., 'R15':0., 'D31':0.}\n\tdataCnt = {'pathbased':0., 'Compound':0., 'jain':0., 'flame':0., 'Aggregation':0., 'spiral':0., 'R15':0., 'D31':0.}\n\twhile i < 0.11:\n\t\tfor j in datasets:\n\t\t\t#print(j[0])\n\t\t\tdx, dy, id, num = inst.read(j[0])\n\t\t\tdataVecs = [[dx[i], dy[i]] for i in range(len(dx))]\n\t\t\tarsdpc = 0.0\n\t\t\tamidpc = 0.0\n\t\t\tarsTmp, amiTmp, centers, clusters = inst.run(j[0], i, 5, j[2])\n\t\t\tamidpc = amiTmp\n\t\t\tdataScore[j[0].split('.')[0]] += amidpc\n\t\t\tif amidpc != 0: dataCnt[j[0].split('.')[0]] += 1\n\t\ti += 0.01\n\tdataScore = {dataScore[itm]/9 for itm in dataScore}\n\tprint(dataScore)\n\tprint('The end...')","sub_path":"mdpc/mdpc_extend/mdpc_extend/dphm.py","file_name":"dphm.py","file_ext":"py","file_size_in_byte":12247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"592760546","text":"import urllib.request\nfrom urllib import request\nimport os\n\nprint('Download data......')\nurl = 'http://cn.bing.com'\nurlFile = urllib.request.urlopen(url)# 打开url\ndata = urlFile.read()# 读取html文件\nurlFile.close()\ndata = data.decode('utf-8')#解码为utf-8\n#print (data)\n\npre = 'g_img={url: \"'#可以通过源代码找到匹配图片url\nindex1 = data.find(pre) + len(pre) #获取图片url开始的索引\nindex2 = data.find('\"', index1)#获取结束索引\nimgUrl = data[index1 : index2]#剪切获得图片url\nprint (imgUrl)\n\npreImg = u'\n\"\"\"\nfrom chatterbot import ChatBot\n\ndef nltk_download_corpus(corpus_name):\n \"\"\"\n Download the specified NLTK corpus file\n unless it has already been downloaded.\n\n Returns True if the corpus needed to be downloaded.\n \"\"\"\n from nltk.data import find\n from nltk import download\n\n # Download the wordnet data only if it is not already downloaded\n zip_file = '{}.zip'.format(corpus_name)\n downloaded = False\n\n try:\n find(zip_file)\n except LookupError:\n download(corpus_name, quiet=True)\n downloaded = True\n\n return downloaded\n\n\nclass Bot(ChatBot):\n \"\"\"\n Bot that silences NLTK downloads\n \"\"\"\n\n def initialize(self):\n \"\"\"\n Do any work that needs to be done before the responses can be returned.\n \"\"\"\n\n # Download required NLTK corpora if they have not already been downloaded\n nltk_download_corpus('stopwords')\n nltk_download_corpus('wordnet')\n nltk_download_corpus('punkt')\n nltk_download_corpus('vader_lexicon')","sub_path":"olga/brain/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"246901374","text":"# class Student:\n# def __init__(self,name,age,score):\n# self.name=name\n# self.age=age\n# self.score=score\n# def show_student(self):\n# print('学生%s,年龄%d,成绩%f'%\n# (self.name,self.age,self.score))\n#\n# list01=[\n# Student('hjl',45,95),\n# Student('赵敏',12,89),\n# Student('无忌',20,56)]\n# def fun01(name):\n# for i in list01:\n# if i.name==name:\n# return i\n# stu01=fun01('赵敏')\n# print(stu01.age)\n#\n# def fun02():\n# list1=[]\n# for i in list01:\n# if i.age<30:\n# list1.append(i)\n# return list1\n#\n# result=fun02()\n# for i in result:\n# print(i.name)\n#\n# def del01():\n# for i in list01:\n# if i.score<60:\n# list01.remove(i)\n# del01()\n# for i in list01:\n# print(i.name)\n\n# 类方法\n# @classmethod\n# 保存当前类的地址\n\n\n\n\n\n#\n# class Wife:\n# w=0\n# @classmethod\n# def print_w(cls):\n# print(cls.w)\n# def __init__(self,name):\n# self.name=name\n# Wife.w +=1\n#\n# w1=Wife('小敏')\n# w2=Wife('小红')\n# w3=Wife('小芳')\n# Wife.print_w()\n#\n\n\nclass Jieq:\n def __init__(self,name,money):\n self.name=name\n self.money=money\n\n\n \n def borrow(self,obj):\n obj.money-=5000\n self.money+=5000\n\nxiaoming=Jieq('小明',10000)\nxiaobai=Jieq('小白',1000)\n\nxiaobai.borrow(xiaoming)\n\nprint('小明剩余:',xiaoming.money)\nprint('小白剩余:',xiaobai.money)\n\n\n\n\n\n\n","sub_path":"mounth001/day10/exercise02.py","file_name":"exercise02.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"521320625","text":"\"\"\" \ncopy from arxivscraper for significant modifications\n\"\"\"\n\nfrom __future__ import print_function\nimport xml.etree.ElementTree as ET\nimport datetime\nfrom dateutil.parser import parse\nimport time\nimport random\nimport sys\nPYTHON3 = sys.version_info[0] == 3\nimport concurrent.futures\n\nimport numpy as np \nfrom urllib.parse import urlencode\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\n\nOAI = '{http://www.openarchives.org/OAI/2.0/}'\nARXIV = '{http://arxiv.org/OAI/arXiv/}'\nBASE = 'http://export.arxiv.org/oai2?verb=ListRecords&'\n\n# from arxivscraper.arxivscraper import Scraper, Record\n\n\nclass Record(object):\n \"\"\"\n A class to hold a single record from ArXiv\n Each records contains the following properties:\n\n object should be of xml.etree.ElementTree.Element.\n \"\"\"\n\n def __init__(self, xml_record):\n \"\"\"if not isinstance(object,ET.Element):\n raise TypeError(\"\")\"\"\"\n self.xml = xml_record\n self.id = self._get_text(ARXIV, 'id')\n self.url = 'https://arxiv.org/abs/' + self.id\n self.title = self._get_text(ARXIV, 'title')\n self.abstract = self._get_text(ARXIV, 'abstract')\n self.cats = self._get_text(ARXIV, 'categories')\n self.created = self._get_text(ARXIV, 'created')\n self.updated = self._get_text(ARXIV, 'updated')\n self.doi = self._get_text(ARXIV, 'doi')\n self.authors = self._get_authors()\n self.affiliation = self._get_affiliation()\n\n def _get_text(self, namespace, tag):\n \"\"\"Extracts text from an xml field\"\"\"\n try:\n return self.xml.find(namespace + tag).text.strip().lower().replace('\\n', ' ')\n except:\n return ''\n\n def _get_authors(self):\n authors_xml = self.xml.findall(ARXIV + 'authors/' + ARXIV + 'author')\n last_names = [author.find(ARXIV + 'keyname').text.lower() for author in authors_xml]\n first_names = [author.find(ARXIV + 'forenames').text.lower() for author in authors_xml]\n full_names = [a+' '+b for a,b in zip(first_names, last_names)]\n return full_names\n\n def _get_affiliation(self):\n authors = self.xml.findall(ARXIV + 'authors/' + ARXIV + 'author')\n try:\n affiliation = [author.find(ARXIV + 'affiliation').text.lower() for author in authors]\n return affiliation\n except:\n return []\n\n def output(self):\n d = {\n 'title': self.title,\n 'id': self.id,\n 'abstract': self.abstract,\n 'categories': self.cats,\n 'doi': self.doi,\n 'created': self.created,\n 'updated': self.updated,\n 'authors': self.authors,\n 'affiliation': self.affiliation,\n 'url': self.url\n }\n return d\n\n\nclass Scraper(object):\n \"\"\"\n A class to hold info about attributes of scraping,\n such as date range, categories, and number of returned\n records. If `from` is not provided, the first day of\n the current month will be used. If `until` is not provided,\n the current day will be used.\n\n Paramters\n ---------\n category: str\n The category of scraped records\n data_from: str\n starting date in format 'YYYY-MM-DD'. Updated eprints are included even if\n they were created outside of the given date range. Default: first day of current month.\n date_until: str\n final date in format 'YYYY-MM-DD'. Updated eprints are included even if\n they were created outside of the given date range. Default: today.\n t: int\n Waiting time between subsequent calls to API, triggred by Error 503.\n timeout: int\n Timeout in seconds after which the scraping stops. Default: 300s\n filter: dictionary\n A dictionary where keys are used to limit the saved results. Possible keys:\n subcats, author, title, abstract. See the example, below.\n\n Example:\n Returning all eprints from\n\n ```\n import arxivscraper.arxivscraper as ax\n scraper = ax.Scraper(category='stat',date_from='2017-12-23',date_until='2017-12-25',t=10,\n filters={'affiliation':['facebook'],'abstract':['learning']})\n output = scraper.scrape()\n ```\n \"\"\"\n\n def __init__(self, category, workers=1, date_from=None, date_until=None, t=30, timeout=300, filters={}):\n self.cat = str(category)\n self.workers = workers\n self.t = t\n self.timeout = timeout\n self.url = BASE + 'metadataPrefix=arXiv&set=%s' % self.cat\n self.token = self.get_token(self.url)\n self.filters = filters\n if not self.filters:\n self.append_all = True\n else:\n self.append_all = False\n self.keys = filters.keys()\n\n def _get_dates(self, values):\n end = None\n if isinstance(values, list):\n if len(values) == 1:\n start = values[0]\n elif len(values) == 2:\n start = values[0]\n end = values[1]\n else:\n raise \"Please pass only two dates for created as the search range.\"\n else:\n raise \"Only accept list for created filter\"\n return start, end\n\n def _in_date_range(self, start, end, target):\n satisfy = False\n start = parse(start)\n target = parse(target)\n\n if end is not None:\n end = parse(end)\n if start <= target <= end:\n satisfy = True\n else:\n if start == target:\n satisfy = True\n return satisfy\n\n def get_token(self, url):\n response = urlopen(url)\n xml = response.read()\n root = ET.fromstring(xml)\n resumptionToken = root.find(OAI + 'ListRecords').find(OAI + 'resumptionToken').text\n api_token = resumptionToken[:resumptionToken.find('|')]\n return api_token\n\n def get_urls(self, start=1):\n tids = list(range(start, (start+self.workers*1000), 1000))\n urls = [BASE+'resumptionToken='+self.token+'|'+str(tid) for tid in tids]\n next_tid = tids[-1]+1000\n return urls, next_tid\n\n def test_error(self):\n url = BASE+'resumptionToken='+self.token+'|'+str(800000)\n response = urlopen(url)\n print(response)\n xml = response.read()\n print('xml',xml)\n root = ET.fromstring(xml)\n print('root',root)\n # below resumptionToken is None if there is no returned result\n resumptionToken = root.find(\n OAI + 'ListRecords').find(\n OAI + 'resumptionToken').text\n print('resumptionToken', resumptionToken)\n\n def scrape_one(self, url):\n print('Scraping url: {}'.format(url))\n ds = []\n tid = url[url.find('|')+1:]\n \n t = random.randint(30,30+self.workers*10) # restart the threads at different time\n success = False\n failure_count = 0\n while not success:\n try:\n response = urlopen(url)\n success = True\n except HTTPError as e:\n if failure_count >= 5:\n return ds, True\n \n if e.code == 503:\n print('Got 503. Retrying after {0:d} seconds.'.format(t))\n time.sleep(t)\n failure_count += 1\n continue\n else:\n raise\n \n xml = response.read()\n root = ET.fromstring(xml)\n records = root.findall(OAI + 'ListRecords/' + OAI + 'record')\n for record in records:\n meta = record.find(OAI + 'metadata').find(ARXIV + 'arXiv')\n try:\n record = Record(meta).output()\n if self.append_all:\n ds.append(record)\n else:\n # save only when the record satisfy all the filter requirements\n satisfy_requirement = []\n for key, values in self.filters.items():\n if key == 'created':\n start, end = self._get_dates(values)\n satisfy = self._in_date_range(start, end, record[key])\n else:\n # satisfy if any of the value is found\n satisfy = False\n for word in values:\n if word.lower() in record[key]:\n satisfy = True\n satisfy_requirement.append(satisfy)\n \n if all(satisfy_requirement):\n ds.append(record)\n except: \n # pass\n print('tid: {} - Cannot fetch the doc: id is {}\\n'.format(\n tid, meta.find(ARXIV + 'id').text.strip().lower().replace('\\n', ' ')))\n\n print ('Total number of records {:d}'.format(len(ds)))\n try:\n resumptionToken = root.find(OAI + 'ListRecords').find(OAI + 'resumptionToken').text\n except:\n resumptionToken = None\n cont = True if resumptionToken else False\n return ds, cont\n\n def scrape_many(self, urls):\n with concurrent.futures.ThreadPoolExecutor() as executor:\n results = executor.map(self.scrape_one, urls)\n return results\n","sub_path":"utilities/arxiv_parser.py","file_name":"arxiv_parser.py","file_ext":"py","file_size_in_byte":9380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"358073763","text":"from nmigen import Elaboratable, Module, Signal, Array, unsigned, Const\nfrom nmigen.build import Platform\nfrom nmigen.cli import main_parser, main_runner\nfrom src.ldpc_decoder import LDPC_Decoder\n\nif __name__ == \"__main__\":\n #Instantiate a command line argument parser\n parser = main_parser()\n args = parser.parse_args()\n\n #Instantiate an nMigen Module\n m = Module()\n \n #Instantiate the Parity Check Matrix 'H'\n #https://en.wikipedia.org/wiki/Low-density_parity-check_code\n\n parityCheckMatrix = [[0b000011100],\n [0b110000010],\n [0b001100001],\n [0b100001010],\n [0b001000101],\n [0b010110000]]\n\n #Instantiate the LDPC_Decoder Module with the generator matrix, input codeword size and output data size as parameters\n m.submodules.LDPC_Decoder = LDPC_Decoder = LDPC_Decoder(parityCheckMatrix,9,4)\n\n main_runner(parser, args, m, ports=[LDPC_Decoder.data_input, LDPC_Decoder.data_output, LDPC_Decoder.start, LDPC_Decoder.done, LDPC_Decoder.success]) \n","sub_path":"ldpc_decoder_9_4_toplevel.py","file_name":"ldpc_decoder_9_4_toplevel.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"130779713","text":"from math import floor\n\nrecord = float(input())\ndistance = float(input())\nseconds_per_meter = float(input())\n\nwater_resistance = (floor(distance / 15) * 12.5)\nivan_time = distance * seconds_per_meter + water_resistance\nold_record_faster = ivan_time - record\nnew_record_faster = record - ivan_time\nif ivan_time < record:\n print(f\"Yes, he succeeded! The new world record is {ivan_time:.2f} seconds.\")\nelse:\n print(f\"No, he failed! He was {old_record_faster:.2f} seconds slower.\")\n","sub_path":"2.Conditional_statements/Exercise/07. World Swimming Record.py","file_name":"07. World Swimming Record.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"441488109","text":"import numpy as np\nfrom keras.optimizers import Adam\nimport keras.backend as K\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard\nfrom unet import UNet, UNet2\nfrom keras.utils.training_utils import multi_gpu_model # add\nfrom PIL import Image\nimport cv2\nfrom dataset_generator import *\n\n# 入力はグレースケール1チャンネル\ninput_channel_count = 1\n# 出力はグレースケール1チャンネル\noutput_channel_count = 1\n# 一番初めのConvolutionフィルタ枚数は64\nfirst_layer_filter_count = 64\n# マルチgpu用のコード\ngpu_count = 2\n# バッチサイズは10\n# BATCH_SIZE = 1*gpu_count\nBATCH_SIZE = 1\n\nHEIGHT = 576\nWIDTH = 576\n\n\n# 値を-1から1に正規化する関数\ndef normalize_x(image):\n image = image / 4096\n return image\n\n\ndef denormalize_x(image):\n image = image * 255\n return image\n\n\n# 値を0から1に正規化する関数\ndef normalize_y(image):\n image = image / 255\n return image\n\n\n# 値を0から255に戻す関数\ndef denormalize_y(image):\n image = image * 255\n return image\n\n\ndef callback_def():\n early = EarlyStopping(monitor='val_loss', min_delta=0, patience=8, mode='auto')\n check = ModelCheckpoint('unet_weights_780.hdf5', monitor='val_loss', verbose=0, save_best_only=True,\n save_weights_only=True, mode='auto')\n Tensor = TensorBoard(log_dir='./logs', histogram_freq=1, batch_size=1)\n return [check, early, Tensor]\n\n\n# インプット画像を読み込む関数\ndef load_dataset():\n # もともとはX.dtype='uint16'、Y.dtype='uint8'\n X = np.load(\"U-net_cell/cell_data.npy\").astype('float32')\n Y = np.load(\"U-net_cell/likelihood.npy\").astype('float32')\n X = normalize_x(X)\n Y = normalize_y(Y)\n # ちゃんとできているか確認\n print(X.shape, X.dtype)\n print(Y.shape, Y.dtype)\n\n return X, Y\n\n\ndef Cross_Validation_data_load(X, Y, A, index):\n X_test = X[A[index]]\n Y_test = Y[A[index]]\n X_train = X.copy()\n Y_train = Y.copy()\n X_train = np.delete(X_train, A[index], axis=0)\n Y_train = np.delete(Y_train, A[index], axis=0)\n return X_train, Y_train, X_test, Y_test\n\n\n# U-Netのトレーニングを実行する関数\ndef train_unet(model, X_train, Y_train):\n callbacks = callback_def()\n epochs = 613\n result = model.fit(X_train, Y_train, batch_size=BATCH_SIZE, epochs=epochs, verbose=1, validation_split=0.1,\n callbacks=callbacks)\n\ndef evaluation():\n print('evaluation')\n\n\n# 学習後のU-Netによる予測を行う関数\ndef predict(model, X_test, Y_test, index):\n model.load_weights('unet_weights_780.hdf5')\n Y_pred = model.predict(X_test, BATCH_SIZE)\n X_test = denormalize_x(X_test)\n Y_test = denormalize_y(Y_test)\n for i, y in enumerate(Y_pred):\n y = cv2.resize(y, (576, 576))\n y = denormalize_y(y)\n save_path = 'c_v_result/%d/original/%05d.tif' % (index, i)\n cv2.imwrite(save_path, X_test[i])\n save_path = 'c_v_result/%d/GT/%05d.tif' % (index, i)\n cv2.imwrite(save_path, Y_test[i])\n save_path = 'c_v_result/%d/result/%05d.tif' % (index, i)\n cv2.imwrite(save_path, y)\n\n\ndef evaluate(model, X_test, Y_test):\n score = model.evaluate(X_test, Y_test, batch_size=BATCH_SIZE, verbose=0)\n print('loss=')\n print(score)\n\n\nif __name__ == '__main__':\n print('cross-validation')\n # クロスバリデーションの用意 : ランダムな5分割のインデックス行列A[0]~A[4]\n X, Y = load_dataset()\n A = np.arange(780 * 6)\n np.random.shuffle(A)\n A = np.array_split(A, 5)\n for i in range(5):\n print('%d回目' % i)\n # # U-Netの生成\n network = UNet2(input_channel_count, output_channel_count, first_layer_filter_count, HEIGHT, WIDTH)\n model = network.get_model()\n model.compile(loss='mse', optimizer=Adam())\n X_train, Y_train, X_test, Y_test = Cross_Validation_data_load(X, Y, A, i)\n train_unet(model, X_train, Y_train)\n predict(model, X_test, Y_test, i)\n print('Finished')\n","sub_path":"main_cell.py","file_name":"main_cell.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"245763919","text":"\"\"\"\nFiles Batch Uploader Plugin for userbot.\nusage:- .upb\nNote:- set TEMP_DIR in Your ENV Vars First.\nBy:-@Zero_cool7870\n\n\"\"\"\nimport os\n\nfrom telethon import events\n\n\n@borg.on(events.NewMessage(pattern=r\"\\.upb\", outgoing=True))\nasync def batch_upload(event):\n if event.fwd_from:\n return\n temp_dir = Config.TEMP_DIR\n if os.path.exists(temp_dir):\n files = sorted(os.listdir(temp_dir))\n await event.edit(\"Uploading Files on Telegram...\")\n for file in files:\n required_file_name = temp_dir + \"/\" + file\n print(required_file_name)\n await borg.send_file(event.chat_id, required_file_name, force_document=True)\n else:\n await event.edit(\"Directory Not Found.\")\n return\n await event.edit(\"Successfullllll.\")\n","sub_path":"stdplugins/batch_upload.py","file_name":"batch_upload.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"207501284","text":"import os\nimport json\nimport sys\nimport re\n\nargs = sys.argv\n#agrv[0]=xxx.py;argv[1]=collect_root\nif (len(args) < 2):\n sys.exit(1)\npath = args[1]\nif(path[-1:] == \"/\"):\n path = path[:-1]\nresult_dict = {}\nresult_dict['VAR_WIN_dnsSuffix_reboot'] = False\nnicList = []\nfilename0 = path + '/command/0/stdout.txt'\nfilename5 = path + '/command/5/stdout.txt'\nfilename6 = path + '/command/6/stdout.txt'\n\nif os.path.isfile(filename0):\n specific_dict = {}\n fo = open(filename0)\n alllines = fo.readlines()\n for strLine in alllines:\n str_match = re.match('\\s*UseDomainNameDevolution\\s*REG_DWORD\\s*(.*)', strLine)\n if str_match is not None:\n useDomainNameDevolution = int((str_match.group(1).strip()), base=16)\n if useDomainNameDevolution == 1:\n specific_dict['useDomainNameDevolution'] = True\n else:\n specific_dict['useDomainNameDevolution'] = False\n strList_match = re.match('\\s*SearchList\\s*REG_SZ\\s*(.*)', strLine)\n if strList_match is not None:\n searchList = strList_match.group(1).strip().split(',')\n specific_dict['searchList'] = searchList\n if len(specific_dict) > 0:\n result_dict['VAR_WIN_dnsSuffix_specific'] = specific_dict\n fo.close()\n\nif os.path.isfile(filename5):\n fo = open(filename5)\n alllines = fo.readlines()\n for strLine in alllines:\n str_match = re.match('\\s*Name\\s*:\\s*(.*)', strLine)\n if str_match is not None:\n nicList.append(str_match.group(1).strip())\n fo.close()\n\nif os.path.isfile(filename6):\n dnsSuffixNic_list = []\n fo = open(filename6)\n alllines = fo.readlines()\n for strLine in alllines:\n for nicname in nicList:\n strSuffix_match = re.match(nicname + '\\s*(.*)', strLine)\n if strSuffix_match is not None:\n sufficname = strSuffix_match.group(1).strip()\n if sufficname != '':\n dnsSuffixNic_dict = {}\n dnsSuffixNic_dict['nicName'] = nicname\n dnsSuffixNic_dict['suffixName'] = sufficname\n dnsSuffixNic_list.append(dnsSuffixNic_dict)\n if len(dnsSuffixNic_list) > 0:\n result_dict['VAR_WIN_dnsSuffix_nic'] = dnsSuffixNic_list\n fo.close()\nprint (json.dumps(result_dict))","sub_path":"files/WIN_dns-suffix.py","file_name":"WIN_dns-suffix.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"653517386","text":"'''\nGiven two binary strings, return their sum (also a binary string).\n\nThe input strings are both non-empty and contains only characters 1 or 0.\n\nExample 1:\n\nInput: a = \"11\", b = \"1\"\nOutput: \"100\"\nExample 2:\n\nInput: a = \"1010\", b = \"1011\"\nOutput: \"10101\"\n'''\n\n# bit by bit adding\n# not my idea\n\nclass Solution:\n def addBinary(self, a, b):\n if len(a) > len(b):\n b = \"0\" * (len(a) - len(b)) + b\n else:\n a = \"0\" * (len(b) - len(a)) + a\n result = \"\"\n i = len(a) - 1\n carry = 0\n while i >= 0:\n result = str((int(a[i]) + int(b[i]) + carry) % 2) + result\n carry = int((int(a[i]) + int(b[i]) + carry) / 2)\n i -= 1\n if carry == 1:\n result = str(carry) + result\n return result","sub_path":"0067.addBinary.py","file_name":"0067.addBinary.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"430580036","text":"from typing import Dict, Optional\n\nimport numpy\nfrom overrides import overrides\nimport torch\nimport torch.nn.functional as F\n\nfrom allennlp.common import Params\nfrom allennlp.common.checks import ConfigurationError\nfrom allennlp.data import Vocabulary\nfrom allennlp.modules import FeedForward, Seq2VecEncoder, TextFieldEmbedder\nfrom allennlp.models.model import Model\nfrom allennlp.nn import InitializerApplicator, RegularizerApplicator\nfrom allennlp.nn import util\nfrom allennlp.training.metrics import CategoricalAccuracy\n\n\n@Model.register(\"baseline_model\")\nclass BasicSequenceModel(Model):\n def __init__(self, vocab: Vocabulary,\n text_field_embedder: TextFieldEmbedder,\n headline_encoder: Seq2VecEncoder,\n body_encoder: Seq2VecEncoder,\n use_sentiment: bool,\n use_tfidf: bool,\n classifier_feedforward: FeedForward,\n initializer: InitializerApplicator = InitializerApplicator(),\n regularizer: Optional[RegularizerApplicator] = None) -> None:\n super(BasicSequenceModel, self).__init__(vocab, regularizer)\n\n self.text_field_embedder = text_field_embedder\n self.num_classes = self.vocab.get_vocab_size('labels')\n self.headline_encoder = headline_encoder\n self.body_encoder = body_encoder\n self.classifier_feedforward = classifier_feedforward\n\n self.use_sentiment = use_sentiment\n self.use_tfidf = use_tfidf\n\n self.metrics = {\n \"accuracy\": CategoricalAccuracy(),\n }\n self.loss = torch.nn.CrossEntropyLoss()\n\n initializer(self)\n\n def forward(self,\n headline,\n body,\n headline_sentiment=None,\n body_sentiment=None,\n tfidf=None,\n stance=None,\n metadata=None):\n embedded_headline = self.text_field_embedder(headline)\n headline_mask = util.get_text_field_mask(headline)\n encoded_headline = self.headline_encoder(embedded_headline, headline_mask)\n\n embedded_body = self.text_field_embedder(body)\n body_mask = util.get_text_field_mask(body)\n encoded_body = self.body_encoder(embedded_body, body_mask)\n\n aggregate_input = torch.cat([encoded_headline, encoded_body], dim=-1)\n if self.use_sentiment:\n aggregate_input = torch.cat([aggregate_input, headline_sentiment, body_sentiment], dim=-1)\n if self.use_tfidf:\n aggregate_input = torch.cat([aggregate_input, tfidf], dim=-1)\n\n logits = self.classifier_feedforward(aggregate_input)\n output_dict = {'logits': logits}\n if stance is not None:\n loss = self.loss(logits, stance)\n for metric in self.metrics.values():\n metric(logits, stance)\n output_dict[\"loss\"] = loss\n\n return output_dict\n\n def decode(self, output_dict):\n class_probabilities = F.softmax(output_dict['logits'], dim=-1)\n output_dict['class_probabilities'] = class_probabilities\n\n predictions = class_probabilities.cpu().data.numpy()\n argmax_indices = numpy.argmax(predictions, axis=-1)\n stance = [self.vocab.get_token_from_index(x, namespace=\"labels\")\n for x in argmax_indices]\n output_dict['stance'] = stance\n return output_dict\n\n def get_metrics(self, reset):\n return {metric_name: metric.get_metric(reset) for metric_name, metric in self.metrics.items()}\n","sub_path":"src/baseline_model.py","file_name":"baseline_model.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"567921395","text":"String = input()\r\nNumber = float(String[:String.find('E')]) # -1.2E+10中的-1.2部分\r\nIndex = int(String[String.find('E') + 1:]) # -1.2E+10中的10^10部分\r\nLength = String.find('E') - String.find('.') - int(String[String.find('E') + 1:]) # 计算后应该满足的小数位长度\r\n\r\nNewNumber = Number * 10 ** Index\r\nNewLength = len(str(NewNumber)) - str(NewNumber).find('.') # 此时的小数位长度\r\n# print(NewNumber, Length, NewLength)\r\nif NewLength < Length:\r\n NewNumber = str(NewNumber) + (Length - NewLength) * '0'\r\nelif NewLength > Length:\r\n NewNumber = int(str(NewNumber)[:str(NewNumber).find('.')])\r\nprint(NewNumber)\r\n","sub_path":"1024_.py","file_name":"1024_.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"126262126","text":"import os\nfrom PIL import Image, ExifTags\nimport arcpy\n\nimg_folder = r\"D:\\Img_to_Shp\\GeoTagged_Images\"\nimg_contents = os.listdir(img_folder)\nout_shapefile = r\"D:\\Img_to_Shp\\GeoTagged_Images\\out_shape_from_video.shp\"\nshp_list = []\nspatial_ref = arcpy.SpatialReference(4326)\n\n\ndef shape_creator():\n\n pt = arcpy.Point()\n ptGeoms = []\n\n for p in shp_list:\n\n pt.X = p[0]\n pt.Y = p[1]\n\n ptGeoms.append(arcpy.PointGeometry(pt, spatial_ref))\n\n arcpy.CopyFeatures_management(ptGeoms, out_shapefile)\n arcpy.AddXY_management(out_shapefile)\n arcpy.AddField_management(out_shapefile, \"timestamp\", \"TEXT\", 9, \"\", \"\", \"refcode\", \"NULLABLE\", \"REQUIRED\")\n arcpy.AddField_management(out_shapefile, \"img_path\", \"TEXT\", 9, \"\", \"\", \"refcode\", \"NULLABLE\", \"REQUIRED\")\n\n count = 0\n\n with arcpy.da.UpdateCursor(out_shapefile, [\"timestamp\", \"img_path\"]) as our_cursor:\n\n for c in our_cursor:\n c[0] = shp_list[count][3]\n c[1] = shp_list[count][2]\n count +=1\n\n our_cursor.updateRow(c)\n\n\ndef convert_to_degress(value):\n\n d0 = value[0][0]\n d1 = value[0][1]\n d = float(d0) / float(d1)\n\n m0 = value[1][0]\n m1 = value[1][1]\n m = float(m0) / float(m1)\n\n s0 = value[2][0]\n s1 = value[2][1]\n s = float(s0) / float(s1)\n\n return d + (m / 60.0) + (s / 3600.0)\n\n\nfor image in img_contents:\n\n full_path = os.path.join(img_folder, image)\n\n pil_img = Image.open(full_path)\n\n exif = {ExifTags.TAGS[k]: v for k, v in pil_img._getexif().items() if k in ExifTags.TAGS}\n\n gps_all = {}\n\n try:\n img_time = (exif['DateTime'])\n\n for key in exif['GPSInfo'].keys():\n\n decoded_value = ExifTags.GPSTAGS.get(key)\n gps_all[decoded_value] = exif['GPSInfo'][key]\n\n long_ref = gps_all.get('GPSLongitudeRef')\n lat_ref = gps_all.get('GPSLatitudeRef')\n\n long = gps_all.get('GPSLongitude')\n lat = gps_all.get('GPSLatitude')\n\n print(long_ref)\n print(lat_ref)\n\n if long_ref == \"W\":\n long_in_degrees = -abs(convert_to_degress(long))\n else:\n long_in_degrees = convert_to_degress(long)\n if lat_ref == \"S\":\n\n lat_in_degrees = -abs(convert_to_degress(lat))\n else:\n lat_in_degrees = convert_to_degress(lat)\n\n shp_list.append([long_in_degrees, lat_in_degrees, full_path, img_time])\n\n except:\n print(\"This image has no GPS info in it\")\n print(full_path)\n pass\n\nprint(shp_list)\nshape_creator()\n","sub_path":"Arcgis Scripting with Python Arcpy/21_Img_to_shp.py","file_name":"21_Img_to_shp.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"263212358","text":"#!/usr/bin/env python\n\n# Copyright (C) 2011 by Benedict Paten (benedictpaten@gmail.com)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\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 THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\nimport logging\nimport multiprocessing\nimport os\nimport random\nimport subprocess\nimport time\nimport math\nfrom threading import Thread\nfrom threading import Semaphore, Lock, Condition\nfrom Queue import Queue, Empty\n\nfrom toil.batchSystems.abstractBatchSystem import AbstractBatchSystem\n\nlogger = logging.getLogger(__name__)\n\n\nclass SingleMachineBatchSystem(AbstractBatchSystem):\n \"\"\"\n The interface for running jobs on a single machine, runs all the jobs you give it as they come in, but in parallel.\n \"\"\"\n\n numCores = multiprocessing.cpu_count()\n\n def __init__(self, config, maxCpus, maxMemory, maxDisk, badWorker=False):\n assert type(maxCpus) == int\n if maxCpus > self.numCores:\n logger.warn('Limiting maxCpus to CPU count of system (%i).', self.numCores)\n maxCpus = self.numCores\n AbstractBatchSystem.__init__(self, config, maxCpus, maxMemory, maxDisk)\n assert self.maxCpus >= 1\n assert self.maxMemory >= 1\n # The scale allows the user to apply a factor to each task's CPU requirement, thereby squeezing more tasks\n # onto each core (scale < 1) or stretching tasks over more cores (scale > 1).\n self.scale = float(config.attrib['scale'])\n # The minimal fractional CPU. Tasks with a smaller CPU requirement will be rounded up to this value. One\n # important invariant of this class is that each worker thread represents a CPU requirement of minCpu,\n # meaning that we can never run more than numCores / minCpu jobs concurrently. With minCpu set to .1,\n # a task with cpu=1 will occupy 10 workers. One of these workers will be blocked on the Popen.wait() call for\n # the worker.py child process, the others will be blocked on the acquiring the CPU semaphore.\n self.minCpu = 0.1\n # Number of worker threads that will be started\n self.numWorkers = int(self.maxCpus / self.minCpu)\n # A counter to generate batchjob IDs and a lock to guard it\n self.jobIndex = 0\n self.jobIndexLock = Lock()\n # A dictionary mapping IDs of submitted jobs to those jobs\n self.jobs = {}\n # A queue of jobs waiting to be executed. Consumed by the workers.\n self.inputQueue = Queue()\n # A queue of finished jobs. Produced by the workers.\n self.outputQueue = Queue()\n # A dictionary mapping IDs of currently running jobs to their Info objects\n self.runningJobs = {}\n # The list of worker threads\n self.workerThreads = []\n # A semaphore representing available CPU in units of minCpu\n self.cpuSemaphore = Semaphore(self.numWorkers)\n # A counter representing failed acquisitions of the semaphore, also in units of minCpu, and a lock to guard it\n self.cpuOverflow = 0\n self.cpuOverflowLock = Lock()\n # A lock to work around the lack of thread-safety in Python's subprocess module\n self.popenLock = Lock()\n # A counter representing available memory in bytes\n self.memoryPool = self.maxMemory\n # A condition object used to guard it (a semphore would force us to acquire each unit of memory individually)\n self.memoryCondition = Condition()\n logger.info('Setting up the thread pool with %i workers, '\n 'given a minimum CPU fraction of %f '\n 'and a maximum CPU value of %i.', self.numWorkers, self.minCpu, maxCpus)\n self.workerFn = self.badWorker if badWorker else self.worker\n for i in xrange(self.numWorkers):\n worker = Thread(target=self.workerFn, args=(self.inputQueue,))\n self.workerThreads.append(worker)\n worker.start()\n\n # The input queue is passed as an argument because the corresponding attribute is reset to None in shutdown()\n\n def worker(self, inputQueue):\n while True:\n args = inputQueue.get()\n if args is None:\n logger.debug('Received queue sentinel.')\n break\n jobCommand, jobID, jobCpu, jobMem, jobDisk = args\n try:\n numThreads = int(jobCpu / self.minCpu)\n logger.debug('Acquiring %i bytes of memory from pool of %i.', jobMem, self.memoryPool)\n self.memoryCondition.acquire()\n while jobMem > self.memoryPool:\n logger.debug('Waiting for memory condition to change.')\n self.memoryCondition.wait()\n logger.debug('Memory condition changed.')\n self.memoryPool -= jobMem\n self.memoryCondition.release()\n\n try:\n logger.debug('Attempting to acquire %i threads for %i cpus submitted', numThreads, jobCpu)\n numThreadsAcquired = 0\n # Acquire first thread blockingly\n logger.debug('Acquiring semaphore blockingly.')\n self.cpuSemaphore.acquire(blocking=True)\n try:\n numThreadsAcquired += 1\n logger.debug('Semaphore acquired.')\n while numThreadsAcquired < numThreads:\n # Optimistically and non-blockingly acquire remaining threads. For every failed attempt\n # to acquire a thread, atomically increment the overflow instead of the semaphore such\n # any thread that later wants to release a thread, can do so into the overflow,\n # thereby effectively surrendering that thread to this batchjob and not into the semaphore.\n # That way we get to start a batchjob with as many threads as are available, and later grab\n # more as they become available.\n if not self.cpuSemaphore.acquire(blocking=False):\n with self.cpuOverflowLock:\n self.cpuOverflow += 1\n numThreadsAcquired += 1\n\n logger.info(\"Executing command: '%s'.\", jobCommand)\n with self.popenLock:\n popen = subprocess.Popen(jobCommand, shell=True)\n info = Info(time.time(), popen, kill_intended=False)\n self.runningJobs[jobID] = info\n try:\n statusCode = popen.wait()\n if 0 != statusCode:\n if statusCode != -9 or not info.kill_intended:\n logger.error(\"Got exit code %i (indicating failure) from command '%s'.\", statusCode, jobCommand )\n finally:\n self.runningJobs.pop(jobID)\n finally:\n logger.debug('Releasing %i threads.', numThreadsAcquired)\n\n with self.cpuOverflowLock:\n if self.cpuOverflow > 0:\n if self.cpuOverflow > numThreadsAcquired:\n self.cpuOverflow -= numThreadsAcquired\n numThreadsAcquired = 0\n else:\n numThreadsAcquired -= self.cpuOverflow\n self.cpuOverflow = 0\n for i in xrange(numThreadsAcquired):\n self.cpuSemaphore.release()\n finally:\n logger.debug('Releasing %i memory back to pool', jobMem)\n self.memoryCondition.acquire()\n self.memoryPool += jobMem\n self.memoryCondition.notifyAll()\n self.memoryCondition.release()\n finally:\n # noinspection PyProtectedMember\n value = self.cpuSemaphore._Semaphore__value\n logger.debug('Finished batchjob. CPU semaphore value (approximate): %i, overflow: %i', value, self.cpuOverflow)\n self.outputQueue.put((jobID, 0))\n logger.info('Exiting worker thread normally.')\n\n # FIXME: Remove or fix badWorker to be compliant with new thread management.\n\n def badWorker(self, inputQueue, outputQueue):\n \"\"\"\n This is used to test what happens if we fail and restart jobs\n \"\"\"\n # Pipe the output to dev/null (it is caught by the worker and will be reported if there is an error)\n fnull = open(os.devnull, 'w')\n while True:\n args = inputQueue.get()\n # Case where we are reducing threads for max number of CPUs\n if args is None:\n inputQueue.task_done()\n return\n command, jobID, threadsToStart = args\n # Run to first calculate the runtime..\n process = subprocess.Popen(command, shell=True, stdout=fnull, stderr=fnull)\n if random.choice((False, True)):\n time.sleep(random.random())\n process.kill()\n process.wait()\n outputQueue.put((jobID, 1, threadsToStart))\n else:\n process.wait()\n outputQueue.put((jobID, process.returncode, threadsToStart))\n inputQueue.task_done()\n\n def issueBatchJob(self, command, memory, cpu, disk):\n \"\"\"\n Adds the command and resources to a queue to be run.\n \"\"\"\n # Round cpu to minCpu and apply scale\n cpu = math.ceil(cpu * self.scale / self.minCpu) * self.minCpu\n assert cpu <= self.maxCpus, \\\n 'batchjob is requesting {} cpu, which is greater than {} available on the machine. Scale currently set ' \\\n 'to {} consider adjusting batchjob or scale.'.format(cpu, multiprocessing.cpu_count(), self.scale)\n assert cpu >= self.minCpu\n assert memory <= self.maxMemory, 'batchjob requests {} mem, only {} total available.'.format(memory, self.maxMemory)\n\n self.checkResourceRequest(memory, cpu, disk)\n logger.debug(\"Issuing the command: %s with memory: %i, cpu: %i, disk: %i\" % (command, memory, cpu, disk))\n with self.jobIndexLock:\n jobID = self.jobIndex\n self.jobIndex += 1\n self.jobs[jobID] = command\n self.inputQueue.put((command, jobID, cpu, memory, disk))\n return jobID\n\n def killBatchJobs(self, jobIDs):\n \"\"\"\n As jobs are already run, this method has no effect.\n \"\"\"\n logger.debug('Killing jobs: {}'.format(jobIDs))\n for id in jobIDs:\n if id in self.runningJobs:\n info = self.runningJobs[id]\n info.kill_intended = True\n os.kill(info.popen.pid, 9)\n while id in self.runningJobs:\n pass\n\n def getIssuedBatchJobIDs(self):\n \"\"\"\n Just returns all the jobs that have been run, but not yet returned as updated.\n \"\"\"\n return self.jobs.keys()\n\n def getRunningBatchJobIDs(self):\n \"\"\"\n Return empty map\n \"\"\"\n currentJobs = {}\n for jobID, info in self.runningJobs.iteritems():\n startTime = info.time\n currentJobs[jobID] = time.time() - startTime\n return currentJobs\n\n def shutdown(self):\n \"\"\"\n Cleanly terminate worker threads. Add sentinels to inputQueue equal to maxThreads. Join all worker threads.\n \"\"\"\n for i in xrange(self.numWorkers):\n self.inputQueue.put(None)\n # Remove reference to inputQueue (raises exception if inputQueue is used after method call)\n self.inputQueue = None\n for thread in self.workerThreads:\n thread.join()\n\n def getUpdatedBatchJob(self, maxWait):\n \"\"\"\n Returns a map of the run jobs and the return value of their processes.\n \"\"\"\n try:\n i = self.outputQueue.get(timeout=maxWait)\n except Empty:\n return None\n jobID, exitValue = i\n self.jobs.pop(jobID)\n logger.debug(\"Ran jobID: %s with exit value: %i\" % (jobID, exitValue))\n self.outputQueue.task_done()\n return jobID, exitValue\n\n @classmethod\n def getRescueBatchJobFrequency(cls):\n \"\"\"\n This should not really occur, wihtout an error. To exercise the system we allow it every 90 minutes.\n \"\"\"\n return 5400\n\n\nclass Info(object):\n def __init__(self, time, popen, kill_intended):\n self.time = time\n self.popen = popen\n self.kill_intended = kill_intended\n","sub_path":"src/toil/batchSystems/singleMachine.py","file_name":"singleMachine.py","file_ext":"py","file_size_in_byte":13774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"273782353","text":"##1列目の文字列の種類(異なる文字列の集合)を求めよ.確認にはsort, uniqコマンドを用いよ.\n\n\npath = r\"\\Users\\Koya\\Documents\\Lab\\100knock2019\\Eguchi\\chapter02\"\n\nwith open(path + \"\\hightemp.txt\", \"r\",encoding=\"utf-8\") as file:\n readfile = file.read()\n listfile = readfile.split(\"\\n\")\n file.seek(0)\n filenumber = len(file.readlines())\n\nans=[]\n\nfor i in listfile:\n ans.append(i.split(\"\\t\"))\n\nfor i in range(filenumber):\n print(ans[i][0])\n ","sub_path":"Eguchi/chapter02/knock17.py","file_name":"knock17.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"492872609","text":"# -------------------------------------------------------------\n# \n# \tProject: Using Math\n#\tDescription: This example will show how to use math operations\n# with variables and commands\n# Configuration: VR Robot\n#\n# -------------------------------------------------------------\n\n# Library imports\nfrom vexcode import *\n\n# Add project code in \"main\"\ndef main():\n # Variables can store the result of a math calculation\n turnAngle = 360 / 8\n\n # Math operations can be used within commands directly\n drivetrain.drive_for(FORWARD, 20 * 20, MM)\n\n # Math operations on variables can be used within commands as well\n drivetrain.turn_for(LEFT,turnAngle + 45, DEGREES)\n\n# VR threads — Do not delete\nvr_thread(main())\n","sub_path":"VEXcode-VR/Examples/Using-Math/Using-Math.py","file_name":"Using-Math.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"31454936","text":"'''\n Day 05: https://adventofcode.com/2020/day/5\n'''\n\nimport math\n\nfound_seat_list = []\n\ndef read_input():\n '''\n Reads the input file and returns a list of all the lines\n '''\n\n lines = []\n with open('day05input.txt') as f:\n lines = f.read().splitlines()\n\n return lines\n\ndef part_one(lines):\n '''\n Calculates a list of seat ids and then returns the highest id\n '''\n\n for line in lines:\n row_str, column_str = line[:7], line[7:]\n row, column = binary_search(row_str, 127), binary_search(column_str, 7)\n\n seat_id = row * 8 + column\n\n found_seat_list.append(seat_id)\n\n return max(found_seat_list)\n\ndef part_two(lines):\n '''\n Finds the missing seat id based on all the other seat ids we have found in part one\n '''\n\n if (found_seat_list):\n first_seat = min(found_seat_list)\n last_seat = max(found_seat_list)\n\n actual_seat_list = list(range(first_seat, last_seat+1)) # create a list of all the actual seat numbers on the plane\n\n missing = list(set(actual_seat_list) - set(found_seat_list)) # find the missing numbers from our calculated seat list using sets\n\n return missing[0] # should only be one\n return None\n\n\ndef binary_search(str, max):\n '''\n Returns a number based on the binary search string.\n '''\n\n lower_range = 0\n upper_range = max \n midpoint = (lower_range + upper_range) / 2 \n\n for char in str:\n if char == 'L' or char == 'F':\n upper_range = math.floor(midpoint)\n elif char == 'R' or char == 'B':\n lower_range = math.ceil(midpoint)\n midpoint = (lower_range + upper_range) / 2\n\n if lower_range == upper_range:\n return lower_range\n else:\n raise ValueError('Incorrect parameters supplied')\n \n\n","sub_path":"AdventOfCode2020/day05.py","file_name":"day05.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"268454460","text":"import base64\nfrom io import BytesIO\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom django.views import View\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nfrom vote.models import Vote, Choice\nfrom django.views import generic\nfrom vote.tasks import file_formation\n\n\n# Create your views here.\n\n\nclass Index(View):\n\n def index(request):\n return render(request, 'base.html')\n\n\nclass ActiveVote(generic.ListView):\n\n model = Vote\n template_name = 'vote/active_votes.html'\n\nclass CloseVote(generic.ListView):\n\n model = Vote\n template_name = 'vote/close_votes.html/'\n\n\n def active_votes(self, request):\n result = Vote.objects.filter(status=True)\n return render(request, self.template_name, {'active_vote': result})\n\n\n \"\"\"\n def active_votes(request):\n result = Vote.objects.filter(status=True)\n return render(request, 'vote/active_votes.html', {'active': result})\n\n def close_votes(request):\n close = Vote.objects.filter(status=False)\n return render(request, 'vote/close_votes.html', {'close': close})\n \"\"\"\n\nclass DetailsVote(generic.DetailView):\n\n def show_vote(request, vote_id):\n choice = Choice.objects.filter(vote_id=vote_id).order_by('-rate')\n return render(request, 'vote/view_votes.html', {'choice': choice})\n\n def show_graph_result_vote(request, vote_id):\n\n choice = Choice.objects.filter(vote_id=vote_id)\n plt.rcdefaults()\n fig, ax = plt.subplots()\n result = []\n rates = []\n y_pos = np.arange(len(choice))\n\n for info in choice.order_by('-rate'):\n result.append('%s\\n %s\\n' % (info.person.first_name, info.person.last_name))\n rates.append(info.rate)\n\n persons = tuple(result)\n res_rates = tuple(rates)\n\n ax.set_xlabel(choice.first().vote.title)\n ax.set_yticks(y_pos)\n ax.set_yticklabels(persons)\n ax.barh(y_pos, res_rates, align='center')\n\n buffer = BytesIO()\n plt.savefig(buffer, format='png')\n buffer.seek(0)\n image = buffer.getvalue()\n buffer.close()\n\n graphic = base64.b64encode(image)\n graphic = graphic.decode('utf-8')\n\n return render(request, 'vote/vote.html', {'choice': choice.order_by('-rate'),\n 'graphics': graphic})\n\n\n def target_info_vote(request, vote_id):\n \"\"\" Просмотр Голосования \"\"\"\n info = Choice.objects.filter(vote_id=vote_id).order_by('-rate')\n title = info[0].vote.title\n return render(request, 'vote/view_votes.html', {'info': info,\n 'title': title})\n\n\n def add_vote(request, vote_id, person_id, MAX_RATE=100):\n\n choice = Choice.objects.get(vote_id=vote_id, person_id=person_id)\n choice.rate += 1\n choice.save()\n\n if choice.rate == MAX_RATE:\n v = Vote.objects.get(pk=choice.vote_id)\n v.status = False\n v.save()\n return HttpResponseRedirect('/vote/close')\n return HttpResponseRedirect('/vote/%s/target/' % choice.vote_id)\n\n def download_report(request, vote_id):\n\n result = file_formation.delay(vote_id)\n\n path_file = result.get()\n content = open(path_file, 'r')\n mime_type = 'application/vnd.ms-excel'\n response = HttpResponse(content, content_type=mime_type)\n response['Content-Disposition'] = 'attachment;filename=report.xls'\n response['X-SendFile'] = 'report.xls'\n return response\n","sub_path":"vote_candidate/vote/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"446291540","text":"################################################################################\n# NAME : get_xid.py\n# DATE STARTED : June 21, 2019\n# AUTHORS : Benjamin Vaughan\n# PURPOSE : a script to interface with the XID program\n# EXPLANATION :\n# CALLING SEQUENCE :\n# INPUTS :\n#\n#\n# OUTPUTS :\n# REVISION HISTORY :\n################################################################################\nimport numpy as np\nimport sys\nsys.path.append('../utilities')\nfrom get_spire_beam_fwhm import *\nfrom model import *\nimport matplotlib as plt\nimport config\nfrom astropy.io import fits\nfrom xidplus import moc_routines\nimport xidplus\nimport xidplus.catalogue as cat\nimport sys\nsys.path.append('../XID_plus/')\nfrom xidplus import moc_routines\nimport xidplus\nfrom scipy.io import readsav\nsys.path.append('../source_handling')\nimport numpy as np\nimport pymoc\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.convolution import Gaussian2DKernel\nfrom xidplus.stan_fit import SPIRE\nfrom astropy.wcs import WCS as wcs\nfrom astropy.wcs.utils import skycoord_to_pixel\nimport json\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nimport pymoc\nimport matplotlib.pyplot as plt\n\ndef clus_get_xid(maps, cats, savemap=0, simmap=0, verbose=1, confusionerrors=1):\n err = False\n thresh = 3.0\n mf = 1.0\n\n mJy2Jy = 1000.0 / mf\n catfile = config.CLUSDATA + 'placeholder' #this doesn't actually seem to do anything in the xid code,\n # but you need something for this for some reason.\n\n #Old code not used anymore\n # print('Retrieving data from cats')\n # inra = []\n # indec = []\n # for i in range(len(cats)):\n # for j in range(len(cats[i]['ra'])):\n # if cats[i]['ra'][j] not in inra and cats[i]['dec'][j] not in indec:\n # inra.append(cats[i]['ra'][j])\n # indec.append(cats[i]['dec'][j])\n # print('Done retrieving data from cats')\n\n inra = np.array(cats['ra'])\n indec = np.array(cats['dec'])\n\n ra = inra * u.deg\n dec = indec * u.deg\n c = SkyCoord(ra,dec, unit='deg')\n plt.scatter(ra, dec, c=cats['flux'], alpha=0.5)\n plt.show()\n\n\n print(inra)\n #initializing data containers.\n pinds = []\n files = []\n primary_hdus = []\n noise_maps = []\n data_maps = []\n headers = []\n pixsizes = []\n prf_sizes = []\n priors = []\n prfs = []\n for i in range(len(maps)):\n bands = [18, 25, 36] #units of arcseconds\n fwhm = bands[i] / maps[i]['pixsize'] #converts to arcseconds/pixel\n pixs = maps[i]['pixsize']\n size = pixs * 5\n moc = pymoc.util.catalog.catalog_to_moc(c, size, 15)\n #getting data from the fits files\n files.append(maps[i]['file'])\n hdul = fits.open(files[i])\n headers.append(hdul[1].header)\n primary_hdus.append(hdul[0].header)\n img = hdul[1].data\n data_maps.append(img)\n noise_maps.append(hdul[2].data)\n pixsizes.append(maps[i]['pixsize'])\n prf_sizes.append(get_spire_beam_fwhm(maps[i]['band']))\n pinds.append(np.arange(0,101,1) * 1.0 / pixsizes[i])\n # print(maps[i]['file'])\n # print(pixsizes[i])\n #setting up priors\n prior = xidplus.prior(data_maps[i], noise_maps[i], primary_hdus[i], headers[i], moc=moc)\n prior.prior_cat(inra, indec, catfile, moc=moc)\n prior.prior_bkg(-5.0, 5)\n\n #setting up prfs.\n # This prf doesnt quite look correct\n # In previous set up we needed to rebin to accuratly describe our beam sizes\n prf = Gaussian2DKernel(bands[i] / 2.355, x_size=101, y_size = 101) #maybe x_size and y_size need to change.\n prf.normalize(mode='peak')\n prfs.append(prf.array)\n # print(prfs)\n exit()\n #appending prf to prior and setting point matrix\n prior.set_prf(prfs[i], pinds[i], pinds[i]) #prfs, xpinds, ypinds\n prior.get_pointing_matrix()\n prior.upper_lim_map()\n\n #appending prior to priors list.\n priors.append(prior)\n\n print('fitting %s sources' % (priors[0].nsrc))\n print('using %s %s %s pixels' % (priors[0].snpix, priors[1].snpix, priors[2].snpix))\n\n fit = SPIRE.all_bands(priors[0], priors[1], priors[2], iter=1000) #number of iterations should be at least 100 just set lower for testing.\n posterior = xidplus.posterior_stan(fit,[priors[0],priors[1],priors[2]])\n\n # figs, fig = xidplus.plots.plot_Bayes_pval_map(priors, posterior)\n # print(type(figs)) #figs is list.\n # print(figs) #fig is matplotlib.figure.figure object.\n # print(type(fig))\n # cols = ['PSW', 'PMW', 'PLW']\n # counter = 0\n # for figure in figs:\n # figure.save('xid_%s.png' %(cols[counter]))\n # counter += 1\n\n # plt.imshow(figs)\n\n spire_cat = cat.create_SPIRE_cat(posterior, priors[0], priors[1], priors[2])\n\n\n # spire_cat.writeto('xid_model_2_%s.fits' % (maps[0]['name']))\n\n xid_data = spire_cat[1].data\n xid = []\n\n #in units of mJy for fluxes and degrees for RA/DEC\n xid1 = {'band' : 'PSW',\n 'sra' : xid_data.field('RA'),\n 'sdec' : xid_data.field('DEC'),\n 'sflux' : xid_data.field('F_SPIRE_250'),\n 'serr' : xid_data.field('FErr_SPIRE_250_u'), #there was also FErr_SPIRE_250_l don't know which to use.\n 'pflux' : xid_data.field('F_SPIRE_250'),\n 'perr' : xid_data.field('FErr_SPIRE_250_u'),\n 'model' : None,\n 'mf' : mf} #idk if perr and pflux is right there may be a conversion needed for pflux.\n #in mikes code it has pflux = output from xid / mJy2Jy.\n xid2 = {'band' : 'PMW',\n 'sra' : xid_data.field('RA'),\n 'sdec' : xid_data.field('DEC'),\n 'sflux' : xid_data.field('F_SPIRE_350'),\n 'serr' : xid_data.field('FErr_SPIRE_350_u'),\n 'pflux' : xid_data.field('F_SPIRE_350'),\n 'perr' : xid_data.field('FErr_SPIRE_350_u'),\n 'model' : None,\n 'mf' : mf}\n\n xid3 = {'band' : 'PLW',\n 'sra' : xid_data.field('RA'),\n 'sdec' : xid_data.field('DEC'),\n 'sflux' : xid_data.field('F_SPIRE_500'),\n 'serr' : xid_data.field('FErr_SPIRE_500_u'),\n 'pflux' : xid_data.field('F_SPIRE_500'),\n 'perr' : xid_data.field('FErr_SPIRE_500_u'),\n 'model' : None,\n 'mf' : mf}\n\n #there was another term in the dictionary sflux, pflux and sflux looked like maybe the same thing, but I'm not sure.\n #I left it out so if there are issues with that then it is because that is gone.\n xid.append(xid1)\n xid.append(xid2)\n xid.append(xid3)\n\n # models = create_model(maps, xid)\n\n # for i in range(len(xid)):\n # xid[i]['model'] = models[i]\n\n # # only look at data with a flux lower than 0.0\n # for i in range(len(xid)):\n # whpl = []\n # for j in range(xid[i]['model'].shape[0]):\n # for k in range(xid[i]['model'].shape[1]):\n # if xid[i]['pflux'][j] >= 0.0:\n # whpl.append(j)\n # whpl = np.array(whpl)\n #\n # xid[i]['sra'] = xid[i]['sra'][whpl]\n # xid[i]['sdec'] = xid[i]['sdec'][whpl]\n # xid[i]['x'] = xid[i]['x'][whpl]\n # xid[i]['y'] = xid[i]['y'][whpl]\n # xid[i]['sflux'] = xid[i]['sflux'][whpl]\n # xid[i]['serr'] = xid[i]['serr'][whpl]\n\n for i in range(len(xid)):\n ra = xid[i]['sra'] * u.deg\n dec = xid[i]['sdec'] * u.deg\n c = SkyCoord(ra, dec)\n #initializing w class.\n hdul = fits.open(maps[i]['file'])\n w = wcs(hdul[1].header)\n #converting ra/dec to pixel coords.\n px, py = skycoord_to_pixel(c, w)\n xid[i]['x'] = px\n xid[i]['y'] = py\n xid[i]['sra'] = xid[i]['sra'].tolist()\n xid[i]['sdec'] = xid[i]['sdec'].tolist()\n xid[i]['sflux'] = xid[i]['sflux'].tolist()\n xid[i]['serr'] = xid[i]['serr'].tolist()\n xid[i]['pflux'] = xid[i]['pflux'].tolist()\n xid[i]['perr'] = xid[i]['perr'].tolist()\n xid[i]['x'] = xid[i]['x'].tolist()\n xid[i]['y'] = xid[i]['y'].tolist()\n\n #saving to json file for further analysis.\n with open('xid_a0370_take_9_%s.json' %(xid[i]['band']), 'w') as f: #code for saving output to a file.\n json.dump(xid[i], f)\n\n #model = image_model(x,y, sflux, maps[i]['astr']['NAXIS'][0], maps[i]['astr']['NAXIS'][1],\n #maps[i]['psf'])\n #need to finish converting model over to python.\n\n\n\n\n\n\n\n\n\n\n #\n # if savemap:\n # outfile = config.CLUSSBOX + 'clus_get_xid_model_' + maps[i]['band'] + '.fit'\n # writefits(outfile, data=model, header_dict=maps[i]['shead'])\n\n\n\n return xid, err\n","sub_path":"source_handling/clus_get_xid.py","file_name":"clus_get_xid.py","file_ext":"py","file_size_in_byte":8712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"286756851","text":"n=int(input())\r\nlst1=[]\r\nsum1=0\r\nfor i in range(n):\r\n m=int(input())\r\n \r\n lst=[int(i) for i in input().split()][:m]\r\n lst=sorted(lst)\r\n for j in range(len(lst)-1):\r\n ss=abs(lst[j]-lst[j+1])\r\n sum1=sum1+ss\r\n lst1.append(sum1)\r\n sum1=0\r\nlst=[]\r\n\r\n\r\nprint(*lst1)\r\n","sub_path":"vito.py","file_name":"vito.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"321435245","text":"\"\"\"Registration of functional data module.\n\nThis module contains routines related to the registration procedure.\n\"\"\"\nimport collections\n\nimport scipy.integrate\nfrom scipy.interpolate import PchipInterpolator\n\nimport numpy as np\n\n\n__author__ = \"Pablo Marcos Manchón\"\n__email__ = \"pablo.marcosm@estudiante.uam.es\"\n\n\ndef mse_decomposition(original_fdata, registered_fdata, warping_function=None,\n *, eval_points=None):\n r\"\"\"Compute mean square error measures for amplitude and phase variation.\n\n Once the registration has taken place, this function computes two mean\n squared error measures, one for amplitude variation, and the other for\n phase variation. It also computes a squared multiple correlation index\n of the amount of variation in the unregistered functions is due to phase.\n\n Let :math:`x_i(t),y_i(t)` be the unregistered and registered functions\n respectively. The total mean square error measure (see [RGS09-8-5]_) is\n defined as\n\n\n .. math::\n \\text{MSE}_{total}=\n \\frac{1}{N}\\sum_{i=1}^{N}\\int[x_i(t)-\\overline x(t)]^2dt\n\n We define the constant :math:`C_R` as\n\n .. math::\n\n C_R = 1 + \\frac{\\frac{1}{N}\\sum_{i}^{N}\\int [Dh_i(t)-\\overline{Dh}(t)]\n [ y_i^2(t)- \\overline{y^2}(t) ]dt}\n {\\frac{1}{N} \\sum_{i}^{N} \\int y_i^2(t)dt}\n\n Whose structure is related to the covariation between the deformation\n functions :math:`Dh_i(t)` and the squared registered functions\n :math:`y_i^2(t)`. When these two sets of functions are independents\n :math:`C_R=1`, as in the case of shift registration.\n\n The measures of amplitude and phase mean square error are\n\n .. math::\n \\text{MSE}_{amp} = C_R \\frac{1}{N}\n \\sum_{i=1}^{N} \\int \\left [ y_i(t) - \\overline{y}(t) \\right ]^2 dt\n\n .. math::\n \\text{MSE}_{phase}=\n \\int \\left [C_R \\overline{y}^2(t) - \\overline{x}^2(t) \\right]dt\n\n It can be shown that\n\n .. math::\n \\text{MSE}_{total} = \\text{MSE}_{amp} + \\text{MSE}_{phase}\n\n The squared multiple correlation index of the proportion of the total\n variation due to phase is defined as:\n\n .. math::\n R^2 = \\frac{\\text{MSE}_{phase}}{\\text{MSE}_{total}}\n\n See [KR08-3]_ for a detailed explanation.\n\n\n Args:\n original_fdata (:class:`FData`): Unregistered functions.\n regfd (:class:`FData`): Registered functions.\n warping_function (:class:`FData`): Warping functions.\n eval_points: (array_like, optional): Set of points where the\n functions are evaluated to obtain a discrete representation.\n\n\n Returns:\n :class:`collections.namedtuple`: Tuple with amplitude mean square error\n :math:`\\text{MSE}_{amp}`, phase mean square error\n :math:`\\text{MSE}_{phase}`, squared correlation index :math:`R^2`\n and constant :math:`C_R`.\n\n Raises:\n ValueError: If the curves do not have the same number of samples.\n\n References:\n .. [KR08-3] Kneip, Alois & Ramsay, James. (2008). Quantifying\n amplitude and phase variation. In *Combining Registration and\n Fitting for Functional Models* (pp. 14-15). Journal of the American\n Statistical Association.\n .. [RGS09-8-5] Ramsay J.O., Giles Hooker & Spencer Graves (2009). In\n *Functional Data Analysis with R and Matlab* (pp. 125-126).\n Springer.\n\n Examples:\n\n >>> from skfda.datasets import make_multimodal_landmarks\n >>> from skfda.datasets import make_multimodal_samples\n >>> from skfda.preprocessing.registration import (\n ... landmark_registration_warping, mse_decomposition)\n\n\n We will create and register data.\n\n >>> fd = make_multimodal_samples(n_samples=3, random_state=1)\n >>> landmarks = make_multimodal_landmarks(n_samples=3, random_state=1)\n >>> landmarks = landmarks.squeeze()\n >>> warping = landmark_registration_warping(fd, landmarks)\n >>> fd_registered = fd.compose(warping)\n >>> mse_amp, mse_pha, rsq, cr = mse_decomposition(fd, fd_registered,\n ... warping)\n\n Mean square error produced by the amplitude variation.\n\n >>> f'{mse_amp:.6f}'\n '0.000987'\n\n In this example we can observe that the main part of the mean square\n error is due to the phase variation.\n\n >>> f'{mse_pha:.6f}'\n '0.115769'\n\n Nearly 99% of the variation is due to phase.\n\n >>> f'{rsq:.6f}'\n '0.991549'\n\n \"\"\"\n\n if registered_fdata.dim_domain != 1 or registered_fdata.dim_codomain != 1:\n raise NotImplementedError\n\n if original_fdata.n_samples != registered_fdata.n_samples:\n raise ValueError(f\"the registered and unregistered curves must have \"\n f\"the same number of samples \"\n f\"({registered_fdata.n_samples})!= \"\n f\"({original_fdata.n_samples})\")\n\n if warping_function is not None and (warping_function.n_samples\n != original_fdata.n_samples):\n raise ValueError(f\"the registered curves and the warping functions \"\n f\"must have the same number of samples \"\n f\"({registered_fdata.n_samples})\"\n f\"!=({warping_function.n_samples})\")\n\n # Creates the mesh to discretize the functions\n if eval_points is None:\n try:\n eval_points = registered_fdata.sample_points[0]\n\n except AttributeError:\n nfine = max(registered_fdata.basis.n_basis * 10 + 1, 201)\n domain_range = registered_fdata.domain_range[0]\n eval_points = np.linspace(*domain_range, nfine)\n else:\n eval_points = np.asarray(eval_points)\n\n x_fine = original_fdata.evaluate(eval_points, keepdims=False)\n y_fine = registered_fdata.evaluate(eval_points, keepdims=False)\n mu_fine = x_fine.mean(axis=0) # Mean unregistered function\n eta_fine = y_fine.mean(axis=0) # Mean registered function\n mu_fine_sq = np.square(mu_fine)\n eta_fine_sq = np.square(eta_fine)\n\n # Total mean square error of the original funtions\n # mse_total = scipy.integrate.simps(\n # np.mean(np.square(x_fine - mu_fine), axis=0),\n # eval_points)\n\n cr = 1. # Constant related to the covariation between the deformation\n # functions and y^2\n\n # If the warping functions are not provided, are suppose to be independent\n if warping_function is not None:\n # Derivates warping functions\n dh_fine = warping_function.evaluate(eval_points, derivative=1,\n keepdims=False)\n dh_fine_mean = dh_fine.mean(axis=0)\n dh_fine_center = dh_fine - dh_fine_mean\n\n y_fine_sq = np.square(y_fine) # y^2\n y_fine_sq_center = np.subtract(\n y_fine_sq, eta_fine_sq) # y^2 - E[y^2]\n\n covariate = np.inner(dh_fine_center.T, y_fine_sq_center.T)\n covariate = covariate.mean(axis=0)\n cr += np.divide(scipy.integrate.simps(covariate,\n eval_points),\n scipy.integrate.simps(eta_fine_sq,\n eval_points))\n\n # mse due to phase variation\n mse_pha = scipy.integrate.simps(cr * eta_fine_sq - mu_fine_sq, eval_points)\n\n # mse due to amplitude variation\n # mse_amp = mse_total - mse_pha\n y_fine_center = np.subtract(y_fine, eta_fine)\n y_fine_center_sq = np.square(y_fine_center, out=y_fine_center)\n y_fine_center_sq_mean = y_fine_center_sq.mean(axis=0)\n\n mse_amp = scipy.integrate.simps(y_fine_center_sq_mean, eval_points)\n\n # Total mean square error of the original funtions\n mse_total = mse_pha + mse_amp\n\n # squared correlation measure of proportion of phase variation\n rsq = mse_pha / (mse_total)\n\n mse_decomp = collections.namedtuple('mse_decomposition',\n 'mse_amp mse_pha rsq cr')\n\n return mse_decomp(mse_amp, mse_pha, rsq, cr)\n\n\ndef invert_warping(fdatagrid, *, eval_points=None):\n r\"\"\"Compute the inverse of a diffeomorphism.\n\n Let :math:`\\gamma : [a,b] \\rightarrow [a,b]` be a function strictly\n increasing, calculates the corresponding inverse\n :math:`\\gamma^{-1} : [a,b] \\rightarrow [a,b]` such that\n :math:`\\gamma^{-1} \\circ \\gamma = \\gamma \\circ \\gamma^{-1} = \\gamma_{id}`.\n\n Uses a PCHIP interpolator to compute approximately the inverse.\n\n Args:\n fdatagrid (:class:`FDataGrid`): Functions to be inverted.\n eval_points: (array_like, optional): Set of points where the\n functions are interpolated to obtain the inverse, by default uses\n the sample points of the fdatagrid.\n\n Returns:\n :class:`FDataGrid`: Inverse of the original functions.\n\n Raises:\n ValueError: If the functions are not strictly increasing or are\n multidimensional.\n\n Examples:\n\n >>> import numpy as np\n >>> from skfda import FDataGrid\n >>> from skfda.preprocessing.registration import invert_warping\n\n We will construct the warping :math:`\\gamma : [0,1] \\rightarrow [0,1]`\n wich maps t to t^3.\n\n >>> t = np.linspace(0, 1)\n >>> gamma = FDataGrid(t**3, t)\n >>> gamma\n FDataGrid(...)\n\n We will compute the inverse.\n\n >>> inverse = invert_warping(gamma)\n >>> inverse\n FDataGrid(...)\n\n The result of the composition should be approximately the identity\n function .\n\n >>> identity = gamma.compose(inverse)\n >>> identity([0, 0.25, 0.5, 0.75, 1]).round(3)\n array([[ 0. , 0.25, 0.5 , 0.75, 1. ]])\n\n \"\"\"\n\n if fdatagrid.dim_codomain != 1 or fdatagrid.dim_domain != 1:\n raise ValueError(\"Multidimensional object not supported.\")\n\n if eval_points is None:\n eval_points = fdatagrid.sample_points[0]\n\n y = fdatagrid(eval_points, keepdims=False)\n\n data_matrix = np.empty((fdatagrid.n_samples, len(eval_points)))\n\n for i in range(fdatagrid.n_samples):\n data_matrix[i] = PchipInterpolator(y[i], eval_points)(eval_points)\n\n return fdatagrid.copy(data_matrix=data_matrix, sample_points=eval_points)\n\n\ndef _normalize_scale(t, a=0, b=1):\n \"\"\"Perfoms an afine translation to normalize an interval.\n\n Args:\n t (numpy.ndarray): Array of dim 1 or 2 with at least 2 values.\n a (float): Starting point of the new interval. Defaults 0.\n b (float): Stopping point of the new interval. Defaults 1.\n\n Returns:\n (numpy.ndarray): Array with the transformed interval.\n \"\"\"\n\n t = t.T # Broadcast to normalize multiple arrays\n t1 = (t - t[0]).astype(float) # Translation to [0, t[-1] - t[0]]\n t1 *= (b - a) / (t[-1] - t[0]) # Scale to [0, b-a]\n t1 += a # Translation to [a, b]\n t1[0] = a # Fix possible round errors\n t1[-1] = b\n\n return t1.T\n\n\ndef normalize_warping(warping, domain_range=None):\n r\"\"\"Rescale a warping to normalize their domain.\n\n Given a set of warpings :math:`\\gamma_i:[a,b]\\rightarrow [a,b]` it is\n used an affine traslation to change the domain of the transformation to\n other domain, :math:`\\tilde \\gamma_i:[\\tilde a,\\tilde b] \\rightarrow\n [\\tilde a, \\tilde b]`.\n\n Args:\n warping (:class:`FDatagrid`): Set of warpings to rescale.\n domain_range (tuple, optional): New domain range of the warping. By\n default it is used the same domain range.\n Return:\n (:class:`FDataGrid`): FDataGrid with the warpings normalized.\n\n \"\"\"\n\n if domain_range is None:\n domain_range = warping.domain_range[0]\n\n data_matrix = _normalize_scale(warping.data_matrix[..., 0], *domain_range)\n sample_points = _normalize_scale(warping.sample_points[0], *domain_range)\n\n return warping.copy(data_matrix=data_matrix, sample_points=sample_points,\n domain_range=domain_range)\n","sub_path":"skfda/preprocessing/registration/_registration_utils.py","file_name":"_registration_utils.py","file_ext":"py","file_size_in_byte":12002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"313329033","text":"# merging 3 data xlsx\nfrom openpyxl import *\nfrom openpyxl.chart import *\nimport numpy as np #주의! numpy data type는 일반형으로 전환해야 openpyxl이용가능 \nimport datetime\n\ndata_buffer1 = [] # 상품명: 상품1, 상품2, ... 상품10\ndata_buffer2 = [[] for i in range(3)] # 영업1팀 상품1판매, 상품2판매... 상품10판매, 영업2팀 상품1판매, 상품2판매.... 상품10판매, 영업3팀 상품1판매, 상품2.... 상품10판매량\nfor i in range(3): # 3개의 영업팀마다 루프\n\tfile_name = './movie_1data/data'+str(i+1)+'.xlsx' # data1.xlsx, data2.xlsx, data3.xlsx ---> filename\n\tbook = load_workbook(file_name,data_only = True) # data#.xlsx의 sheet1 data_only -> 단순 숫자만 호출, True호출 안할시 숫자x 함수식을 반환 30 (=sum(a3:a5))\n\tsheet = book.active # sheet1 활성화... 추후 원하는 sheet를 이름변경, 삭제, 복사 등등\n\t\n\tcells = sheet['A4:B13'] # 우리가 원하는 데이터셀들 선택, 헤더 제외\n\tfor c1, c2 in cells:\n\t\tif i == 0:\n\t\t\tdata_buffer1.append(c1.value) # value 내부함수 안적을시 'sheet1:c1' 이런형식으로 호출\n\t\tdata_buffer2[i].append(c2.value) # 각 영업팀마다 상품 아이템의 판매량 \n\n# book과 sheet를 메모리상에서 지움\ndel book \ndel sheet\n\t\t\n#open new excel sheet\nbook = Workbook() # 새로운 엑셀시트를 호출! \nsheet = book.active\t# sheet1을 활성화\n\n# 이 밑 두줄 처럼 np쓰고 형변환 'tolist()'안쓰면 망\t\t\ndata_buffer1 = np.array(data_buffer1[:]) # sum 그리고 mean값을 구하기위해 numpy로 변환\ndata_buffer2 = np.array(data_buffer2[:])\n\nrows = []\nfor i in range(len(data_buffer1)): # 상품1, 상품2, 상품3.... 상품10 루프\n\tdummy = [] \n\tdummy.append(data_buffer1[i].tolist()) #'상품1' append\n\tdummy.extend([data_buffer2[0][i].tolist(),data_buffer2[1][i].tolist(),data_buffer2[2][i].tolist()]) # 영업1팀 상품1판매량(수치), 영업2팀 상품1판매량(수치), 영업3팀의 상품판매량(수치) append\n\tmax_val = np.max([data_buffer2[0][i],data_buffer2[1][i],data_buffer2[2][i]]).tolist() \n\tdummy.append(max_val) # 3개 영업팀중 i번째 상품 판매량 최대판매량 \n\tmean_val = np.mean([data_buffer2[0][i],data_buffer2[1][i],data_buffer2[2][i]]).tolist()\n\tdummy.append(mean_val) # 3개 영업팀의 i번째 상품 판매량 평균\n\trows.append(dummy) # rows == [상품i, 영업1팀판매량, 영업2팀판매량, 영업3팀판매량, 최대판매량, 평균판매량] * 10개의 상품\n \nsheet.append(['상품명','영업1팀','영업2팀','영업3팀','최대판매량','평균판매량']) # 새로불러온 엑셀시트에 작성 \nfor row in rows: # 10개의 상품 루프실행\n\tsheet.append(row) #새 엑셀시트에 row를 작성\n\t\n'''\t\nmean and max value and draw bar-chart\n'''\ndata = Reference(sheet,min_col=2, max_col=4, min_row=1, max_row=11) #엑셀시트 데이터 부분\ncategs = Reference(sheet, min_col=1, min_row=2, max_row=11) #엑셀시트 카테고리부분\n\nchart = BarChart() #막대그래프 호출\nchart.add_data(data,titles_from_data = True) #막대그래프 데이터파일 덧씌우기\nchart.set_categories(categs)\n\nchart.legened=None # 차트의 legend 생략\nchart.y_axis.majorGridlines=None # y축의 점선 생략\nchart.varyColors=True # 차트의 색상은 알록달록\nchart.title='일간 영업팀별 상품판매량 비교표' # 차트의 제목\nsheet.add_chart(chart,'A12') # A12셀에 차트 삽입\n\n# get today's date \nnow = datetime.datetime.now() # 2019-06-09 22:57 \nnowdate = now.strftime('%Y-%m-%d') # '2019-06-09'\nfile_name = str(nowdate)+'summary.xlsx' # '2019-06-09summary.xlsx'\nbook.save(file_name) #엑셀파일 생성","sub_path":"excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"110667281","text":"import base64\n\nimport unittest2\nfrom boto.kms.exceptions import InvalidCiphertextException\nfrom mock import patch\n\nfrom cfn_sphere.aws.kms import KMS\nfrom cfn_sphere.exceptions import InvalidEncryptedValueException\n\n\nclass KMSTests(unittest2.TestCase):\n @patch('cfn_sphere.aws.kms.kms.connect_to_region')\n def test_decrypt_value(self, kms_mock):\n kms_mock.return_value.decrypt.return_value = {'Plaintext': b'decryptedValue'}\n\n self.assertEqual('decryptedValue', KMS().decrypt(\"ZW5jcnlwdGVkVmFsdWU=\"))\n kms_mock.return_value.decrypt.assert_called_once_with(base64.b64decode(\"ZW5jcnlwdGVkVmFsdWU=\".encode()))\n\n @patch('cfn_sphere.aws.kms.kms.connect_to_region')\n def test_decrypt_value_with_unicode_char(self, kms_mock):\n kms_mock.return_value.decrypt.return_value = {'Plaintext': b'(\\xe2\\x95\\xaf\\xc2\\xb0\\xe2\\x96\\xa1\\xc2\\xb0\\xef\\xbc\\x89\\xe2\\x95\\xaf\\xef\\xb8\\xb5 \\xe2\\x94\\xbb\\xe2\\x94\\x81\\xe2\\x94\\xbb'}\n\n self.assertEqual(u'(\\u256f\\xb0\\u25a1\\xb0\\uff09\\u256f\\ufe35 \\u253b\\u2501\\u253b', KMS().decrypt(\"KOKVr8Kw4pahwrDvvInila/vuLUg4pS74pSB4pS7\"))\n kms_mock.return_value.decrypt.assert_called_once_with(base64.b64decode(\"KOKVr8Kw4pahwrDvvInila/vuLUg4pS74pSB4pS7\".encode()))\n\n\n @patch('cfn_sphere.aws.kms.kms.connect_to_region')\n def test_invalid_base64(self, kms_mock):\n with self.assertRaises(InvalidEncryptedValueException):\n KMS().decrypt(\"asdqwda\")\n\n @patch('cfn_sphere.aws.kms.kms.connect_to_region')\n def test_invalid_kms_key(self, kms_mock):\n kms_mock.return_value.decrypt.side_effect = InvalidCiphertextException(\"400\", \"Bad Request\")\n\n with self.assertRaises(InvalidEncryptedValueException):\n KMS().decrypt(\"ZW5jcnlwdGVkVmFsdWU=\")\n","sub_path":"src/unittest/python/aws/kms_tests.py","file_name":"kms_tests.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"652060769","text":"import threading\nimport tkinter as tk\nfrom tkinter import messagebox\n\nimport numpy as np\nfrom PIL import ImageGrab\n\nfrom qqx.gui import progress, output\nfrom qqx.gui.debug import image_debug\nfrom qqx.gui.debug import log_debug\nfrom qqx.logic import core\n\n\ndef button(window, store):\n # Analysis\n store['btn'] = tk.Button(window, text='分析', bd='5', command=lambda: on_click(window, store))\n store['btn'].pack()\n\n store['is_robust'] = tk.IntVar()\n store['is_robust_chk'] = tk.Checkbutton(window, text=\"超级分析(贼慢)\", variable=store['is_robust'])\n store['is_robust_chk'].pack()\n\n # Debug\n debug_frame = tk.Frame(window)\n store['btn_debug'] = tk.Button(debug_frame, text='图像', bd='5',\n command=lambda: image_debug.create_window(window, store))\n store['btn_debug'].pack(side=tk.LEFT)\n store['btn_debug_log'] = tk.Button(debug_frame, text='日志', bd='5',\n command=lambda: log_debug.create_window(window, store))\n store['btn_debug_log'].pack(side=tk.RIGHT)\n debug_frame.pack()\n\n\ndef set_disable(store):\n store['btn']['state'] = 'disabled'\n store['btn_debug']['state'] = 'disabled'\n store['btn_debug_log']['state'] = 'disabled'\n store['is_robust_chk'].config(state=tk.DISABLED)\n\n\ndef set_enable(store):\n store['btn']['state'] = 'normal'\n store['btn_debug']['state'] = 'normal'\n store['btn_debug_log']['state'] = 'normal'\n store['is_robust_chk'].config(state=tk.NORMAL)\n\n\ndef update_progress_bar(val, store, window):\n progress.set_value(val, store)\n window.update()\n\n\ndef logger(log, store):\n print(log)\n store['log'].append(str(log))\n\n\ndef on_click(window, store):\n im = ImageGrab.grabclipboard()\n if im is None:\n messagebox.showwarning('错误', '剪切板内没有图像')\n return\n\n # init state\n set_disable(store)\n store['log'] = []\n\n threading.Thread(target=run_analysis, args=(im, store, window)).start()\n\n\ndef run_analysis(im, store, window):\n try:\n public_cards, my_cards, img_rgb = core.process(\n np.array(im),\n progress_updater=lambda val: update_progress_bar(val, store, window),\n logger=lambda log: logger(log, store),\n is_robust=store['is_robust'].get()\n )\n store['img_rgb'] = img_rgb\n output.set_my_cards(my_cards, store)\n output.set_public_cards(public_cards, store)\n except Exception:\n messagebox.showwarning('分析出错', '请查看日志')\n finally:\n set_enable(store)\n","sub_path":"qqx/gui/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"138626484","text":"import json\nimport urllib\nimport re\nimport StringIO\n\nimport celery\nimport cwt\nimport django\nfrom django import http\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom django.views.decorators.http import require_http_methods\nfrom lxml import etree\n\nfrom . import common\nfrom wps import backends\nfrom wps import helpers\nfrom wps import metrics\nfrom wps import models\nfrom wps import tasks\nfrom wps import WPSError\nfrom wps.util import wps as wps_util\n\nlogger = common.logger\nclass WPSExceptionError(WPSError):\n def __init__(self, message, code):\n self.report = wps_util.exception_report(settings, message, code)\n\n super(WPSExceptionError, self).__init__('WPS Exception')\n\nclass WPSScriptGenerator(object):\n def __init__(self, variable, domain, operation, user):\n self.operation = operation\n\n self.domain = domain\n\n self.variable = variable\n\n self.user = user\n\n self.root_op = None\n\n def write_header(self, buf):\n buf.write('import cwt\\nimport time\\n\\n')\n\n buf.write('api_key=\\'{}\\'\\n\\n'.format(self.user.auth.api_key))\n\n buf.write('wps = cwt.WPSClient(\\'{}\\', api_key=api_key)\\n\\n'.format(settings.WPS_ENDPOINT))\n\n def write_variables(self, buf):\n for v in self.variable.values():\n buf.write('var-{} = cwt.Variable(\\'{}\\', \\'{}\\')\\n'.format(v.name, v.uri, v.var_name))\n\n buf.write('\\n')\n\n def write_domain(self, buf):\n for d in self.domain.values():\n buf.write('dom-{} = cwt.Domain([\\n'.format(d.name))\n\n for dim in d.dimensions:\n buf.write('\\tcwt.Dimension(\\'{}\\', \\'{}\\', \\'{}\\', crs=cwt.VALUES, step=\\'{}\\'),\\n'.format(dim.name, dim.start, dim.end, dim.step))\n\n buf.write('])\\n\\n')\n\n def write_processes(self, buf):\n for o in self.operation.values():\n buf.write('op-{} = wps.process(\\'{}\\')\\n\\n'.format(o.name, o.identifier))\n\n op = self.operation.values()[0]\n\n self.root_op = 'op-{}'.format(op.name)\n\n buf.write('wps.execute(op-{}, inputs=['.format(op.name))\n\n l = len(op.inputs) - 1\n\n for i, v in enumerate(op.inputs):\n buf.write('var-{}'.format(v.name))\n\n if i < l:\n buf.write(', ')\n\n if op.domain is not None:\n buf.write('], domain=dom-{}'.format(op.domain.name))\n\n if 'domain' in op.parameters:\n del op.parameters['domain']\n\n if 'gridder' in op.parameters:\n g = op.parameters['gridder']\n\n buf.write(', gridder=cwt.Gridder(\\'{}\\', \\'{}\\', \\'{}\\')'.format(g.tool, g.method, g.grid))\n\n del op.parameters['gridder']\n\n for p in op.parameters.values():\n buf.write(', {}={}'.format(p.name, p.values))\n\n buf.write(')\\n\\n')\n\n def write_status(self, buf):\n buf.write('while {}.processing:\\n'.format(self.root_op))\n\n buf.write('\\tprint {}.status\\n\\n'.format(self.root_op))\n\n buf.write('\\ttime.sleep(1)\\n\\n'.format(self.root_op))\n\n def write_output(self, buf):\n buf.write('print {}.status\\n\\n'.format(self.root_op))\n\n buf.write('try:\\n\\timport vcs\\n\\timport cdms2\\nexcept:\\n\\tpass\\nelse:\\n')\n\n buf.write('\\tf = cdms2.open({}.output.uri)\\n\\n'.format(self.root_op))\n\n buf.write('\\tv = vcs.init()\\n\\n')\n\n buf.write('\\tv.plot(f[{}.output.var_name])'.format(self.root_op))\n\n def generate(self):\n buf = StringIO.StringIO()\n\n self.write_header(buf)\n\n self.write_variables(buf)\n\n self.write_domain(buf)\n\n self.write_processes(buf)\n\n self.write_status(buf)\n\n self.write_output(buf)\n\n data = buf.getvalue()\n\n buf.close()\n\n return data\n\ndef load_data_inputs(data_inputs, resolve_inputs=False):\n o, d, v = cwt.WPSClient.parse_data_inputs(data_inputs)\n\n v = dict((x.name, x) for x in v)\n\n d = dict((x.name, x) for x in d)\n\n o = dict((x.name, x) for x in o)\n\n logger.info('Loaded variables %r', v)\n\n logger.info('Loaded domains %r', d)\n\n logger.info('Loaded operations %r', o)\n\n if resolve_inputs:\n collected_inputs = list(y for x in o.values() for y in x.inputs)\n\n try:\n root_op = [o[x] for x in o.keys() if x not in collected_inputs][0]\n except IndexError as e:\n raise WPSError('Error resolving root operation')\n\n root_op.resolve_inputs(v, o)\n\n try:\n for x in o.values():\n if x.domain is not None:\n x.domain = d[x.domain]\n except KeyError as e:\n raise WPSerror('Error resolving domain')\n\n return o, d, v\n\ndef get_parameter(params, name, required=True):\n \"\"\" Gets a parameter from a django QueryDict \"\"\"\n\n # Case insesitive\n temp = dict((x.lower(), y) for x, y in params.iteritems())\n\n if name.lower() not in temp:\n logger.info('Missing required parameter %s', name)\n\n raise WPSExceptionError(name.lower(), cwt.ows.MissingParameterValue)\n\n param = temp.get(name.lower())\n\n if required and param is None:\n raise WPSError('Missing required parameter')\n\n return param\n\ndef handle_get_capabilities(host=None):\n if host is None:\n host = 'default'\n\n server = models.Server.objects.get(host=host)\n\n return server.capabilities\n\ndef handle_describe_process(identifiers):\n processes = models.Process.objects.filter(identifier__in=identifiers)\n\n return wps_util.process_descriptions_from_processes(settings, processes)\n\ndef handle_execute(api_key, identifier, data_inputs):\n try:\n user = models.User.objects.filter(auth__api_key=api_key)[0]\n except IndexError:\n raise WPSError('Missing API key for WPS execute request')\n\n try:\n process = models.Process.objects.get(identifier=identifier)\n except models.Process.DoesNotExist:\n raise WPSError('Process \"{identifier}\" does not exist', identifier=identifier)\n\n # load the process drescription to get the data input descriptions\n process_descriptions = cwt.wps.CreateFromDocument(process.description)\n\n description = process_descriptions.ProcessDescription[0]\n\n kwargs = {\n 'variable': None,\n 'domain': None,\n 'operation': None,\n }\n\n # load up the required data inputs for the process\n if description.DataInputs is not None:\n for x in description.DataInputs.Input:\n input_id = x.Identifier.value().lower()\n\n try:\n data = json.loads(data_inputs[input_id])\n except KeyError:\n raise WPSError('Missing required input \"{input_id}\" for process {name}', input_id=input_id, name=identifier)\n\n if input_id == 'variable':\n data = [cwt.Variable.from_dict(x) for x in data]\n elif input_id == 'domain':\n data = [cwt.Domain.from_dict(x) for x in data]\n elif input_id == 'operation':\n data = [cwt.Process.from_dict(x) for x in data]\n else:\n raise WPSError('Unknown input %r', input_id)\n\n kwargs[input_id] = dict((x.name, x) for x in data)\n\n server = models.Server.objects.get(host='default')\n\n job = models.Job.objects.create(server=server, process=process, user=user, extra=json.dumps(data_inputs))\n\n # at this point we've accepted the job\n job.accepted()\n\n logger.info('Acceped job %r', job.id)\n\n kwargs.update({\n 'identifier': identifier,\n 'user': user,\n 'job': job,\n 'process': process,\n })\n\n try:\n backend = backends.Backend.get_backend(process.backend)\n\n if backend is None:\n raise WPSError('Unknown backend \"{name}\"', name=process.backend)\n\n backend.execute(**kwargs)\n except Exception as e:\n logger.exception('Error executing backend %r', process.backend)\n\n if not job.is_started:\n job.started()\n\n job.failed(wps_util.exception_report(settings, str(e), cwt.ows.NoApplicableCode))\n\n raise\n\n return job.report\n\ndef handle_get(params, query_string):\n \"\"\" Handle an HTTP GET request. \"\"\"\n request = get_parameter(params, 'request', True).lower()\n\n service = get_parameter(params, 'service', True)\n\n data_inputs = {}\n\n logger.info('GET request %r, service %r', request, service)\n\n if request == 'getcapabilities':\n with metrics.WPS_REQUESTS.labels('GetCapabilities', 'GET').time():\n response = handle_get_capabilities() \n elif request == 'describeprocess':\n identifier = get_parameter(params, 'identifier', True).split(',')\n\n with metrics.WPS_REQUESTS.labels('DescribeProcess', 'GET').time():\n response = handle_describe_process(identifier)\n elif request == 'execute':\n api_key = get_parameter(params, 'api_key', True)\n\n identifier = get_parameter(params, 'identifier', True)\n\n query_string = urllib.unquote(query_string)\n\n if 'datainputs' in query_string:\n match = re.match('.*datainputs=\\[(.*)\\].*', query_string)\n\n if match is not None:\n # angular2 encodes ; breaking django query_string parsing so the \n # webapp replaces ; with | and the change is reverted before parsing\n # the datainputs\n data_inputs = re.sub('\\|(operation|domain|variable)=', ';\\\\1=', match.group(1))\n\n data_inputs = dict(x.split('=') for x in data_inputs.split(';'))\n\n with metrics.WPS_REQUESTS.labels('Execute', 'GET').time():\n response = handle_execute(api_key, identifier, data_inputs)\n else:\n raise WPSError('Operation \"{name}\" is not supported', name=request)\n\n return response\n\ndef handle_post(data, params):\n \"\"\" Handle an HTTP POST request. \n\n NOTE: we only support execute requests as POST for the moment\n \"\"\"\n try:\n request = cwt.wps.CreateFromDocument(data)\n except Exception as e:\n raise WPSError('Malformed WPS execute request')\n\n if isinstance(request, cwt.wps.CTD_ANON_11):\n raise WPSError('GetCapabilities POST not supported')\n elif isinstance(request, cwt.wps.CTD_ANON_12):\n raise WPSError('DescribeProcess POST not supported')\n\n data_inputs = {}\n\n for x in request.DataInputs.Input:\n data_inputs[x.Identifier.value()] = x.Data.LiteralData.value()\n\n api_key = params.get('api_key')\n\n logger.info('Handling POST request for API key %s', api_key)\n\n with metrics.WPS_REQUESTS.labels('Execute', 'POST').time():\n response = handle_execute(api_key, request.Identifier.value(), data_inputs)\n\n return response\n\n@metrics.WPS_ERRORS.count_exceptions()\ndef handle_request(request):\n \"\"\" Convert HTTP request to intermediate format. \"\"\"\n if request.method == 'GET':\n return handle_get(request.GET, request.META['QUERY_STRING'])\n elif request.method == 'POST':\n return handle_post(request.body, request.GET)\n\n@require_http_methods(['POST'])\ndef generate(request):\n try:\n common.authentication_required(request)\n\n data_inputs = request.POST['datainputs']\n\n data_inputs = re.sub('\\|(domain|operation|variable)=', ';\\\\1=', data_inputs, 3)\n\n o, d, v = load_data_inputs(data_inputs, resolve_inputs=True)\n\n script = WPSScriptGenerator(v, d, o, request.user)\n\n kernel = o.values()[0].identifier.split('.')[1]\n\n data = {\n 'filename': '{}.py'.format(kernel),\n 'text': script.generate()\n }\n except WPSError as e:\n return common.failed(str(e))\n else:\n return common.success(data)\n\n@require_http_methods(['GET', 'POST'])\n@ensure_csrf_cookie\ndef wps_entrypoint(request):\n response = None\n\n try:\n response = handle_request(request)\n except WPSExceptionError as e:\n logger.exception('WSPExceptionError %r %r', request.method, request.path)\n\n response = e.report\n except WPSError as e:\n logger.exception('WPSError %r %r', request.method, request.path)\n\n response = wps_util.exception_report(settings, str(e), cwt.ows.NoApplicableCode)\n except Exception as e:\n logger.exception('Some generic exception %r %r', request.method, request.path)\n\n error = 'Please copy the error and report on Github: {}'.format(str(e))\n\n response = wps_util.exception_report(settings, error, cwt.ows.NoApplicableCode)\n\n return http.HttpResponse(response, content_type='text/xml')\n\n@require_http_methods(['GET'])\ndef regen_capabilities(request):\n try:\n common.authentication_required(request)\n\n common.authorization_required(request)\n\n server = models.Server.objects.get(host='default')\n\n processes = []\n\n for process in server.processes.all():\n proc = cwt.wps.process(process.identifier, process.identifier, '1.0.0')\n\n processes.append(proc)\n\n process_offerings = cwt.wps.process_offerings(processes)\n\n server.capabilities = wps_util.generate_capabilities(settings, process_offerings)\n\n server.save()\n except WPSError as e:\n return common.failed(str(e))\n else:\n return common.success('Regenerated capabilities')\n\n@require_http_methods(['GET'])\ndef status(request, job_id):\n try:\n job = models.Job.objects.get(pk=job_id)\n except models.Job.DoesNotExist:\n raise WPSError('Status for job \"{job_id}\" does not exist', job_id=job_id)\n\n return http.HttpResponse(job.report, content_type='text/xml')\n\n@require_http_methods(['GET'])\ndef ping(request):\n return http.HttpResponse('pong')\n","sub_path":"compute/wps/views/wps_service.py","file_name":"wps_service.py","file_ext":"py","file_size_in_byte":13685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"110683052","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc, rcParams\nimport matplotlib.lines as mlines\nfrom matplotlib.pyplot import *\nfrom scipy import interpolate\nimport scipy.stats\nimport sys\nimport scipy.ndimage as ndimage\n\n# Energy, P(e to mu), P(mub to muv). Nevents Signal Nevens Background\nE, Peu, Pmubmub, vevus, vubvubs, vevub, vubvubb, cs_e, cs_mub, f_e, f_mub = np.genfromtxt('Events_sys.txt', unpack=True, skip_header=0)\nEp, Pmubmubp, PmubmubpN, Pmubmubp2, Pmubmubp2N, Pmubmubp3, Pmubmubp3N = np.genfromtxt('Prob.txt', unpack=True, skip_header=0)\n\n\nxmin = 0.01\nxmax = 200\nfsize = 8\nrc('text', usetex=True)\nparams={'axes.labelsize':fsize,'xtick.labelsize':fsize+1,'ytick.labelsize':fsize+1,\\\n\t\t'figure.figsize':(3.44961,2.9617)}\nrcParams['font.family'] = 'serif'\nrcParams['font.sans-serif'] = ['Computer Modern']\nrcParams.update(params)\n\n\n\nfig = plt.figure()\nax =fig.add_axes([0.1,0.17,0.77,0.77])\n# ax.scatter(E,vevu)\n\nEs = E-0.25/2\nEs[0] = E[0]-0.24/2\n\nEe = E+0.25/2\nEe[0] = E[0]+0.24/2\nrects2 = ax.bar(0.05/(Es), vevus, width =(0.05/Ee - 0.05/Es),\n color='purple', alpha=0.4, label=r'ND Signal', bottom=vevub)\nrects = ax.bar(0.05/(Es), vevub, width =(0.05/Ee - 0.05/Es),\n color='lightgreen', alpha=0.4, label=r'ND Background')\n\nrects4 = ax.bar(2.0/(Es), vubvubs, width =(2.0/Ee - 2.0/Es),\n color='lightblue', alpha=0.4, label=r'FD Signal', bottom=vubvubb)\nrects3 = ax.bar(2.0/(Es), vubvubb, width =(2.0/Ee - 2.0/Es),\n color='orange', alpha=0.4, label=r'FD Background')\n\n\naxt = ax.twinx()\naxt.plot(0.05/Ep, PmubmubpN, color='lightblue', label=r'$P_{\\overline{\\nu}_{\\mu} \\to \\overline{\\nu}_{\\mu}} (L = 2 km, E)$')\n\naxt.plot(2.0/Ep, Pmubmubp, color='orange')\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\n\nax.set_xlabel(r'L/E (km/GeV)')\nax.set_ylabel(r'Events ($\\nu$)')\naxt.set_ylabel(r'$P(\\overline{\\nu}_{\\mu} \\to \\overline{\\nu}_{\\mu})$')\n\n# ax.set_xlim(xmin,xmax)\n# ax.set_ylim(0,)\n# axt.set_xlim(xmin,xmax)\naxt.set_ylim(0.90,1.005)\n# ax.set_yticks((0,2e6,4e6, 6e6,8e6))\naxt.set_yticks((0.90,0.95,1.0))\n# ax.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))\n# axt.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))\n\n\nax.legend(loc='upper right', shadow=0, fontsize=fsize-1, frameon=0)\naxt.legend(loc='lower right', shadow=0, fontsize=fsize-1, frameon=0)\n\nax.text(1.1,1e4, 'FD')\n\nax.set_xlim(xmin,xmax)\naxt.set_xlim(xmin,xmax)\n\n# axt.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))\n# ax.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))\n\n\nplt.show()\nfig.savefig('Plots/Prob_ND_FD.pdf')","sub_path":"code/new_code/NDFD.py","file_name":"NDFD.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"109103110","text":"import torch\nimport torchvision\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport os\nimport torch.backends.cudnn as cudnn\n\nfrom torch.autograd import Variable\nfrom torchcv.transforms import resize\nfrom torchcv.datasets import ListDataset\nfrom torchcv.evaluations.voc_eval import voc_eval\n# from torchcv.models.ssd import FPNMobileNetV2SSD512,SSD300, SSDBoxCoder\nfrom torchcv.models.fpnssd import FPNMobileNetV2SSD512, FPNSSDBoxCoder\n\nfrom PIL import Image\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,2\"\n\nprint('Loading model..')\n# net = SSD300(num_classes=21)\n# net.load_state_dict(torch.load('./examples/ssd/checkpoint/ckpt.pth'))\n# net.cuda()\n# net.eval()\n\nnet = FPNMobileNetV2SSD512(num_classes=21).to('cuda')\nnet = torch.nn.DataParallel(net)\ncudnn.benchmark = True\n\ncheckpoint = torch.load('/home/ysdu/torchcv/examples/fpnssd/checkpoint/ckpt.pth')\nnet.load_state_dict(checkpoint['net'])\nbest_loss = checkpoint['loss']\nstart_epoch = checkpoint['epoch']\nnet.cuda()\nnet.eval()\n \nprint('Preparing dataset..')\nimg_size = 512\ndef transform(img, boxes, labels):\n img, boxes = resize(img, boxes, size=(img_size,img_size))\n img = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.485,0.456,0.406),(0.229,0.224,0.225))\n ])(img)\n return img, boxes, labels\n\ndataset = ListDataset(root='/home/ysdu/hardwareDisk/ysduDir/voc/voc_all_images', \\\n list_file='torchcv/datasets/voc/voc07_test.txt',\n transform=transform)\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, num_workers=2)\nbox_coder = FPNSSDBoxCoder()\n\npred_boxes = []\npred_labels = []\npred_scores = []\ngt_boxes = []\ngt_labels = []\n\nwith open('torchcv/datasets/voc/voc07_test_difficult.txt') as f:\n gt_difficults = []\n for line in f.readlines():\n line = line.strip().split()\n d = [int(x) for x in line[1:]]\n gt_difficults.append(d)\n\ndef eval(net, dataset):\n for i, (inputs, box_targets, label_targets) in enumerate(dataloader):\n print('%d/%d' % (i, len(dataloader)))\n gt_boxes.append(box_targets.squeeze(0))\n gt_labels.append(label_targets.squeeze(0))\n\n loc_preds, cls_preds = net(Variable(inputs.cuda(), volatile=True))\n box_preds, label_preds, score_preds = box_coder.decode(\n loc_preds.cuda().data.squeeze(),\n F.softmax(cls_preds.squeeze(), dim=1).cuda().data,\n score_thresh=0.01)\n\n pred_boxes.append(box_preds)\n pred_labels.append(label_preds)\n pred_scores.append(score_preds)\n\n print (voc_eval(\n pred_boxes, pred_labels, pred_scores,\n gt_boxes, gt_labels, gt_difficults,\n iou_thresh=0.5, use_07_metric=True))\n\neval(net, dataset)\n","sub_path":"examples/fpnssd/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"94862603","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# 動画ファイルから、顔認識したものを取り出す\n\n# 分類器をアニメ向けのもの使用\nfrom __future__ import print_function\nimport cv2\nimport time\nfrom IPython import embed\n\n# 分類器へのパス\ncascade_path = 'lbpcascade_animeface.xml'\n\n# 動画パス\nvideo_path = 'gochiusa_01.avi'\nout_video_path = 'gochiusa_01.out.avi'\n\n# colorはBGRの順番?\ncolor = (0, 187, 254) #黄\n#カスケード分類器の特徴量を取得する\ncascade = cv2.CascadeClassifier(cascade_path)\n\nfourcc = cv2.cv.CV_FOURCC('I', '4', '2', '0')\n# 動画ファイル読み込み\ncap = cv2.VideoCapture(video_path)\nif not cap.isOpened():\n raise IOError('cannot open a video {}'.format(video_path))\n\nout = cv2.VideoWriter(out_video_path, fourcc, fps=30.0, frameSize=(1920, 1000))\n\nframe_num = 0\nimg_cnt = 0\n# フレームごとの処理\nwhile cap.isOpened():\n continue_flag, frame = cap.read()\n if not continue_flag:\n break\n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n facerect = cascade.detectMultiScale(frame_gray, scaleFactor=1.1, minNeighbors=1, minSize=(1, 1))\n\n print('frame : {}'.format(frame_num))\n if len(facerect) > 0:\n #検出した顔を囲む矩形の作成\n for x, y, w, h in facerect:\n cv2.rectangle(frame, (x, y), (x + w, y + h), color, thickness=7)\n img_cnt += 1\n out.write(frame)\n frame_num += 1\n\ncap.release()\ncv2.destroyAllWindows()\nout.release()\n","sub_path":"face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"77665289","text":"import re\nimport shutil\n\n# res = re.match('a', 'back')\n# res1 = re.search('a.', 'back read')\n# res2 = re.search('^a', 'back')\n# res3 = re.findall('a.', 'back read')\n# res4 = re.finditer('a.', 'back read')\n#\n# print(res1.group())\n# print(res2)\n# print(res3)\n# for m in res4:\n# print(m.group())\nre.compile\nstr = re.compile('wjy')\nm = str.search('nice to meet your wjy!')\nprint(m.group())\n\nalist = re.split(',|\\*', 'ni*hao,hao*are,your')\nprint(alist)\n\nss = re.sub('x', 'wjy', 'x nic to meet your')\nprint(ss)\n","sub_path":"python2/day4/myre.py","file_name":"myre.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"361311701","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 15 23:33:05 2020\r\n\r\n@author: khahn\r\n\"\"\"\r\n\r\n# imports\r\nimport spacy\r\nimport pandas as pd\r\nfrom nltk.tokenize import word_tokenize\r\nimport All_Functions as af\r\nfrom collections import Counter\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nnlp = spacy.load('es_core_news_sm')\r\n\r\n# Variables \r\nwordsThatArePeople = ['director','viceministro','alcalde','presidente',\r\n 'cineasta','cantante','expresidente','jefe','inspector',\r\n 'inmigrante','magnate', 'inspector','protagonista',\r\n 'productor','mentor','actor','autor','servidor','esposo',\r\n 'extranjero','juicio','agentes','sheriff','guardacostas',\r\n 'senador','joven','mexicano','trabajador', 'repartidor', \r\n 'gobernador','constructor','poblano','profesor', 'solicitante',\r\n 'vecino', 'comisario','fiscal','juez','líder', 'africanos',\r\n 'subsecretario','etíopes','eritreos', 'nigerianos','hombre',\r\n 'dueño','extranjero', 'secretario','embajador',\r\n 'guatemalteco','conductor','funcionario', 'cabo',\r\n 'titular', 'canciller', 'criaturas','asesinato',\r\n 'representante','poblano','gobernador', 'secretario',\r\n 'panadero', 'manager','diputado','sacerdote', 'padre',\r\n 'empleador', 'pollero', 'hermano','portavoz','señora',\r\n 'migrante', 'guardia','vocero','periodista','migrantes', \r\n 'extraficantes','vicepresidente','guatemalteca','alcaldesa',\r\n 'vicegobernadora', 'víctima','funcionaria', 'presidenta',\r\n 'esposa','autoridades','secretaria', 'doctor', 'viudo', \r\n 'investigadora', 'mujer','procesadora', 'niña', 'jueza',\r\n 'policía','directora','actriz','mujeres','estudiantes',\r\n 'mexicanas','cameruneses','víctimas','esposas','personas',\r\n 'indocumentados','familias','latinos', 'héroes','lectores',\r\n 'obreros', 'sacerdotes', 'corruptos', 'varones', 'líderes',\r\n 'párroco', 'señores','egresados','transmigrantes',\r\n 'estudiantes', 'chavos','dueños', 'familiares','jóvenes', \r\n 'diputados','niños','asaltantes','narcotraficantes', \r\n 'pasajeros', 'hondureños','poblanos', 'conciudadanos','rusos',\r\n 'indígenas', 'pobres','legisladores','centroamericanos',\r\n 'americanos', 'hijos','infectados', 'asistentes','miembro',\r\n 'juzgados','habitantes','agricultores', 'productores',\r\n 'humanos', 'equipos','usuarios','especialistas','funcionarios',\r\n 'sobrevivientes','periodistas', 'hermanos','titulares',\r\n 'enfermos','granjeros', 'profesionales','vecindarios', \r\n 'padres', 'mexicanos', 'franceses', 'jefes','congresistas',\r\n 'doctores','vecinos', 'familias','paisanos','avatares',\r\n 'miembros','investigadores', 'solicitantes', 'republicanos',\r\n 'indocumentados', 'demócratas', 'testigos', 'candidatos',\r\n 'activistas','refugiados', 'rohingyas', 'menores',\r\n 'trabajadores', 'propietarios','residentes','personas',\r\n 'personajes','centroamericano','hija', 'custodia' 'enfermera',\r\n 'caravana','persona','familiares','gente','mayordomos','robots',\r\n 'traficantes','pandillas','empresarios','extranjeros',\r\n 'presidentes', 'policías', 'pacientes', 'estadounidenses', 'ciudadanos',\r\n 'custodia', 'enfermera','caravanas', 'hordas','mentes',\r\n 'alicantino','príncipe', 'animador', 'arquitecto', 'rector',\r\n 'candidato', 'decenio', 'artista', 'portador', 'médico', \r\n 'editor', 'poeta', 'reservista', 'bebé', 'pastor', 'papá', \r\n 'chofer', 'investigador', 'especialista', 'expertos', \r\n 'intérprete', 'austriaca', 'hombres', 'abuelita','paciente', \r\n 'portadora', 'chicos','autora', 'neoyorquina','críticos',\r\n 'familia','sobrina','madre','doctora','abogada', 'gerente',\r\n 'pintora', 'camioneta','pilotos', 'profesora','académicos', \r\n 'alumnos', 'integrantes', 'hombres', 'mujeres','seres', \r\n 'reclusos', 'conmovedoras','músicos', 'encarcelados',\r\n 'jornaleros', 'inmigrantes', 'empleadores', 'portadores',\r\n 'polleros','viajeros', 'estereotipos', 'hispanos', 'latinoamericanos',\r\n 'editores', 'escritores', 'supervivientes', 'detenidos', \r\n 'individuos','cocineros','médicos','coordinadores','guardacosta',\r\n 'delincuentes','huéspedes','ancianos', 'profesores', 'maestros',\r\n 'abusadores','científicas', 'ganadoras','niñas', 'enfermeras', \r\n 'costureras','amigas', 'amiga', 'amigo', 'amigos','inmigrantes',\r\n 'encargadas','maestras','maestra', 'maestros', 'maestro',\r\n 'empleadas', 'maquiladoras','parejas','pareja', 'marido',\r\n 'maridos']\r\n#clean this variable\r\npeopleVocab = []\r\nfor item in wordsThatArePeople:\r\n if item not in peopleVocab:\r\n peopleVocab.append(item)\r\n\r\n# Functions\r\n \r\n# gets toples with the positions of a value in a dataframe\r\n# input: pd dataframe, value to find\r\ndef getIndexes(dataframe, value):\r\n listOfPos = list()\r\n # Get bool dataframe with True at positions where the given value exists\r\n result = dataframe.isin([value])\r\n # Get list of columns that contains the value\r\n seriesObj = result.any()\r\n columnNames = list(seriesObj[seriesObj == True].index)\r\n # Iterate over list of columns and fetch the rows indexes where value exists\r\n for col in columnNames:\r\n rows = list(result[col][result[col] == True].index)\r\n for row in rows:\r\n listOfPos.append((row, col))\r\n # Return a list of tuples indicating the positions of value in the dataframe\r\n return listOfPos\r\n\r\n# gets the noun that follows a given article \r\n# input: article to search for, dataframe with colums 'part_of_speech' and 'text'\r\ndef get_searchedNoun(article, dataframe):\r\n indexes = []\r\n searchedNouns = []\r\n art_locations = getIndexes(dataframe, article) # get the location of the article\r\n for elt in range(len(art_locations)): # make a list of article indexes\r\n index = art_locations[elt][0]\r\n indexes.append(index)\r\n posdf = dataframe['part_of_speech']\r\n textdf = dataframe['text']\r\n for index in indexes:\r\n i = 1 \r\n while i < 5 and i + index < len(posdf):\r\n location = index + i\r\n if posdf[location] == 'NOUN': \r\n searchedNoun = textdf[location]\r\n searchedNouns.append(searchedNoun)\r\n break \r\n else:\r\n i += 1\r\n return searchedNouns\r\n \r\ndef get_token_sentences(sentence_list):\r\n return [word_tokenize(word) for word in sentence_list]\r\n\r\ndef sort_nouns(dataframe, article):\r\n peoplewords = []\r\n# notpeoplewords = []\r\n art_nouns = get_searchedNoun(article, dataframe)\r\n# for word in art_nouns:\r\n# if word not in notpeoplewords and word not in peopleVocab:\r\n# notpeoplewords.append(word)\r\n for word in art_nouns:\r\n if word in peopleVocab:\r\n peoplewords.append(word)\r\n# print(article, 'Not People Words:' ,notpeoplewords)\r\n return peoplewords\r\n\r\n\r\ndef load_possesiveNouns(pronoun, dataframe):\r\n indexes = []\r\n searchedWords = []\r\n pro_locations = getIndexes(dataframe, pronoun) # get the location of the article\r\n for elt in range(len(pro_locations)): # make a list of article indexes\r\n index = pro_locations[elt][0]\r\n indexes.append(index)\r\n textdf = dataframe['text']\r\n for index in indexes:\r\n location = index + 1\r\n if textdf[index] == pronoun:\r\n searchedWord = textdf[location]\r\n searchedWords.append(searchedWord)\r\n return searchedWords\r\n\r\ndef plot_frequency(text, title):\r\n counter = Counter(text)\r\n most = counter.most_common()\r\n x, y, = ([] for i in range(2))\r\n for word, count in most[:15]:\r\n x.append(word)\r\n y.append(count)\r\n sns.barplot(x=y, y=x, color='cyan').set_title(title)\r\n plt.show()\r\n \r\n\r\n# open the articles\r\nmigrantCsvDirectory = 'C:/Users/khahn/PycharmProjects/HypothesisA/articleDB/migrants/migrants/' \r\n# get articles from migrant folder\r\nurlsList = af.get_articles(migrantCsvDirectory)\r\n\r\n\r\n# get text and format it\r\nlistsOfSentences = []\r\nfor url in urlsList:\r\n text = af.get_page_sentences(url) # gets stripped p tags from each url\r\n listsOfSentences.append(text)\r\n\r\n\r\none_list_sentences = []\r\nfor elt in listsOfSentences: # make it just one list of all the strings\r\n for i in elt:\r\n one_list_sentences.append(i)\r\n\r\n\r\nnext_text = ' '.join(one_list_sentences)\r\ntest_text = nlp(next_text)\r\n\r\ndf = pd.DataFrame()\r\ndf['text'] = [token.text for token in test_text]\r\ndf['part_of_speech'] = [token.pos_ for token in test_text]\r\n \r\n\r\nel_nouns = sort_nouns(df, 'el')\r\nla_nouns = sort_nouns(df, 'la')\r\nlos_nouns = sort_nouns(df, 'los')\r\nlas_nouns = sort_nouns(df, 'las')\r\n\r\n\r\nprint(len(el_nouns))\r\nprint(len(la_nouns))\r\nprint(len(los_nouns))\r\nprint(len(las_nouns))\r\n\r\nel_nounsFreq = plot_frequency(el_nouns, 'El Nouns')\r\nla_nounsFreq = plot_frequency(la_nouns, 'la_nouns')\r\nlos_nounsFreq = plot_frequency(los_nouns, 'los_nouns')\r\nlas_nounsFreq = plot_frequency(las_nouns, 'las_nouns')\r\n\r\n\r\n\r\n#su_Freq = plot_frequency(su_nouns, 'Su_nouns')\r\n\r\ntesting_getindexes = getIndexes(df, 'su')\r\nprint('Got testing get indexes')\r\nlas_nouns = sort_nouns(df, 'su')\r\nprint('Got su sort nouns')\r\nsu_nouns = load_possesiveNouns(df, 'el')\r\n","sub_path":"POStagging.py","file_name":"POStagging.py","file_ext":"py","file_size_in_byte":10319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"152811344","text":"import numpy as np\n\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import r2_score, mean_squared_error, accuracy_score, make_scorer\n\nfrom .base import train_and_select_estimator\n\ndef train(X, y, pipeline=None):\n models = [\n ('svm', SVC(),\n [{\n 'kernel': ['rbf'],\n 'C': [.001, .005, .01, .05, .1, .5, 1, 5, 10, 50],\n 'gamma': [0, .001, .005, .01, .05, .1, .5, 1, 5, 10, 50],\n }, {\n 'kernel': ['poly'],\n 'C': [.001, .005, .01, .05, .1, .5, 1, 5, 10, 50],\n 'degree': range(2, 5)\n }, {\n 'kernel': ['linear'],\n 'C': [.001, .005, .01, .05, .1, .5, 1, 5, 10, 50]\n }]\n ),\n\n ('random_forest', RandomForestClassifier(),\n [{\n 'n_estimators': np.arange(2, 31, 2),\n 'criterion': ['gini', 'entropy'],\n 'max_features': ['sqrt', 'log2', None]\n }]\n ),\n\n ('mlp', MLPClassifier(solver='lbfgs'),\n [{\n 'alpha': 10.0 ** -np.arange(1, 7),\n 'hidden_layer_sizes': [\n (10, 10, 10), \n (50, 50, 50), \n (100, 100, 100), \n (110, 110, 110),\n (150, 150, 150),\n (200, 200, 200)\n ], \n 'activation': ['logistic', 'tanh', 'relu']\n }]\n )\n ]\n\n scores = {\n 'r2 score': r2_score,\n 'mean_squared_error': mean_squared_error,\n 'accuracy score': accuracy_score\n }\n scorer = make_scorer(accuracy_score)\n\n return train_and_select_estimator(models, X, y, scores, scorer, pipeline)\n","sub_path":"learning/models/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"223769812","text":"# This is a simple pytorch server demo shows how to use DGL distributed kvstore.\n# In this demo, we initialize two embeddings on server and push/pull data to/from it.\nimport dgl\nimport torch\nimport argparse\n\nserver_namebook, client_namebook = dgl.contrib.ReadNetworkConfigure('config.txt')\n\ndef start_server(args):\n server = dgl.contrib.KVServer(\n server_id=args.id, \n client_namebook=client_namebook, \n server_addr=server_namebook[args.id])\n\n server.start()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='kvstore')\n parser.add_argument(\"--id\", type=int, default=0, help=\"node ID\")\n args = parser.parse_args()\n\n start_server(args)\n","sub_path":"examples/pytorch/dis_kvstore/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"593386052","text":"from __future__ import print_function\n\nimport io\nimport os\nimport re\nimport pwd\nimport sys\nimport copy\nimport json\nimport math\nimport time\nimport random\nimport argparse\nimport traceback\nimport statistics as stats\n\nfrom nebula import (\n config,\n)\n\nfrom nebula.commons import *\n\n# ============================================================================================================================ #\n# kmer helpers\n# ============================================================================================================================ #\n\nchroms = {}\nwhole_genome_extracted = False\n\ndef extract_chromosome(chromosome):\n chromosome = chromosome.lower()\n if chromosome in chroms:\n print(yellow('loading from cache'))\n return chroms[chromosome]\n else:\n print(red('chromosome not found'), chromosome)\n if whole_genome_extracted:\n return None\n c = config.Configuration()\n sequence = ''\n print(yellow(c.reference))\n ref = open(c.reference)\n line = ref.readline().lower().strip()\n found = False\n while True:\n if line.startswith('>chr'):\n chrom = line[line.find('>') + 1:]\n if chrom == chromosome:\n print('extracting ' + chrom)\n while True:\n line = ref.readline().lower().strip()\n if line.startswith('>') or len(line) == 0:\n print(line)\n chroms[chromosome] = sequence\n return sequence\n sequence += line.upper()\n line = ref.readline().lower().strip()\n if len(line) == 0:\n break\n\ndef extract_chromosomes(chromosomes):\n c = config.Configuration()\n m = 0\n ref = open(c.reference)\n line = ref.readline().lower().strip()\n found = False\n sequence = ''\n while True:\n if line.startswith('>chr'):\n chrom = line[line.find('>') + 1:].strip().lower()\n if chrom in chromosomes:\n print('extracting ' + chrom)\n while True:\n line = ref.readline().lower().strip()\n if line.startswith('>') or len(line) == 0:\n print(len(sequence), 'bases')\n yield sequence, chrom\n sequence = ''\n found = True\n m += 1\n if m == len(chromosomes):\n return\n break\n sequence += line.upper()\n # this is to avoid skipping the last line we read for the previous chromosome (header of next)\n if found:\n found = False\n continue\n line = ref.readline().lower().strip()\n if len(line) == 0:\n break\n\ndef extract_whole_genome():\n c = config.Configuration()\n global whole_genome_extracted\n if whole_genome_extracted:\n return chroms\n print('extracting whole genome')\n if not c.chromosomes:\n a = ['chr' + str(x) for x in range(1, 23)]\n a.append('chrx')\n a.append('chry')\n else:\n a = [d.lower() for d in c.chromosomes]\n for seq, chrom in extract_chromosomes(a):\n chroms[chrom] = seq\n whole_genome_extracted = True\n return chroms\n\n","sub_path":"src/python/nebula/chromosomes.py","file_name":"chromosomes.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"652251879","text":"'''\nCORE APP\n\nCore views.\n\n'''\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.views import generic as generic_views\nfrom django.views.generic.detail import SingleObjectMixin\nfrom django.utils.translation import ugettext as _\n\nfrom tunobase.core import models, utils, mixins\n\nclass ListWithDetailView(generic_views.ListView, SingleObjectMixin):\n\n def get_object(self):\n return NotImplemented\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object_list = self.get_queryset()\n allow_empty = self.get_allow_empty()\n\n if not allow_empty:\n # When pagination is enabled and object_list is a queryset,\n # it's better to do a cheap query than to load the unpaginated\n # queryset in memory.\n if (self.get_paginate_by(self.object_list) is not None\n and hasattr(self.object_list, 'exists')):\n is_empty = not self.object_list.exists()\n else:\n is_empty = len(self.object_list) == 0\n if is_empty:\n raise Http404(_(\n \"Empty list and '%(class_name)s.allow_empty' is False.\"\n )\n % {'class_name': self.__class__.__name__})\n context = self.get_context_data()\n return self.render_to_response(context)\n\n\nclass MarkDeleteView(generic_views.DeleteView):\n\n def delete(self, request, *args, **kwargs):\n '''\n Calls the mark_deleted() method on the fetched object and then\n redirects to the success URL.\n '''\n self.object = self.get_object()\n success_url = self.get_success_url()\n self.object.mark_deleted()\n return HttpResponseRedirect(success_url)\n\n\nclass ContentBlockUpdate(mixins.AdminRequiredMixin, generic_views.View):\n\n def post(self, request, *args, **kwargs):\n slug = request.POST.get('slug')\n content = request.POST.get('content')\n\n content_block = get_object_or_404(models.ContentModel, slug=slug)\n content_block.content = content\n content_block.save()\n\n return utils.respond_with_json({'success': True})\n","sub_path":"tunobase/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"186153459","text":"import hashlib\nfilepath = 'data.txt'\n\n\nl = []\n\nwith open(filepath) as fp:\n line = fp.readline()\n while line:\n l.append(line.strip())\n line = fp.readline()\n\nnl = len(l)\n\nc = 0\n\nn = 0\n\nfor i in range(nl):\n tl = l[i]\n\n res = hashlib.md5((tl + str(n)).encode('utf-8')).hexdigest()\n\n while res[:6] != \"000000\":\n res = hashlib.md5((tl + str(n)).encode('utf-8')).hexdigest()\n n += 1\n\n print(\"md5: \", n-1)\n\n\nprint(\"answer: \", c)\n","sub_path":"4/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"6471065","text":"# Sissi Xu S3C2\nimport pickle\nclass CarRecord:\n def __init__(self):\n self.VehicleID=''\n self.Registration=''\n self.DateOfRegistration=None\n self.EngineSize=0\n self.PurchasePrice=0.00\n\nclass DataAndFile:\n def LimitingLength(x,n):\n try:\n x[n-1]\n x=x[:n]\n except:\n x=x.ljust(n,'/')\n return x\n def Hash(ID):\n return ((ord(ID[0])+ord(ID[1]))%20)*32+1\n def Access(ID):\n CarFile=open('Cars.DAT','rb')\n CarFile.seek(DataAndFile.Hash(ID))\n ThisCar=pickle.load(CarFile)\n print(ThisCar.VehicleID,ThisCar.Registration,ThisCar.DateOfRegistration,ThisCar.EngineSize,ThisCar.PurchasePrice)\n CarFile.close()\n \nclass main:\n def __init__(self,n=5):\n self.number=n\n self.run()\n def run(self):\n print('input data now')\n CarFile=open('Cars.DAT','rb+')\n for i in range(self.number):\n ThisCar=CarRecord()\n ThisCar.VehicleID=DataAndFile.LimitingLength(input(\"What's the vehicle ID?\"),8)\n ThisCar.Registration=DataAndFile.LimitingLength(input(\"What's the Registration?\"),8)\n ThisCar.DateOfRegistration=DataAndFile.LimitingLength(input(\"What's the date of registration?\"),8)\n ThisCar.EngineSize=DataAndFile.LimitingLength(input(\"What's the engine size?\"),8)\n ThisCar.PurchasePrice=DataAndFile.LimitingLength(input(\"What's the purchase price?\"),8)\n CarFile.seek(DataAndFile.Hash(ThisCar.VehicleID))\n pickle.dump(ThisCar,CarFile)\n CarFile.close()\n print('input over')\n target=input('find a record with the vehicle ID:')\n DataAndFile.Access(target)\n\nif __name__=='__main__':\n main(2)\n","sub_path":"Cha 26/26.02.py","file_name":"26.02.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"522242734","text":"import requests, json, time, _thread\nfrom time import sleep\nimport urllib\nimport hmac, hashlib\nfrom urllib.parse import urlparse, urlencode\nfrom urllib.request import Request, urlopen\nimport re\n\nclass Binance():\n\n methods = {\n # public methods\n 'ping': {'url':'api/v1/ping', 'method': 'GET', 'private': False},\n 'time': {'url':'api/v1/time', 'method': 'GET', 'private': False},\n 'exchangeInfo': {'url':'api/v1/exchangeInfo', 'method': 'GET', 'private': False},\n 'depth': {'url': 'api/v1/depth', 'method': 'GET', 'private': False},\n 'trades': {'url': 'api/v1/trades', 'method': 'GET', 'private': False},\n 'historicalTrades': {'url': 'api/v1/historicalTrades', 'method': 'GET', 'private': False},\n 'aggTrades': {'url': 'api/v1/aggTrades', 'method': 'GET', 'private': False},\n 'klines': {'url': 'api/v1/klines', 'method': 'GET', 'private': False},\n 'ticker24hr': {'url': 'api/v1/ticker/24hr', 'method': 'GET', 'private': False},\n 'tickerPrice': {'url': 'api/v3/ticker/price', 'method': 'GET', 'private': False},\n 'tickerBookTicker': {'url': 'api/v3/ticker/bookTicker', 'method': 'GET', 'private': False},\n # private methods\n 'createOrder': {'url': 'api/v3/order', 'method': 'POST', 'private': True},\n 'testOrder': {'url': 'api/v3/order/test', 'method': 'POST', 'private': True},\n 'orderInfo': {'url': 'api/v3/order', 'method': 'GET', 'private': True},\n 'cancelOrder': {'url': 'api/v3/order', 'method': 'DELETE', 'private': True},\n 'openOrders': {'url': 'api/v3/openOrders', 'method': 'GET', 'private': True},\n 'allOrders': {'url': 'api/v3/allOrders', 'method': 'GET', 'private': True},\n 'account': {'url': 'api/v3/account', 'method': 'GET', 'private': True},\n 'myTrades': {'url': 'api/v3/myTrades', 'method': 'GET', 'private': True},\n # wapi\n 'depositAddress': {'url': '/wapi/v3/depositAddress.html', 'method':'GET', 'private':True},\n 'withdraw': {'url': '/wapi/v3/withdraw.html', 'method':'POST', 'private':True},\n 'depositHistory': {'url': '/wapi/v3/depositHistory.html', 'method':'GET', 'private':True},\n 'withdrawHistory': {'url': '/wapi/v3/withdrawHistory.html', 'method':'GET', 'private':True},\n 'withdrawFee': {'url': '/wapi/v3/withdrawFee.html', 'method':'GET', 'private':True},\n 'accountStatus': {'url': '/wapi/v3/accountStatus.html', 'method':'GET', 'private':True},\n 'systemStatus': {'url': '/wapi/v3/systemStatus.html', 'method':'GET', 'private':True},\n }\n \n def __init__(self, API_KEY, API_SECRET):\n self.API_KEY = API_KEY\n self.API_SECRET = bytearray(API_SECRET, encoding='utf-8')\n self.shift_seconds = 0\n\n def __getattr__(self, name):\n def wrapper(*args, **kwargs):\n kwargs.update(command=name)\n return self.call_api(**kwargs)\n return wrapper\n \n def call_api(self, **kwargs):\n\n command = kwargs.pop('command')\n api_url = 'https://api.binance.com/' + self.methods[command]['url']\n\n payload = kwargs\n headers = {}\n \n payload_str = urllib.parse.urlencode(payload)\n if self.methods[command]['private']:\n payload.update({'timestamp': int(time.time() + self.shift_seconds - 1) * 1000})\n payload_str = urllib.parse.urlencode(payload).encode('utf-8')\n sign = hmac.new(\n key=self.API_SECRET,\n msg=payload_str,\n digestmod=hashlib.sha256\n ).hexdigest()\n\n payload_str = payload_str.decode(\"utf-8\") + \"&signature=\"+str(sign) \n headers = {\"X-MBX-APIKEY\": self.API_KEY}\n\n if self.methods[command]['method'] == 'GET':\n api_url += '?' + payload_str\n\n response = requests.request(method=self.methods[command]['method'], url=api_url, data=\"\" if self.methods[command]['method'] == 'GET' else payload_str, headers=headers)\n if 'code' in response.text:\n print(response.text)\n return response.json()\n\nclass Trader:\n\n\tdef __init__(self, api_key, api_secret, thread_limit, percent, coin, profit):\n\t\tself.client = Binance(API_KEY=api_key, API_SECRET=api_secret)\n\n\t\tself.exchange_info = {}\n\n\t\tfor symbol in self.client.exchangeInfo()['symbols']:\n\t\t\tself.exchange_info[symbol['symbol']] = symbol['filters']\n\n\t\tself.price_url = 'https://api.binance.com/api/v3/ticker/price?symbol='\n\t\tself.signals_url = \"https://scanner.tradingview.com/crypto/scan\"\n\t\tself.start_bank = float(self.client.account(recvWindow=600000)['balances'][0]['free'])\n\t\tself.bank = self.start_bank\n\t\tself.percent = percent\t\t\t\t# % of balance which will be used\n\t\tself.threads = 0\t\t\t\t\t# Number of trading threads\n\t\tself.thread_limit = thread_limit\t# Maximum threads\n\t\tself.start_time = time.time()\n\t\tself.coin = coin\t\t\t\t\t# Primary coin, example - BTC in GVT_BTC\n\t\tself.profit = profit \t\t\t\t# % of profit from every trade (example: 0.02 = 2%)\n\n\tdef update_balance(self):\n\t\tself.start_bank = float(self.client.account(recvWindow=600000)['balances'][0]['free'])\n\t\tself.bank = self.start_bank\n\n\tdef format_float(self, num, delimeter):\n\t\ttry:\n\t\t\treg = \"%.\" + str(delimeter) + \"f\"\n\t\t\treturn reg % float(num)\n\t\texcept:\n\t\t\treturn num\n\n\tdef trade_thread(self, signal):\n\t\ttry:\n\t\t\ttaken = self.start_bank * self.percent\n\t\t\tself.bank -= taken\n\t\t\tbuy_price = self.client.tickerPrice(symbol=signal['d'][0])['price']\n\n\t\t\tcount = taken / float(buy_price)\n\t\t\tcount -= count * 0.01\n\t\t\t\n\t\t\tdelimeter = len(self.exchange_info[signal['d'][0]][1]['stepSize'].split('.')[1].split('1')[0]) + 1\n\n\t\t\tif float(self.exchange_info[signal['d'][0]][1]['minQty']) > float(count):\n\t\t\t\tprint(\"Log: not enough money \" + str(self.exchange_info[signal['d'][0]][1]['minQty']) + \" \" + str(self.format_float(count, delimeter)))\n\t\t\t\tself.threads -= 1\n\t\t\t\tself.bank += taken\n\t\t\t\treturn\n\n\t\t\tif float(self.exchange_info[signal['d'][0]][1]['maxQty']) < count:\n\t\t\t\tcount = self.exchange_info[signal['d'][0]][1]['maxQty']\n\n\t\t\tif float(self.exchange_info[signal['d'][0]][2]['minNotional']) > float(buy_price) * float(count):\n\t\t\t\tprint(\"Low notional\")\n\t\t\t\tself.threads -= 1\n\t\t\t\tself.bank += taken\n\t\t\t\treturn\n\n\t\t\tcount = self.format_float(count, delimeter)\n\n\t\t\tbuy_order_id = self.client.createOrder(\n\t\t\t symbol=signal['d'][0],\n\t\t\t recvWindow=600000,\n\t\t\t side='BUY',\n\t\t\t type='LIMIT',\n\t\t\t quantity=count,\n\t\t\t price=buy_price,\n\t\t\t newOrderRespType='RESULT',\n\t\t\t timeInForce='GTC',\n\t\t\t)\n\t\t\tprint(buy_order_id)\n\t\t\tcount = float(count) - float(count) * 0.001\n\t\t\tcount = self.format_float(count, delimeter)\n\n\t\t\ttry:\n\t\t\t\tbuy_price = buy_order_id['price']\n\t\t\t\tbuy_order_id = buy_order_id['orderId']\n\t\t\texcept:\n\t\t\t\tprint(\"Log: error on buying\")\n\t\t\t\tself.threads -= 1\n\t\t\t\treturn\n\t\t\t\t\n\t\t\tsleep(1)\n\n\t\t\ti = 0\n\t\t\tbuy_order_info = self.client.orderInfo(orderId=buy_order_id, symbol=signal['d'][0], recvWindow=6000000)\n\t\t\twhile float(buy_order_info['origQty']) != float(buy_order_info['executedQty']):\n\t\t\t\tsleep(10)\n\t\t\t\tbuy_order_info = self.client.orderInfo(orderId=buy_order_id, symbol=signal['d'][0], recvWindow=6000000)\n\t\t\t\ti += 1\n\t\t\t\tif i >= 5:\n\t\t\t\t\tif float(buy_order_info['executedQty']) > 0:\n\t\t\t\t\t\tcount = self.format_float(buy_order_info['executedQty'], delimeter)\n\t\t\t\t\t\tself.bank += taken - float(buy_order_info['executedQty']) * float(buy_order_info['price'])\n\t\t\t\t\t\ttaken -= float(buy_order_info['executedQty']) * float(buy_order_info['price'])\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"Cancelling order...\")\n\t\t\t\t\t\tself.client.cancelOrder(orderId=buy_order_id, symbol=signal['d'][0], recvWindow=6000000)\n\t\t\t\t\t\tself.threads -= 1\n\t\t\t\t\t\tself.bank += taken\n\t\t\t\t\t\treturn\n\t\t\t\n\t\t\tprint(\"Bought \" + signal['d'][0] + \" at \" + str(buy_price) + \". Qty: \" + str(taken / float(buy_price)))\n\t\t\tfor i in self.client.account()['balances']:\n\t\t\t\tif i['asset'] == signal['d'][0].split('BTC')[0]:\n\t\t\t\t\tcount = float(i['free']) - float(i['free']) * 0.0075\n\t\t\tif self.exchange_info[signal['d'][0]][0]['tickSize'].split('.')[0] == '1':\n\t\t\t\tdelim = 0\n\t\t\telse:\n\t\t\t\tdelim = len(self.exchange_info[signal['d'][0]][0]['tickSize'].split('.')[1].split('1')[0]) + 1\n\n\t\t\tsell_price = self.format_float(float(buy_price) + float(buy_price) * self.profit, delim)\n\n\t\t\tplus = ((float(sell_price) - float(buy_price)) * 100.0 / float(buy_price)) * taken\n\t\t\tsell_order_info = ''\n\t\t\tcount = self.format_float(count, delimeter)\n\t\t\ttry:\n\t\t\t\tsell_order_id = self.client.createOrder(\n\t\t\t\t symbol=signal['d'][0],\n\t\t\t\t recvWindow=600000,\n\t\t\t\t side='SELL',\n\t\t\t\t\ttype='LIMIT',\n\t\t\t\t quantity=count,\n\t\t\t\t price=sell_price,\n\t\t\t\t timeInForce='GTC',\n\t\t\t\t newOrderRespType='RESULT',\n\t\t\t\t)\n\t\t\t\tprint(sell_order_id)\n\t\t\t\tsell_order_id = sell_order_id['orderId']\n\t\t\texcept Exception as e:\n\t\t\t\tprint(count)\n\t\t\t\tprint(sell_price)\n\t\t\t\tprint(e)\n\n\t\t\tsell_order_info = self.client.orderInfo(orderId=sell_order_id, symbol=signal['d'][0], recvWindow=6000000)\n\t\t\twhile float(sell_order_info['origQty']) != float(sell_order_info['executedQty']):\n\t\t\t\ttry:\n\t\t\t\t\tsleep(10)\n\t\t\t\t\tsell_order_info = self.client.orderInfo(orderId=sell_order_id, symbol=signal['d'][0], recvWindow=6000000)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\t\tprint(\"Sold \" + signal['d'][0] + \" at \" + sell_price)\n\t\t\tprint(\"-----------------------\")\n\n\t\t\tprint(\"Current bank: \" + str(self.bank) + \"\\nStart bank: \" + str(self.start_bank) + \"\\nTime passed: %s minutes\" % ((time.time() - self.start_time) / 60))\n\t\t\tprint(\"-----------------------\")\n\t\t\tself.threads -= 1\n\t\t\treturn\n\t\texcept Exception as e:\n\t\t\tself.threads -= 1\n\t\t\tprint(e)\n\t\t\treturn\n\n\tdef start_trading(self):\n\t\twhile True:\n\t\t\tsleep(1)\n\t\t\tif self.threads < self.thread_limit:\n\t\t\t\ttry:\n\t\t\t\t\traw_signals = requests.post(self.signals_url, data=json.dumps({\"filter\":[{\"left\":\"name\",\"operation\":\"nempty\"},{\"left\":\"exchange\",\"operation\":\"equal\",\"right\":\"BINANCE\"},{\"left\":\"total_shares_diluted\",\"operation\":\"egreater\",\"right\":1000000},{\"left\":\"Recommend.All|60\",\"operation\":\"nequal\",\"right\":0.5},{\"left\":\"Recommend.All|60\",\"operation\":\"in_range\",\"right\":[0.5,1]}],\"symbols\":{\"query\":{\"types\":[]},\"tickers\":[]},\"columns\":[\"name\",\"close|60\",\"change|60\",\"change_abs|60\",\"high|60\",\"low|60\",\"volume|60\",\"Recommend.All|60\",\"exchange\",\"description\",\"name\",\"subtype\",\"pricescale\",\"minmov\",\"fractional\",\"minmove2\"],\"sort\":{\"sortBy\":\"name\",\"sortOrder\":\"asc\"},\"options\":{\"lang\":\"ru\"},\"range\":[0,150]})).text\n\t\t\t\t\tjson_signals = json.loads(raw_signals)['data']\n\t\t\t\t\tfor signal in json_signals:\n\t\t\t\t\t\tif signal['s'].split(':')[1][-3::] == self.coin and self.threads < self.thread_limit and self.exchange_info[signal['d'][0]][1]['stepSize'].split('.')[0] != '1':\n\t\t\t\t\t\t\tself.update_balance()\n\t\t\t\t\t\t\t_thread.start_new_thread(self.trade_thread, (signal,))\n\t\t\t\t\t\t\tself.threads += 1\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(e)\n\t\t\t\n\t\t\t\t\t\n\napi_key = 'API'\napi_secret = 'SECRET'\n\ntrader = Trader(api_key, api_secret, 1, 1, \"BTC\", 0.015)\ntrader.start_trading()\n","sub_path":"Trade Bot.py","file_name":"Trade Bot.py","file_ext":"py","file_size_in_byte":11145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"431558897","text":"# -*- encoding: utf-8 -*-\n\"\"\"\npip install pymongo\n\"\"\"\nfrom pymongo import MongoClient #mongodb 모듈 지정\nimport datetime\nimport pprint\nimport json\nimport os\nimport sys\nfrom bson.objectid import ObjectId #objectid 모듈 지정\nimport requests\nimport json\n\ndef send(text, title):\n requests.post('https://meeting.ssafy.com/hooks/xjyuws5ywtratrtu8e8qx57k7c', \n data=json.dumps({\"attachments\": [{\n \"color\": \"#FF8000\",\n \"text\": str(text),\n \"author_name\": \"data\",\n \"author_icon\": \"http://www.mattermost.org/wp-content/uploads/2016/04/icon_WS.png\",\n \"title\": str(title),\n }]}),\n headers={'Content-Type': 'application/json'}\n )\nsys.stdout.reconfigure(encoding='utf-8')\ndef open_json(name):\n with open('./%s.json'%name,'r', -1, \"utf-8\") as f:\n dt=json.load(f)\n return dt\n\ndef open_file(name):\n with open(name, 'r', -1, \"utf-8\") as f:\n dt=json.load(f)\n return dt\n\ndef save_json(name,dt):\n with open('./%s.json'%name,'w', -1, \"utf-8\") as f:\n json.dump(dt,f)\n\n#mongodb 연결객체 생성\n# client = MongoClient()\n# client = MongoClient('localhost', '27017') #접속IP, 포트\n#client = MongoClient('mongodb://root:sSLe2f46tf3EeLo3Eo9tj94cmEcVvERf3D3bBgVfcs@j3b302.p.ssafy.io:8022/admin')\nclient = MongoClient('mongodb://localhost:27017')\n#데이터베이스 개체 가져오기\n# db = client['------']\ndb = client.spotify\n#컬렉션 개체 가져오기\n\n\"\"\"\n#아티스트 추가\nartistsCol = db.artists\n\nkpopArtists = open_json(\"data/artists/k-pop_artists_info\")\nfor artist in kpopArtists:\n check = False\n for t in artist['genres']:\n if \"k-pop\" in t or \"korean\" in t:\n check = True\n break\n if not check:\n continue\n artistsCol.insert_one(artist)\n\n#현재 aws에 아티스트만 추가함\n\"\"\"\n\n\"\"\"\n#앨범 추가\nalbumsCol = db.albums\nkpopAlbums = open_json(\"data/albums/k-pop_albums\")\nfor albums in kpopAlbums:\n for album in kpopAlbums[albums]:\n albumsCol.insert_one(album)\n #print(album['name'])\n\"\"\"\n\n\"\"\"\n#앨범 데이터 정제 for django\nalbumsCol = db.albums\nDalbumsCol = db.music_albums\nals = albumsCol.find(no_cursor_timeout = True)\nfor album in als:\n temp = {}\n \n if DalbumsCol.count_documents({'id' : album['id']}) != 0:\n continue\n temp['id'] = album['id']\n temp['album_type'] = album['album_type']\n temp['name'] = album['name']\n temp['release_date'] = album['release_date']\n temp['release_date_precision'] = album['release_date_precision']\n temp['total_tracks'] = album['total_tracks']\n temp['images'] = album['images']\n ate = []\n for ar in album['artists']:\n te = {}\n te['id'] = ar['id']\n te['name'] = ar['name']\n ate.append(te)\n temp['artists'] = ate\n try:\n temp['tracks'] = album['tracks']\n except:\n temp['tracks'] = []\n print(album['id'])\n \n DalbumsCol.insert_one(temp)\nals.close()\n\"\"\"\n#db.users.count_documents({\"email\": email}) != 0:\n\n\"\"\"\n#트랙 추가\ntracksCol = db.tracks\nalbumsCol = db.albums\ndir_l=os.listdir(u'./data/tracks/')\nfor artist in dir_l:\n albums = open_file('./data/tracks/' + artist)\n for album in albums['albums']:\n tracks = []\n for track in albums['albums'][album]:\n tracks.append({'id' : track['id']})\n if tracksCol.count_documents({'id' : track['id']}) > 0:\n continue\n temp = {}\n temp['id'] = track['id']\n temp['artists'] = track['artists']\n temp['duration_ms'] = track['duration_ms']\n temp['external_urls'] = track['external_urls']\n temp['name'] = track['name']\n temp['preview_url'] = track['preview_url']\n temp['track_number'] = track['track_number']\n temp['album_id'] = album\n tracksCol.insert_one(temp)\n albumsCol.update_many({'id': album}, {'$set': {'tracks': tracks}})\n\"\"\"\n\n\"\"\"\n#tarcks 복제\nnts = db.ntracks\nts = db.tracks\ntts = ts.find(no_cursor_timeout = True)\n\nfor t in tts:\n nts.insert_one(t)\ntts.close()\n\"\"\"\n\n\n\"\"\"\n#아티스트 데이터 정제 for django\nartistsCol = db.artists\nDartistsCol = db.music_artists\nars = artistsCol.find(no_cursor_timeout = True)\nfor artist in ars:\n if DartistsCol.count_documents({'id' : artist['id']}) != 0:\n continue\n temp = {}\n temp['id'] = artist['id']\n temp['followers'] = artist['followers']['total']\n temp['name'] = artist['name']\n temp['popularity'] = artist['popularity']\n li = []\n for gen in artist['genres']:\n te={}\n te['genre'] = gen\n li.append(te)\n temp['genres'] = li\n temp['images'] = artist['images']\n DartistsCol.insert_one(temp)\nars.close()\n\"\"\"\n\n\n\"\"\"\n#트랙 데이터 정제\ntracksCol = db.tracks\nDtracksCol = db.music_tracks\nfor i in range(0, 109):\n ts = tracksCol.find(no_cursor_timeout = True).skip(i*1000).limit(1000)\n for track in ts:\n if DtracksCol.count_documents({'id' : track['id']}) >= 1:\n continue\n temp = {}\n temp['id'] = track['id']\n ate = []\n for ar in track['artists']:\n te = {}\n te['id'] = ar['id']\n te['name'] = ar['name']\n ate.append(te)\n temp['artists'] = ate\n you = None\n mr = None\n for ex in track['external_urls']:\n try:\n you = ex['youtube']\n except:\n pass\n try:\n mr = ex['youtube_mr']\n except:\n pass\n temp['youtube_urls'] = you\n temp['youtube_mr'] = mr\n temp['name'] = track['name']\n temp['duration_ms'] = track['duration_ms']\n temp['track_number'] = track['track_number']\n temp['preview_url'] = track['preview_url']\n try:\n temp['popularity'] = track['popularity']\n except:\n temp['popularity'] = None\n try:\n temp['album_id'] = track['album_id']\n except:\n temp['album_id'] = None\n #album_id = models.CharField(max_length=200)\n DtracksCol.insert_one(temp)\n ts.close()\n send(i, 'music_track')\nsend('done', 'music_track')\n\"\"\"\n\ntracksCol = db.tracks\nDtracksCol = db.music_tracks\nfor i in range(0, 109):\n ts = tracksCol.find(no_cursor_timeout = True).skip(i*1000).limit(1000)\n for track in ts:\n mr = None\n for ex in track['external_urls']:\n try:\n mr = ex['youtube_mr']\n except:\n pass\n DtracksCol.update_one({'id': track['id']}, {'$set': {'youtube_mr': mr}})\n ts.close()\n\n\"\"\"\ntracksCol = db.tracks\nidx = 0\nfor track in tracksCol.find().skip(2*1000).limit(1000):\n print(track['external_urls'])\n idx += 1\n print(idx)\n\"\"\"\n\n\"\"\"\nidx = 0\ntracksCol = db.tracks\nDtracksCol = db.music_tracks\nts = tracksCol.find(no_cursor_timeout = True)\nfor track in ts:\n if 'album_id' in DtracksCol.find_one({'id': track['id']}):\n continue\n #print(idx)\n #print(track)\n #print(track['album_id'])\n DtracksCol.update_many({'id': track['id']}, {'$set': {'album_id': track['album_id']}})\n idx+=1\nts.close()\n\"\"\"\n\n\"\"\"\ntrackCol = db.tracks_af_clustered\nDtracksCol = db.music_tracks\nfor i in range(0, 109):\n dts = trackCol.find(no_cursor_timeout = True).skip(i*1000).limit(1000)\n idx = 0\n for track in dts:\n #if 'cluster' in DtracksCol.find_one({'id': track['id']}):\n # continue\n try:\n DtracksCol.update_many({'id': track['id']}, {'$set': {'cluster': track['cluster']}})\n except Exception as e:\n print(idx)\n print(track['id'])\n print(e)\n idx+= idx\n dts.close()\n if i%10 == 0:\n send(i, 'tracks_af_clustered')\nsend('done', 'tracks_af_clustered')\n\"\"\"\n\n\"\"\"\ntracksCol = db.ntracks\nDtracksCol = db.music_tracks\nfor i in range(0, 405):\n ts = tracksCol.find(no_cursor_timeout = True).skip(i*1000).limit(1000)\n for track in ts:\n mr = None\n for ex in track['external_urls']:\n try:\n mr = ex['youtube_mr']\n except:\n pass\n DtracksCol.update_many({'id': track['id']}, {'$set': {'youtube_mr': mr}})\n ts.close()\n send(i, 'music_track')\nsend('done', 'music_track')\n\"\"\"\n\n\"\"\"\nidx=0\nalbumsCol = db.albums\nDalbumsCol = db.music_albums\nals = albumsCol.find(no_cursor_timeout = True)\nfor album in als:\n if 'tracks' in DalbumsCol.find_one({'id': album['id']}):\n continue\n try:\n trs = []\n for tr in album['tracks']:\n trs.append({'id':tr})\n DalbumsCol.update_many({'id': album['id']}, {'$set': {'tracks': trs}})\n except Exception as e:\n print(idx)\n print(album['id'])\n print(e)\n idx+= idx\nals.close()\n\"\"\"\n\n\"\"\"\nacuser = db.accounts_user\nusers = acuser.find()\nfor user in users:\n acuser.update_many({'userid': user['userid']}, {'$set': {'pi_re_songs': []}})\n\"\"\"\n\n\n\"\"\"\nDartistsCol = db.music_artists\nDalbumsCol = db.music_albums\nDtrackCol = db.music_tracks\n\nfor i in range(0, 24):\n ats = DartistsCol.find({'$nor' : [{'genres': {'$elemMatch' : { 'genre' : {'$regex' : '^korean', '$options':'i'} }}}, {'genres': {'$elemMatch' : { 'genre' : {'$regex' : '^k-pop', '$options':'i'} }}}]}, no_cursor_timeout = True).limit(10)\n li = []\n for a in ats:\n als = DalbumsCol.find({'artists':{'$elemMatch': {'id' : a['id']}}})\n for album in als:\n for track in album['tracks']:\n DtrackCol.delete_many({'id' : track['id']})\n DalbumsCol.delete_many({'id' : album['id']})\n DartistsCol.delete_many({'id' : a['id']})\n ats.close()\n\"\"\"\n\n\"\"\"\nDafCol = db.tracks_af_clustered\nDtrackCol = db.music_tracks\n\nfor i in range(0, 398):\n afs = DafCol.find().skip(i*1000).limit(1000)\n for a in afs:\n track = DtrackCol.find_one({'id':a['id']})\n if track == None:\n DafCol.delete_many({'id':a['id']})\n\n\"\"\"\n\n\"\"\"\nDartistsCol = db.music_artists\nDtrackCol = db.music_tracks\nDalbumsCol = db.music_albums\nDafCol = db.tracks_af_clustered\n\nfor i in range(0, 395):\n tracks = DtrackCol.find().skip(i*1000).limit(1000)\n for track in tracks:\n temp = []\n\n for artist in track['artists']:\n temp.append({'id': artist['id']})\n if DartistsCol.count_documents({'$or': temp}) == 0:\n DalbumsCol.delete_many({'id' : track['album_id']})\n DtrackCol.delete_many({'id' : track['id']})\n DafCol.delete_many({'id' : track['id']})\n tracks.close()\n\"\"\"\n\n\n\"\"\"\nDartistsCol = db.music_artists\nDtrackCol = db.music_tracks\nDalbumsCol = db.music_albums\nalbumsCol = db.albums\nartistsCol = db.artists\n\nidx = 0\nfor i in range(0, 395):\n tracks = DtrackCol.find().skip(i*1000).limit(1000)\n for track in tracks:\n if DalbumsCol.count_documents({'id': track['album_id']}) == 0:\n album = albumsCol.find_one({'id': track['album_id']})\n if album is not None:\n temp = {}\n temp['id'] = album['id']\n temp['album_type'] = album['album_type']\n temp['name'] = album['name']\n temp['release_date'] = album['release_date']\n temp['release_date_precision'] = album['release_date_precision']\n temp['total_tracks'] = album['total_tracks']\n temp['images'] = album['images']\n ate = []\n for ar in album['artists']:\n te = {}\n te['id'] = ar['id']\n te['name'] = ar['name']\n ate.append(te)\n temp['artists'] = ate\n trs = []\n for tr in album['tracks']:\n trs.append({'id':tr})\n DalbumsCol.insert_one(temp)\n for artist in track['artists']:\n if DartistsCol.count_documents({'id': artist['id']}) == 0:\n artist = artistsCol.find_one({'id': artist['id']})\n if artist is not None:\n temp = {}\n temp['id'] = artist['id']\n temp['followers'] = artist['followers']['total']\n temp['name'] = artist['name']\n temp['popularity'] = artist['popularity']\n li = []\n for gen in artist['genres']:\n te={}\n te['genre'] = gen\n li.append(te)\n temp['genres'] = li\n temp['images'] = artist['images']\n DartistsCol.insert_one(temp)\n idx+=1\n if idx%10 == 0:\n send(i, idx)\nsend('done', 'done') \n\n\"\"\"\n\n\"\"\"\nuserdb = db.accounts_user\nDtrackCol = db.music_tracks\n\nusers = userdb.find()\n\nfor user in users:\n sang_songs = []\n for songs in user['sang_songs']:\n if DtrackCol.count_documents({'id': songs['songid']}) >= 1:\n sang_songs.append(songs)\n userdb.update_one({'userid': user['userid']}, {'$set': {'sang_songs': sang_songs}})\n\n re_songs = []\n for songs in user['re_songs']:\n if DtrackCol.count_documents({'id': songs['songid']}) >= 1:\n re_songs.append(songs)\n userdb.update_one({'userid': user['userid']}, {'$set': {'re_songs': re_songs}})\n\n pi_re_songs = []\n for songs in user['pi_re_songs']:\n if DtrackCol.count_documents({'id': songs['songid']}) >= 1:\n pi_re_songs.append(songs)\n userdb.update_one({'userid': user['userid']}, {'$set': {'pi_re_songs': pi_re_songs}})\n\"\"\"\n\n\n#같은노래 external_url 같은거면 하나는 지우기\n\n#제목에 못들어가는거 있으면 잘라내기\n#k = re.sub('\\*|\\\\|:|\\?|\"|<|>|\\|', '', k)\n\n\n#컬렉션 확인하기\n#print(db.collection_names())\n\n\n#데이터 삭제하기\n# result = posts.delete_one() #조건과 일치하는 데이터중 하나만 삭제\n# result = posts.delete_many() #조건과 일치하는 데이터 모두 삭제\n# result = posts.delete_many({}) #모두 삭제 (조건지정x)\n\n\n#접속 해제\nclient.close()","sub_path":"backend/mongoDB.py","file_name":"mongoDB.py","file_ext":"py","file_size_in_byte":14084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"346980601","text":"\nfrom ensemble import Ensemble\nfrom connection import Connection\nfrom probe import Probe\nfrom input import Input\nfrom neurons import LIFNeuronModel\n\nclass Network(object):\n def __init__(self, name):\n\n self.name = name\n self.Connections = []\n self.Ensembles = []\n self.Networks = []\n self.Nodes = []\n self.Probes = []\n\n self.reset()\n\n def connect(self, pre, post, function=None, transform=None, scale=None,\n filter=0.005, learning_rule=None):\n\n connection = Connection(pre, post, neuron_space=False,\n function=function, transform=transform,\n scale=scale,\n filter=filter, learning_rule=learning_rule)\n self.Connections.append(connection)\n return connection\n\n def connect_neurons(self, pre, post, weights=None, scale=None,\n filter=0.005, learning_rule=None):\n\n connection = Connection(pre, post, neuron_space=True,\n weights=weights, scale=scale,\n filter=filter, learning_rule=learning_rule)\n self.Connections.append(connection)\n return connection\n\n def make_ensemble(self, name, neurons, dimensions=1,\n max_rate=(50,100), intercept=(-1,1), radius=1.0,\n encoders=None, neuron_model=dict(type=LIFNeuronModel,\n tau_ref=0.002, tau_rc=0.02), mode='spiking'):\n\n ensemble = Ensemble(name, neurons, dimensions,\n max_rate=max_rate, intercept=intercept, radius=radius,\n encoders=encoders, neuron_model=neuron_model,\n mode=mode)\n\n self.Ensembles.append(ensemble)\n return ensemble\n\n def make_input(self, name, value):\n input = Input(name, value)\n self.Nodes.append(input)\n return input\n\n def make_probe(self, name, dimensions, dt=0.01):\n probe = Probe(name, dimensions, dt=dt)\n self.Probes.append(probe)\n return probe\n\n @property\n def all_ensembles(self):\n ensembles = list(self.Ensembles)\n for network in self.Networks:\n ensembles.extend(network.all_ensembles)\n return ensembles\n\n @property\n def all_connections(self):\n connections = list(self.Connections)\n for network in self.Networks:\n connections.extend(network.all_connections)\n return connections\n\n @property\n def all_probes(self):\n probes = list(self.Probes)\n for network in self.Networks:\n probes.extend(network.all_probes)\n return probes\n\n @property\n def objects(self):\n return self.Connections + self.Ensembles + self.Networks + \\\n self.Nodes + self.Probes\n\n def build(self, dtype):\n for network in self.Networks:\n network.build(dtype)\n\n for node in self.Nodes:\n node.build(dtype)\n\n for probe in self.Probes:\n probe.build(dtype)\n\n def reset(self):\n for obj in self.objects:\n obj.reset()\n\n def run(self, t_end):\n for network in self.Networks:\n network.run(t_end)\n\n for node in self.Nodes:\n node.run(t_end)\n\n for probe in self.Probes:\n probe.run(t_end)\n\n def tick(self, dt):\n for network in self.Networks:\n network.tick(dt)\n\n for ensemble in self.Ensembles:\n ensemble.tick(dt)\n\n # for node in self.Nodes:\n # node.tick(dt)\n\n for probe in self.Probes:\n probe.tick(dt)\n","sub_path":"nengo_theano/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"75473110","text":"# # 6/11/2020\n# Often, GridSearchCV can be really time consuming, so in practice, you may want to use RandomizedSearchCV instead, as you will do in this exercise. The good news is you only have to make a few modifications to your GridSearchCV code to do RandomizedSearchCV. The key difference is you have to specify a param_distributions parameter instead of a param_grid parameter.\n\n# Create the parameter grid: gbm_param_grid \ngbm_param_grid = {\n 'n_estimators': [25],\n 'max_depth': range(2, 12)\n}\n\n# Instantiate the regressor: gbm\ngbm = xgb.XGBRegressor(n_estimators=10)\n\n# Perform random search: grid_mse\nrandomized_mse = RandomizedSearchCV(estimator = gbm, param_distributions = gbm_param_grid,\n scoring = \"neg_mean_squared_error\", n_iter = 5, cv = 4, verbose = 1)\n\n\n# Fit randomized_mse to the data\nrandomized_mse.fit(X, y)\n\n# Print the best parameters and lowest RMSE\nprint(\"Best parameters found: \", randomized_mse.best_params_)\nprint(\"Lowest RMSE found: \", np.sqrt(np.abs(randomized_mse.best_score_)))\n\n# Best parameters found: {'n_estimators': 25, 'max_depth': 6}\n# Lowest RMSE found: 36909.98213965752","sub_path":"Extreme Gradient Boosting with XGBoost/3 Fine-tuning Your XGBoost Model/07_Random_Search_with_XGBoost.py","file_name":"07_Random_Search_with_XGBoost.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"23611999","text":"import math\n\nres = []\n\nfor i in range(100000):\n digits = [int(j) for j in list(str(i))]\n s = sum(math.factorial(d) for d in digits)\n if s==i:\n res.append(i)\n print(i)\n","sub_path":"Python/034.py","file_name":"034.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"144135703","text":"# 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 \n# \n# \n# \n# 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Mar\n# cos 贡献此图。 \n# \n# 示例: \n# \n# 输入: [0,1,0,2,1,0,1,3,2,1,2,1]\n# 输出: 6 \n# Related Topics 栈 数组 双指针\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def trap(self, height: List[int]) -> int:\n stack,area = [],0\n for i in range(len(height)):\n while stack and height[stack[-1]] < height[i]:\n n = stack.pop()\n if not stack:\n break\n area += (min(height[i],height[stack[-1]])-height[n])*(i-stack[-1]-1)\n stack.append(i)\n return area\n\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_01/trapping-rain-water.py","file_name":"trapping-rain-water.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"568924555","text":"# Date: 4/13/2020\n# Purpose: Create monthly QC plots on many variables for meteorological data-collection stations\n\n# (MJW) This is edited from Dr. Kimball's original script. I did not include all comments from the original.\n# This is designed for Python 2.7.5 with numpy 1.7 and matplotlib 1.2.0\n# It is also tested with Python 2.7.17 with numpy 1.16.5 and matplotlib 2.2.3 as well as Python 3.7.6 with numpy 1.18.1 and matplotlib 3.1.3\n# Some comments may still be in Python 3 syntax (e.g., print functions) or for more up-to-date versions of modules (e.g., matplotlib legend alphas, numpy.full())\n\n# This version of the script, in comparison to monthly_QCSingleMonths.py is significantly faster but uses much more RAM. On the development server it completed in around\n# 60-70 minutes but used over 1 GB of memory.\n\n# time used solely for execution-time metrics\nimport time\nentire_time = time.time()\n\n# Used just for testing. Would need to split code into functions/modules\n#import cProfile\n\n# The following import and .use are required on display-less server\n#import matplotlib # Needs to be installed\n#matplotlib.use('Agg')\n\nimport os\nfrom datetime import datetime\nimport mysql.connector # Needs to be installed\nimport matplotlib.pyplot as plt # Needs to be installed\nimport numpy as np # Needs to be installed\n\n# Base directory for plot PNG file output. Currently uses the directory where this script is housed.\n# Must be in the format '/your/file/directory'\n# User running the script must have permission to create folders, as a directory tree will be created to house the images if it does not exist.\n# Directory tree will be '/QCplots///'\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n#print(dir_path)\n\n# MySQL connection parameters\nconfig = {\n 'user': 'chilistudent',\n 'password': 'chilistudent',\n 'host': 'localhost',\n 'port': '3306',\n 'database': 'chili',\n 'raise_on_warnings': True\n}\n\n# Create connection and cursor that can accept parameters\ncnx = mysql.connector.connect(**config)\ncursor = cnx.cursor(prepared = True)\n\n# Query for QC metrics.\nquery = (\"SELECT \"\n \"YEAR(TS), \"\n \"MONTH(TS), \"\n \"DAY(TS), \"\n \"HOUR(TS), \"\n \"MINUTE(TS), \"\n \"AirT_2m, \"\n \"AirT_1pt5m, \"\n \"AirT_10m, \"\n \"AirT_9pt5m, \"\n \"RH_2m, \"\n \"RH_10m, \"\n \"Precip_TB3_Tot, \"\n \"Precip_TX_Tot, \" \n \"WndSpd_10m_WVc_2, \"\n \"WndSpd_2m_WVc_2, \"\n \"WndSpd_10m_WVc_3, \"\n \"WndSpd_2m_WVc_3, \"\n \"Pressure_1, \"\n \"Pressure_2, \"\n \"TotalRadn, \"\n \"QuantRadn, \"\n \"Temp_C, \" # Hydroprobe\n \"SoilT_100cm, \" # Thermocouple\n \"SoilSfcT, \"\n \"SoilT_5cm, \"\n \"SoilT_10cm, \"\n \"SoilT_5cm, \"\n \"SoilT_50cm, \"\n \"SoilT_20cm, \"\n \"WndSpd_Vert, \" \n \"WndSpd_10m_WVc_4, \"\n \"Batt, \"\n \"ObsInSumm_Tot, \"\n \"Door, \"\n \"PTemp \"\n \"FROM chili.station_data \"\n \"INNER JOIN chili.station ON chili.station.id = chili.station_data.StationID \"\n \"WHERE DATE(TS) BETWEEN %s AND LAST_DAY(%s) \"\n \"AND StationKey = %s \"\n \"ORDER BY TS;\"\n )\n\n# Primary stations. The names correspond to the chili.station table StationKey field. Each station has a matching buddy in buddyList at the same index.\nstationList = ['ashford', 'geneva', 'kinston', 'florala', 'andalusia', 'dixie', 'castleberry', 'jay', 'atmore', \n 'poarch', 'mtvernon', 'leakesville', 'agricola', 'mobileusaw', 'mobiledr', 'grandbay', 'pascagoula', \n 'gasque', 'foley', 'elberta', 'fairhope', 'robertsdale', 'loxley', 'bayminette', 'saraland']\n\n# Buddy stations. The names correspond to the chili.station table StationKey field\nbuddyList = ['geneva', 'kinston', 'florala', 'andalusia', 'dixie', 'castleberry', 'jay', 'atmore', \n 'poarch', 'mtvernon', 'leakesville', 'agricola', 'mobileusaw', 'mobiledr', 'grandbay', 'pascagoula', \n 'gasque', 'foley', 'elberta', 'fairhope', 'robertsdale', 'loxley', 'bayminette', 'saraland', 'mobileusaw']\n\n# Could also define in terms of endMonth and not have to call datetime.today()\ndef getTimeFrame():\n # Get the last plot month, derived from time of script execution.\n if datetime.today().month == 1:\n endMonth = 12\n startYear = str(datetime.today().year - 1)\n else:\n endMonth = datetime.today().month - 1\n if 1 < datetime.today().month < 7:\n startYear = str(datetime.today().year - 1)\n\n # Get starting month\n if endMonth > 6:\n startMonth = endMonth - 6\n else:\n startMonth = endMonth + 7\n\n # Get year for query range. This is not the same as plotyear, which is for individual months\n if 1 < datetime.today().month < 7:\n startYear = str(datetime.today().year - 1)\n else:\n startYear = str(datetime.today().year)\n\n endYear = str(datetime.today().year)\n\n return startMonth, endMonth, startYear, endYear\n\n# Queries station data, convert to list, replace Nones with 'nan's, returns list transformed by seperateByMonth function\ndef getData(prevResult, dateStart, dateEnd, cursor, MonthNums, StationNames):\n for s in range(2):\n if s == 0 and len(prevResult[1]) > 0:\n result[s] = prevResult[1]\n print('\\nUsing cached previous query for %s' % (StationNames[s]) )\n continue\n\n start_time = time.time()\n params = (dateStart, dateEnd, StationNames[s]) # params must be a tuple\n cursor.execute(query, params)\n #print(cursor.statement)\n\n # Only fetch if rows were returned. Rows may still contain NULL data.\n if cursor.with_rows:\n #print(True)\n result[s] = cursor.fetchall()\n #print(result)\n\n elapsed_time = time.time() - start_time\n print('Query execution time for station = ' + StationNames[s] + ': ' + str(elapsed_time))\n\n # Convert rows to lists.\n for row in range(len(result[s])):\n result[s][row] = list(result[s][row]) # Test if np.asrray works. Might need to be list\n\n # Replace NULLs, None, etc., with 'nan'.\n for i in range(len(result[s])):\n for j in range(len(result[s][i])):\n if result[s][i][j] in ('', 'NAN', '\"NAN\"', 'NULL', 'None') or result[s][i][j] is None:\n result[s][i][j] = 'nan' # s = station, i = record, j = field value\n\n result[s] = separateByMonth(result[s], MonthNums) # Test this to make sure it gives the same result as the tmp method\n #tmp = separateByMonth(result[s], MonthNums)\n #result[s] = tmp\n #print(len(result[s][0]))\n #if len(result[s]) > 0:\n # print(result)\n return result\n\n# Separate query data by month. \n# Becomes a list of months. Each month has a list of records. Each record has a list of field values.\ndef separateByMonth(data, MonthNums):\n ByMonth = [[] for x in range(6)]\n #print(ByMonth)\n #print(data)\n for record in data:\n #print(MonthNums)\n #print(record[1])\n #print(MonthNums[0])\n if record[1] == MonthNums[0]:\n ByMonth[0].append(record)\n elif record[1] == MonthNums[1]:\n ByMonth[1].append(record)\n elif record[1] == MonthNums[2]:\n ByMonth[2].append(record)\n elif record[1] == MonthNums[3]:\n ByMonth[3].append(record)\n elif record[1] == MonthNums[4]:\n ByMonth[4].append(record)\n elif record[1] == MonthNums[5]:\n ByMonth[5].append(record)\n #if len(ByMonth[0]) > 0:\n # print(ByMonth[0][0])\n return np.asarray(ByMonth) \n\n# Variables used for the time frame.\nstartMonth, endMonth, startYear, endYear = getTimeFrame()\n\n# Format dates to use in query\ndateStart = startYear + '-' + '{:02d}'.format(startMonth) + '-' + '01'\ndateEnd = endYear + '-' + '{:02d}'.format(endMonth) + '-' + '01' \n#dateStart = '2019-02-01'\n#dateEnd = '2020-08-01'\n#print(dateStart, dateEnd) \n\n# Calendar\nMonthName = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nDaysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\nLeapYears = ['2004', '2008', '2012', '2016', '2020', '2024', '2028', '2032']\n\n# Create a list of the past 6 month names.\nPlotMonths = []\nfor i in range(6, 0, -1):\n PlotMonths.append(MonthName[endMonth - i])\n#print(PlotMonths)\n\n# List of plot-month calendar numbers\nMonthNums = [MonthName.index(x) + 1 for x in PlotMonths]\n#print(MonthNums)\n\n# Metric names (variable and then a like-sensor to compare against) and comments describing some variable names\nVariableNames = ['2m Temperature', '10m Temperature', '2m RH', 'TB3 Rainfall', '10m Windspeed', '10m Wind Direction', 'Pressure1',\n 'Total Radiation', 'Hydraprobe', 'Surface Temp', '10cm Soil Temp', '50cm Soil Temp', 'Vertical Windspeed']\nVariableComment = ['', '', '', '', '(1-min vector mean)', '(1-min vector mean)', '', '', '1m Soil Temperature',\n '', 'Thermocouples', 'Thermocouples', '(both parameters indicate turbulence at 10m)'] \nLikeSensorNames = ['1.5m Temperature', '9.5m Temperature', '10m RH', 'TE Rainfall', '2m Windspeed', '2m Wind Direction', 'Pressure2',\n 'Quantum Radiation', 'Thermocouple', '5cm Soil Temp', '5cm Soil Temp', '20cm Soil Temp', '10m Wind St.Dev.']\n\n# Encoding below is for symbols like m/s^2, degrees, exponents, etc. There appears to be encoding issues in the versions of Python and modules on the server.\nVariableUnits = ['$^{o}$C', '$^{o}$C', '%', 'mm', 'ms$^{-1}$', 'degrees', 'mb', 'Wm$^{-2}$', '$^{o}$C', '$^{o}$C', '$^{o}$C', '$^{o}$C', 'ms$^{-1}$']\n\n# Set y-axis ranges and increments for plotting\n# plot1 and plot3\nMinValues = [-10.0, -10.0, 0.0, 0.0, 0.0, 0, 1000, 0, -5, -10, -5, -5, -4]\nMaxValues = [ 40.0, 40.0, 110.0, 2.5, 15.0, 360, 1040, 2000, 40, 55, 40, 40, 4]\nIncValues = [ 5.0, 5.0, 10.0, 0.5, 5.0, 45, 10, 200, 5, 5, 5, 5, 1]\n\n# plot1 secondary yaxis\nSecMinValues = [-10.0, -10.0, 0.0, 0.0, 0.0, 0, 1000, 0, -5, -10, -5, -5, 0]\nSecMaxValues = [ 40.0, 40.0, 110.0, 2.5, 15.0, 360, 1040, 2000, 40, 55, 40, 40, 100]\nSecIncValues = [ 5.0, 5.0, 10.0, 0.5, 5.0, 45, 10, 200, 5, 5, 5, 5, 10]\n\n# plot2\nMinDiffValues = [-2.0, -2.0, -10.0, -2.5, -5.0, -180, -2, -500, -10, -10, -10, -10, -100]\nMaxDiffValues = [ 2.0, 2.0, 10.0, 2.5, 5.0, 180, 2, 500, 10, 10, 10, 10, 10]\nIncDiffValues = [ 0.5, 0.5, 1.0, 0.5, 1.0, 90, 1, 50, 2, 2, 2, 2, 10]\n\n# plot4\nMinDiffBuddy = [-4.0, -4.0, -15.0, -2.5, -5.0, -180, -4, -500, -10, -10, -10, -10, -10]\nMaxDiffBuddy = [ 4.0, 4.0, 15.0, 2.5, 5.0, 180, 4, 500, 10, 10, 10, 10, 10]\nIncDiffBuddy = [ 0.5, 0.5, 5.0, 0.5, 1.0, 90, 1, 50, 2, 2, 2, 2, 2]\n\n# Main station and its buddy makes 2 stations. station and buddy variables are used for list/array indices.\nstations = 2\nstation = 0\nbuddy = 1\n\nresult = [[] for x in range(2)]\n\n# Get data and create plots for primary station per month in timeframe.\ndef main(result, dateStart, dateEnd, cursor, MonthNums, InputNames):\n #print(dateStart)\n #print(dateEnd)\n StationNames = InputNames\n result = getData(result, dateStart, dateEnd, cursor, MonthNums, StationNames)\n #print(result)\n\n # Loop over the months. \n for mo in PlotMonths:\n start_time = time.time()\n monthIndex = PlotMonths.index(mo)\n #print(monthIndex)\n\n # Calculate the actual number of minutes in this month, allow for leap years. Prepare basic label info. \n # Jan through July MUST be in the current year if doing 6 months worth of plots.\n # Aug through Dec (if they are plotted) must be in previous year if last plotted month is between Jan and May\n if mo in MonthName[7:] and 1 <= endMonth <= 5: \n plotyear = str(datetime.today().year - 1) #Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec\n else:\n plotyear = str(datetime.today().year)\n\n monthNum = MonthName.index(mo)\n if monthNum == 1 and (plotyear in LeapYears):\n days = 29\n else:\n days = DaysInMonth[monthNum]\n #print(MonthName[monthNum], plotyear, days)\n\n delx = 24 * 60 # minutes in a day\n plotmins = days * delx # minutes in a given month\n\n timelabel = ['' for i in range(plotmins)]\n xlabel = ['' for i in range((plotmins // delx) + 1)] # This integer-division syntax works for both Py 2 and Py 3\n\n # zeroline\n #zeroline = np.full((plotmins), 0.0, dtype = float)\n zeroline = np.zeros(plotmins) # In order to make this work using numpy 1.7\n #print(zeroline)\n #print(zeroline.shape)\n\n ## Weather Station Data\n # Initialize the full array with NaN to account for missing data\n\n # Initializations for newer version of numpy\n #Variables = np.full((len(VariableNames), stations, plotmins), np.nan, dtype = float) # This gives a np array with a shape of (for example) 13x2x43200. (large number is minues in month)\n # Last dimension size will vary based on what month it is.\n #LikeVars = np.full((len(VariableNames), stations, plotmins), np.nan, dtype = float)\n #BatVolt = np.full((stations, plotmins), np.nan, dtype = float) # 2 x numMinsInMonth\n #DoorOpen = np.full((stations, plotmins), np.nan, dtype = float) # Same\n #Observations = np.full((stations , plotmins), np.nan, dtype = float) # Same\n #PanelTemp = np.full((stations, plotmins), np.nan, dtype = float) # Same\n\n # Initializations for older version of numpy on dev server without np.full()\n Variables = np.empty((len(VariableNames), stations, plotmins))\n Variables[:] = np.nan\n LikeVars = np.empty((len(VariableNames), stations, plotmins))\n LikeVars[:] = np.nan\n BatVolt = np.empty((stations, plotmins))\n BatVolt[:] = np.nan\n DoorOpen = np.empty((stations, plotmins))\n DoorOpen[:] = np.nan\n Observations = np.empty((stations, plotmins))\n Observations[:] = np.nan\n PanelTemp = np.empty((stations, plotmins))\n PanelTemp[:] = np.nan\n\n #print(LikeVars.shape)\n\n batmins = 0\n doormins = 0\n obsmins = 0\n\n date = mo + plotyear\n #print(date)\n #elapsed_time = time.time() - start_time\n #print('Numpy initialization time for ' + mo + ': ' + str(elapsed_time))\n\n # Read in the data for the station and its buddy\n for s in range(stations):\n for row in result[s][monthIndex]:\n #print(row)\n # Start storing the data when it coincides with the iMET observing period. \n #year = row[0] # Currently unused\n #month = row[1] # Currently unused\n day = row[2]\n hour = row[3]\n minute = row[4]\n index = ((day - 1) * delx) + (hour * 60) + minute # Refers to the particular minute of a month accounting for minutes\n # that have already been processed.\n\n # Each variable contains information for each station. s = index of one of the stations that had info pulled\n # index refers to the particular minute of the day being processed\n if (index < plotmins): \n timelabel[index] = str(day)\n # 2m Temperature\n Variables[0, s, index] = float(row[5]) \n # 1.5m Temperature\n LikeVars[0, s, index] = float(row[6]) \n # 10m Temperature\n Variables[1, s, index] = float(row[7]) \n # 9.5m Temperature\n LikeVars[1, s, index] = float(row[8]) \n # 2m RH\n Variables[2, s, index] = float(row[9])\n # 10m RH \n LikeVars[2, s, index] = float(row[10])\n # TB3 Rainfall\n Variables[3, s, index] = float(row[11])\n # TE Rainfall \n LikeVars[3, s, index] = float(row[12])\n # 10m vector mean wind speed over 1 min\n Variables[4, s, index] = float(row[13])\n # 2m vector mean wind speed over 1 min \n LikeVars[4, s, index] = float(row[14])\n # 10m vector mean wind direction over 1 min\n Variables[5, s, index] = float(row[15])\n # 2m vector mean wind direction over 1 min\n LikeVars[5, s, index] = float(row[16])\n # Pressure 1\n Variables[6, s, index] = float(row[17])\n # Pressure 2\n LikeVars[6, s, index] = float(row[18])\n # Total Radiation\n Variables[7, s, index] = float(row[19])\n # Quantum Radiation\n LikeVars[7, s, index] = float(row[20])\n # Hydraprobe soil temp at 1m\n Variables[8, s, index] = float(row[21])\n # Thermocouple soil temp at 1m\n LikeVars[8, s, index] = float(row[22]) \n # Soil surface temp\n Variables[9, s, index] = float(row[23])\n # Soil Temp at 5 cm\n LikeVars[9, s, index] = float(row[24]) \n # Soil Temp at 10 cm\n Variables[10, s, index] = float(row[25])\n # Soil Temp at 5 cm\n LikeVars[10, s, index] = float(row[26]) \n # Soil Temp at 50 cm\n Variables[11, s, index] = float(row[27])\n # Soil Temp at 20 cm\n LikeVars[11, s, index] = float(row[28]) \n # Verical Wind speed at 10m\n Variables[12, s, index] = float(row[29])\n # 10m Horizontal wind speed standard deviation - subtract maximum axis value to line up the 2 variables.\n LikeVars[12, s, index] = float(row[30]) \n # Battery voltage\n BatVolt[s, index] = float(row[31])\n if (s == 0 and BatVolt[s, index] < 12.0):\n batmins += 1\n # Number of obs per minute\n Observations[s, index] = float(row[32])\n if (s == 0 and Observations[s, index] < 10.0):\n obsmins += 1\n # Door Open indicator\n DoorOpen[s, index] = float(row[33])\n if (s == 0 and DoorOpen[s, index] == 1.0):\n doormins += 1\n # Data logger panel temperature\n PanelTemp[s, index] = float(row[34])\n \n # To test if data is being readin correctly\n #for station in Variables[0]:\n # for reading in station:\n # if not np.isnan(reading):\n # print(reading)\n\n #print(PanelTemp[station,0])\n\n # Get differences between variable and like-sensor metrics\n Diff = Variables - LikeVars\n\n # For older version of numpy where nansum, etc. not available:\n # Creates a mask over np.nan, carries out operation, then refills True ('np.nan') values with np.nan\n meanvar = np.mean(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n meanvar = np.ma.filled(meanvar, fill_value = np.nan)\n\n sumvar = np.sum(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n sumvar = np.ma.filled(sumvar, fill_value = np.nan)\n\n minvar = np.min(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n minvar = np.ma.filled(minvar, fill_value = np.nan)\n\n maxvar = np.max(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n maxvar = np.ma.filled(maxvar, fill_value = np.nan)\n\n stdvar = np.std(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n stdvar = np.ma.filled(stdvar, fill_value = np.nan)\n\n # For older version of numpy where nansum, etc. not available:\n # Creates a mask over np.nan, carries out operation, then refills True ('np.nan') values with np.nan\n meandiff = np.mean(np.ma.masked_array(Diff, np.isnan(Diff)), axis = 2)\n meandiff = np.ma.filled(meandiff, fill_value = np.nan)\n\n mindiff = np.min(np.ma.masked_array(Diff, np.isnan(Diff)), axis = 2)\n mindiff = np.ma.filled(mindiff, fill_value = np.nan)\n\n maxdiff = np.max(np.ma.masked_array(Diff, np.isnan(Diff)), axis = 2)\n maxdiff = np.ma.filled(maxdiff, fill_value = np.nan)\n\n stddiff = np.std(np.ma.masked_array(Diff, np.isnan(Diff)), axis = 2)\n stddiff = np.ma.filled(stddiff, fill_value = np.nan)\n\n ## The plot creation and printing section of the program. This could be a logical place to split the program.\n ## Much of this could probably be defined as classes in order to reduce duplicate coding.\n ## For instance, many plots have the same base property values and could be created from a template class\n\n print('\\nPlots for ' + StationNames[0] + ': ' + date) # Syntax works for Py 2 and 3\n print('===============================')\n \n start_time = time.time()\n\n for var in range(len(VariableNames)):\n\n #print(VariableNames[var])\n #print(Variables[var,station])\n \n print('Plotting ' + VariableNames[var])\n\n ## Get axes statistics\n\n # Will show warnings if entire fields are NULL in data. Can probably be surpressed.\n # Below is for more up-to-date versions of numpy\n #meanvar = np.nanmean(Variables, axis=2) # Compute mean along axis, ignoring nans \n #sumvar = np.nansum(Variables, axis=2) # Compute sum along axis, ignore nans\n #minvar = np.nanmin(Variables, axis=2) # Compute minimum along axis, ignore nans\n #maxvar = np.nanmax(Variables, axis=2) # Compute max along axis, ignore nans\n #stdvar = np.nanstd(Variables, axis=2) # Compute standard deviation along axis, ignore nans\n\n # For older version of numpy where if nansum, etc. not available:\n # Creates a mask over np.nan, carries out operation, then refills True ('np.nan') values with np.nan\n #meanvar = np.mean(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n #meanvar = np.ma.filled(meanvar, fill_value = np.nan)\n #sumvar = np.sum(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n #sumvar = np.ma.filled(sumvar, fill_value = np.nan)\n #minvar = np.min(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n #minvar = np.ma.filled(minvar, fill_value = np.nan)\n #maxvar = np.max(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n #maxvar = np.ma.filled(maxvar, fill_value = np.nan)\n #stdvar = np.std(np.ma.masked_array(Variables, np.isnan(Variables)), axis = 2)\n #stdvar = np.ma.filled(stdvar, fill_value = np.nan)\n \n # Get differences between variable and like-sensor metrics\n #Diff = Variables - LikeVars\n\n # Will show warnings if entire fields are NULL in data\n # For newer versions of numpy\n #meandiff = np.nanmean(Diff, axis = 2)\n #mindiff = np.nanmin(Diff, axis = 2)\n #maxdiff = np.nanmax(Diff, axis = 2) \n #stddiff = np.nanstd(Diff, axis = 2) # unused?\n\n # For older version of numpy where if nansum, etc. not available:\n # Creates a mask over np.nan, carries out operation, then refills True ('np.nan') values with np.nan\n #meandiff = np.mean(np.ma.masked_array(Diff, np.isnan(Diff)), axis = 2)\n #meandiff = np.ma.filled(meandiff, fill_value = np.nan)\n #mindiff = np.min(np.ma.masked_array(Diff, np.isnan(Diff)), axis = 2)\n #mindiff = np.ma.filled(mindiff, fill_value = np.nan)\n #maxdiff = np.max(np.ma.masked_array(Diff, np.isnan(Diff)), axis = 2)\n #maxdiff = np.ma.filled(maxdiff, fill_value = np.nan)\n #stddiff = np.std(np.ma.masked_array(Diff, np.isnan(Diff)), axis = 2)\n #stddiff = np.ma.filled(stddiff, fill_value = np.nan)\n \n missing = 0 # Used to keep count of missing readings\n\n # Find number of missing minutes (data entries)\n for index in range(plotmins):\n if np.isnan(Variables[var, station, index]):\n missing += 1\n\n #print(missing)\n #print(plotmins)\n\n misspercent = (float(missing) / plotmins) * 100 # This float-division syntax works for both Py 2 and Py 3\n #print(misspercent)\n\n # Start figure/plot creation\n figure1 = plt.figure(figsize = (25, 20))\n\n # Add some space between the panels on the plot\n figure1.subplots_adjust(hspace=0.5)\n\n # Add subplots\n plot1 = figure1.add_subplot(4,1,1)\n plot2 = figure1.add_subplot(4,1,2)\n plot3 = figure1.add_subplot(4,1,3)\n plot4 = figure1.add_subplot(4,1,4)\n\n # Plot variable and like-sensor for station\n # This works because order of Variables and VariableNames matches. Assignment of variables from DB pull need to match.\n # The order of VariableUnits also relies on the above. Assignment of variables from DB pull need to match.\n # LikeVariableNames follow the same rules. Order matters.\n if (VariableNames[var] == '10m Wind direction'): \n plot1.scatter(range(plotmins), Variables[var,station], linewidth = 0, marker = '.', \n color = 'royalblue', label = '%s %s' % (VariableNames[var], StationNames[station])) \n # alpha makes the line transparent; a smaller value is more transparent\n # plot1.scatter(range(plotmins), LikeVars[var,station], linewidth=0, marker='.', color='red', alpha=0.4, label='%s %s' %(LikeSensorNames[var],StationNames[station]))\n else:\n plot1.plot(range(plotmins), Variables[var,station], linewidth = 2, color = 'royalblue', \n label = '%s %s' % (VariableNames[var], StationNames[station])) \n # alpha makes the line transparent; a smaller value is more transparent\n # plot1.twinx().plot(range(plotmins), LikeVars[var,station], linewidth=1.2, linestyle='--', color='red', alpha=0.4, label='%s %s' %(LikeSensorNames[var],StationNames[station]))\n\n # 'pad' is the padding space between the tick marks and the number, 'direction' determines which way the tick marks point, 'size' sets the length of the tick marks\n plot1.set_xlim([0, plotmins])\n\n # Set time (x) axis increment in minutes\n plot1.tick_params(axis = 'x', colors = 'black', direction = 'out', pad = 0, size = 10)\n\n # Minor tick marks\n #plot1.minorticks_on()\n\n #plot1.xaxis.set_minor_locator(MultipleLocator(60*12))\n plot1.set_xticks(np.linspace(0, plotmins, (plotmins // delx) + 1))\n for i in range((plotmins // delx)):\n xlabel[i] = timelabel[i * delx]\n plot1.set_xticklabels(xlabel, rotation = 90, ha = 'center', fontsize = 14)\n\n #Set ticks and labels on primary y-axis\n plot1.set_ylim(MinValues[var], MaxValues[var])\n plot1.set_yticks(np.arange(MinValues[var], MaxValues[var] + 0.1, IncValues[var]))\n plot1.set_ylabel(r\"%s (%s)\" % (VariableNames[var], VariableUnits[var]), fontsize = 14, color = 'royalblue')\n\n # Make the y labels bigger.\n for label in plot1.get_yticklabels():\n label.set_color('royalblue') # This does not work. I believe it is a bug in matplotlib. I have tried different colors according to spec.\n label.set_size(14)\n\n plot1.tick_params(axis = 'y', colors='blue')\n\n # Add title, grid, legend etc.\n # transform=plot1.transAxes makes the x and y coordinates run from 0 to 1 with (0,0) being the lower left and (1,1) the upper left corner of the plot panel.\n plot1.text(0, 1.5, \"Station: %s Buddy: %s Date: %s \" % (StationNames[station], StationNames[buddy], date), \n transform = plot1.transAxes, fontsize = 28, fontweight = 'bold')\n plot1.text(0, 1.3, \"Variable: %s %s\" % (VariableNames[var], VariableComment[var]), \n transform = plot1.transAxes, fontsize = 26, fontweight = 'bold')\n if(VariableNames[var] == 'TB3 Rainfall'):\n plot1.text(0, 1.1, \"Total = %5.2f %s\" % (sumvar[var, station], VariableUnits[var]), \n transform = plot1.transAxes, horizontalalignment = 'left', fontsize = 22, fontweight = 'bold')\n else:\n plot1.text(0, 1.1, \"Mean = %5.2f %s\" % (meanvar[var, station], VariableUnits[var]), \n transform = plot1.transAxes, horizontalalignment = 'left', fontsize = 22, fontweight ='bold')\n\n # minvalue=minvar[var,station]\n plot1.text(0.25, 1.1, \"Minimum = %5.2f %s\" % (minvar[var, station], VariableUnits[var]), \n transform = plot1.transAxes, horizontalalignment = 'left', fontsize = 20, fontweight = 'bold')\n # maxvalue=maxvar[var,station]\n plot1.text(0.5, 1.1, \"Maximum = %5.2f %s\" % (maxvar[var, station], VariableUnits[var]), \n transform = plot1.transAxes, horizontalalignment = 'left', fontsize = 20, fontweight = 'bold')\n # tsdvalue=stdvar[var,station]\n plot1.text(0.75, 1.1, \"St. Deviation = %5.2f %s\" % (stdvar[var, station], VariableUnits[var]), \n transform = plot1.transAxes, horizontalalignment = 'left', fontsize = 20, fontweight = 'bold')\n unit = \"%\"\n plot1.text(0.675, 1.5, \"Missing minutes = %6i (%6.2f %s)\" % (missing, misspercent, unit), \n transform = plot1.transAxes, horizontalalignment = 'left', fontsize = 20, fontweight = 'bold')\n \n plot1.grid(which = 'major', axis = 'both', color = 'LightGrey', linestyle = 'dotted')\n plot1.grid(which = 'minor', axis = 'x', color = 'LightGrey', linestyle = 'dotted')\n\n ## Secondary y-axis for like-sensor\n plot5 = plot1.twinx()\n if (VariableNames[var] == '10m Wind direction'):\n plot5.scatter(range(plotmins), LikeVars[var, station], linewidth = 0, marker = '.', color = 'red', \n alpha = 0.3, label = '%s %s' % (LikeSensorNames[var],StationNames[station]))\n else:\n plot5.plot(range(plotmins), LikeVars[var, station], linewidth = 1.2, linestyle = '--', color = 'red', \n alpha = 0.4, label = '%s %s' % (LikeSensorNames[var],StationNames[station]))\n plot5.set_xlim([0,plotmins])\n\n # Set Secondary axis y labels and tick marks.\n plot5.set_ylim(SecMinValues[var], SecMaxValues[var])\n plot5.set_yticks(np.arange(SecMinValues[var], SecMaxValues[var] + 0.1, SecIncValues[var]))\n for label in plot5.get_yticklabels():\n label.set_color('red')\n label.set_size(14)\n # plot1.twinx().set_ylabel(r\"%s %s\" %(VariableNames[var],VariableUnits[var]),fontsize = 14, color ='red')\n # plot1.twinx().get_yaxis().get_major_formatter().set_useOffset(False)\n \n # Draw legends\n # ncol alows you to place the legend labels side by side; set it to n if you have n labels, so it creates n columns for you.\n # bbox_to_anchor allows you to place the legend relative to the plot area with the first number being the x dimension and the second the y dimensions, \n # x and y values ranging from 0 to 1 define the plot area with bottom left being (0,0) and top right (1,1).\n # Throughout, legend and frame coding was changed because the API is different for the version of matplotlib on the server\n # The original code has been left in, just commented out.\n\n #plot5.legend(loc = 2, ncol = 1, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.8, 1.04))\n #plot1.legend(loc = 2, ncol = 1, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.4, 1.04))\n legend5 = plot5.legend(loc = 2, ncol = 1, fontsize = 14, bbox_to_anchor = (0.3, -0.1))\n frame5 = legend5.get_frame()\n frame5.set_alpha(1.0) # May need to be '1.0' for older module?\n legend1 = plot1.legend(loc = 2, ncol = 1, fontsize = 14, bbox_to_anchor = (0.0, -0.1))\n frame1 = legend1.get_frame()\n frame1.set_alpha(1.0)\n\n # Plot difference between variable and like-sensor for station\n if (VariableNames[var] == '10m Wind direction'):\n plot2.scatter(range(plotmins), Variables[var, station] - LikeVars[var, station], \n linewidth = 0.0, marker = '.', color = 'royalblue', label = '%s-%s %s' % (VariableNames[var], LikeSensorNames[var], StationNames[station])) \n else:\n plot2.plot(range(plotmins), Variables[var, station] - LikeVars[var, station], \n linewidth = 1.2, color = 'royalblue', label = '%s-%s %s' % (VariableNames[var], LikeSensorNames[var], StationNames[station]))\n\n plot2.plot(range(plotmins), zeroline, linewidth = 1.0, color = 'black') \n plot2.set_xlim([0, plotmins])\n\n # Set time (x) axis increment in minutes\n plot2.tick_params(axis = 'x', colors = 'black', direction = 'out', pad = 0, size = 10)\n\n # Minor tick marks\n #plot2.minorticks_on()\n #plot2.xaxis.set_minor_locator(MultipleLocator(60*12))\n plot2.set_xticks(np.linspace(0, plotmins, (plotmins // delx) + 1))\n for i in range((plotmins // delx)):\n xlabel[i] = timelabel[i * delx]\n\n plot2.set_xticklabels(xlabel, rotation = 90, ha = 'center', fontsize = 14)\n #plot2.set_xlabel(\"Midnight/Day of the month\", fontsize= 14)\n plot2.set_ylim(MinDiffValues[var], MaxDiffValues[var])\n plot2.set_yticks(np.arange(MinDiffValues[var], MaxDiffValues[var] + 0.1, IncDiffValues[var]))\n plot2.set_ylabel(r\"%s (%s)\" % (VariableNames[var], VariableUnits[var]), fontsize = 14, color = 'black')\n\n # Make the y labels bigger and blue.\n for label in plot1.get_yticklabels():\n label.set_size(14)\n label.set_color('black')\n\n #plot2.text(-60,MaxDiffValues[var]+IncDiffValues[var],\"Station: %s Buddy: %s Date: %s\" % (StationNames[station],StationNames[buddy],date),fontsize=22,fontweight='bold')\n plot2.grid(which = 'major', axis = 'both', color = 'LightGrey', linestyle = 'dotted')\n plot2.grid(which = 'minor', axis = 'x', color = 'LightGrey', linestyle = 'dotted')\n #plot2.legend(loc = 2, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.4, 1.08))\n legend2 = plot2.legend(loc = 2, fontsize = 14, bbox_to_anchor = (0.0, -0.1))\n frame2 = legend2.get_frame()\n frame2.set_alpha(1.0)\n plot2.text(0, 1.1,\"DiffMean = %5.2f %s\" % (meandiff[var, station],VariableUnits[var]), \n transform = plot2.transAxes, horizontalalignment = 'left', fontsize = 20, fontweight = 'bold')\n plot2.text(0.25, 1.1, \"DiffMin = %5.2f %s\" % (mindiff[var, station],VariableUnits[var]), \n transform = plot2.transAxes, horizontalalignment = 'left', fontsize = 20, fontweight = 'bold')\n plot2.text(0.5, 1.1, \"DiffMax = %5.2f %s\" % (maxdiff[var, station],VariableUnits[var]), \n transform = plot2.transAxes, horizontalalignment = 'left', fontsize = 20, fontweight = 'bold') \n plot2.text(0.75, 1.1, \"DiffStDev = %5.2f %s\" % (stddiff[var, station],VariableUnits[var]), \n transform = plot2.transAxes, horizontalalignment = 'left', fontsize = 20, fontweight = 'bold')\n\n # Plot variable for station and buddy \n if (VariableNames[var] == '10m Wind direction'):\n # Should 'royalblue' be 'RoyalBlue' or 'SeaGreen' be 'seagreen'?\n plot3.scatter(range(plotmins), Variables[var, station], linewidth = 0, marker = '.', color = 'royalblue', \n label = '%s %s' % (VariableNames[var], StationNames[station])) \n plot3.scatter(range(plotmins), Variables[var, buddy], linewidth = 0, marker = '.', color = 'SeaGreen', \n alpha = 0.3, label = '%s %s' % (VariableNames[var], StationNames[buddy])) \n else:\n plot3.plot(range(plotmins), Variables[var, station], linewidth = 2, color = 'royalblue', \n label = '%s %s' % (VariableNames[var], StationNames[station])) \n plot3.plot(range(plotmins), Variables[var, buddy], linewidth = 2, linestyle = '--', color = 'SeaGreen', \n alpha = 0.4, label = '%s %s' % (VariableNames[var], StationNames[buddy]))\n\n # 'pad' is the padding space between the tick marks and the number, 'direction' determines which way the tick marks point, 'size' sets the length of the tick marks\n plot3.set_xlim([0, plotmins])\n\n # Set time (x) axis increment in minutes\n plot3.tick_params(axis = 'x', colors = 'black', direction = 'out', pad = 0, size = 10)\n\n # Minor tick marks\n #plot3.minorticks_on()\n #plot3.xaxis.set_minor_locator(MultipleLocator(60*12))\n plot3.set_xticks(np.linspace(0, plotmins, (plotmins // delx) + 1))\n for i in range((plotmins // delx)):\n xlabel[i] = timelabel[i * delx]\n\n plot3.set_xticklabels(xlabel, rotation = 90, ha = 'center', fontsize = 14)\n #plot3.set_xlabel(\"Midnight/Day of the month\", fontsize= 14)\n plot3.set_ylim(MinValues[var], MaxValues[var])\n plot3.set_yticks(np.arange(MinValues[var], MaxValues[var] + 0.1, IncValues[var]))\n plot3.set_ylabel(r\"%s (%s)\" % (VariableNames[var], VariableUnits[var]), fontsize = 14, color = 'black')\n\n # Make the y labels bigger.\n for label in plot3.get_yticklabels():\n label.set_size(14)\n label.set_color('black')\n\n plot3.grid(which = 'major', axis = 'both', color = 'LightGrey', linestyle = 'dotted')\n plot3.grid(which = 'minor', axis = 'x', color = 'LightGrey', linestyle = 'dotted')\n # ncol alows you to place the legend labels side by side; set it to n if you have n labels, so it creates n columns for you.\n #plot3.legend(loc = 2, ncol = 2, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.4, 1.08))\n legend3 = plot3.legend(loc = 2, ncol = 2, fontsize = 14, bbox_to_anchor = (0.0, -0.1))\n frame3 = legend3.get_frame()\n frame3.set_alpha(1.0)\n\n # Plot variable difference between buddies.\n if (VariableNames[var] == '10m Wind direction'):\n plot4.scatter(range(plotmins), Variables[var, station] - Variables[var, buddy], linewidth = 0, marker = '.', color = 'seagreen', \n label = '%s %s - %s %s' % (VariableNames[var], StationNames[station], VariableNames[var], StationNames[buddy])) \n else:\n plot4.plot(range(plotmins), Variables[var, station] - Variables[var, buddy], linewidth = 1.2, color = 'seagreen', \n label = '%s %s - %s %s' % (VariableNames[var], StationNames[station], VariableNames[var], StationNames[buddy])) \n plot4.plot(range(plotmins), zeroline, linewidth = 1.0, color = 'black') \n\n # 'pad' is the padding space between the tick marks and the number, 'direction' determines which way the tick marks point, 'size' sets the length of the tick marks\n plot4.set_xlim([0, plotmins])\n\n # Set time (x) axis increment in minutes\n plot4.tick_params(axis = 'x', colors = 'black', direction = 'out', pad = 0, size = 10)\n\n # Minor tick marks\n #plot4.minorticks_on()\n #plot4.xaxis.set_minor_locator(MultipleLocator(60*12))\n plot4.set_xticks(np.linspace(0, plotmins, (plotmins // delx) + 1))\n for i in range((plotmins // delx)):\n xlabel[i] = timelabel[i * delx]\n\n plot4.set_xticklabels(xlabel, rotation = 90, ha = 'center', fontsize = 14)\n plot4.set_xlabel(\"Midnight/Day of the month\", fontsize = 14)\n\n plot4.set_ylim(MinDiffBuddy[var], MaxDiffBuddy[var])\n plot4.set_yticks(np.arange(MinDiffBuddy[var], MaxDiffBuddy[var] + 0.1, IncDiffBuddy[var]))\n plot4.set_ylabel(r\"%s (%s)\" % (VariableNames[var], VariableUnits[var]), fontsize = 14, color = 'black')\n\n # Make the y labels bigger and blue.\n for label in plot1.get_yticklabels():\n label.set_size(14)\n label.set_color('black')\n\n #plot4.text(-60,MaxDiffValues[var]+IncDiffValues[var],\"Station: %s Buddy: %s Date: %s\" % (StationNames[station],StationNames[buddy],date),fontsize=22,fontweight='bold')\n plot4.grid(which = 'major', axis = 'both', color = 'LightGrey', linestyle = 'dotted')\n plot4.grid(which = 'minor', axis = 'x', color = 'LightGrey', linestyle = 'dotted')\n #plot4.legend(loc = 2, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.4, 1.08))\n legend4 = plot4.legend(loc = 2, fontsize = 14, bbox_to_anchor = (0.0, -0.1))\n frame4 = legend4.get_frame()\n frame4.set_alpha(1.0)\n\n ### Write the plot to a file \n #Variable = '2mTemperature' # I'm unsure what this was for as the variable was never used.\n # Added dir_path and the forward-slash to save files to current working directory. Windows may need to flip the slash?\n \n savePath = dir_path + \"/QCplots/%s/%s/%s/\" % (StationNames[station], plotyear, mo)\n if not os.path.exists(savePath):\n os.makedirs(savePath)\n\n figure1.savefig(savePath + \"%s-%s-%s.png\" % (StationNames[station], VariableNames[var].replace(' ', ''), date), format='png')\n plt.close(figure1)\n\n # Plot DL Status parameters\n print('Plotting Status Parameters\\n')\n\n figure1 = plt.figure(figsize = (25, 16))\n plot1 = figure1.add_subplot(4, 1, 1)\n plot2 = figure1.add_subplot(4, 1, 2)\n plot3 = figure1.add_subplot(4, 1, 3)\n plot4 = figure1.add_subplot(4, 1, 4)\n\n figure1.subplots_adjust(hspace = 0.55)\n\n minrange = 10\n maxrange = 14\n incrange = 1\n\n plot1.plot(range(plotmins), BatVolt[station], linewidth = 2, color = 'royalblue', label = 'Battery Voltage') \n plot1.set_xlim([0, plotmins])\n # Set time (x) axis increment in minutes\n plot1.tick_params(axis = 'x', colors = 'black', direction = 'out', pad = 0, size = 10)\n plot1.set_xticks(np.linspace(0, plotmins, (plotmins // delx) + 1))\n for i in range((plotmins // delx)):\n xlabel[i] = timelabel[i * delx]\n\n plot1.set_xticklabels(xlabel, rotation = 90, ha = 'center', fontsize = 14)\n #plot1.set_xlabel(\"Midnight/Day of the month\", fontsize= 14)\n\n plot1.set_ylim(minrange, maxrange)\n plot1.set_yticks(np.arange(minrange, maxrange + 0.1, incrange))\n plot1.set_ylabel(r\"Battery Voltage (V)\",fontsize = 14, color = 'black')\n\n # Make the y labels bigger.\n for label in plot1.get_yticklabels():\n label.set_size(14)\n label.set_color('black')\n\n plot1.text(-55, maxrange + incrange, \"Station: %s Date: %s Status Parameters\" % (StationNames[station], date), \n fontsize = 26,fontweight = 'bold')\n plot1.grid(which = 'major', axis = 'both', color = 'LightGrey', linestyle = 'dotted')\n plot1.grid(which = 'minor', axis = 'x', color = 'LightGrey', linestyle = 'dotted')\n # ncol alows you to place the legend labels side by side; set it to n if you have n labels, so it creates n columns for you.\n # bbox_to_anchor allows you to place the legend relative to the plot area with the first number being the x dimension and the second the y dimensions, \n # x and y values ranging from 0 to 1 define the plot area with bottom left being (0,0) and top right (1,1).\n\n #plot1.legend(loc = 2, ncol = 2, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.4, 1.08))\n legend1 = plot1.legend(loc = 2, ncol = 2, fontsize = 14, bbox_to_anchor = (0.0, -0.1))\n frame1 = legend1.get_frame()\n frame1.set_alpha(1.0)\n unit = \"%\"\n plot1.text(0.7, 1.25, \"Missing minutes = %6i (%6.2f %s)\" % (missing,misspercent,unit), \n transform = plot1.transAxes, horizontalalignment = 'left', fontsize = 18, fontweight = 'bold')\n plot1.text(0.0, 1.1, \"Number of minutes below 12V = %6i \" % (batmins), \n transform = plot1.transAxes, horizontalalignment = 'left', fontsize = 18, fontweight = 'bold')\n\n minrange = -1\n maxrange = 2\n incrange = 1\n\n plot2.plot(range(plotmins), DoorOpen[station], linewidth = 2, color = 'red', label = 'Door Open') \n plot2.set_xlim([0, plotmins])\n\n # Set time (x) axis increment in minutes\n plot2.tick_params(axis = 'x', colors = 'black', direction = 'out', pad = 0, size = 10)\n plot2.set_xticks(np.linspace(0, plotmins, (plotmins // delx) + 1))\n for i in range((plotmins // delx)):\n xlabel[i] = timelabel[i * delx]\n\n plot2.set_xticklabels(xlabel, rotation = 90, ha = 'center', fontsize = 14)\n #plot2.set_xlabel(\"Midnight/Day of the month\", fontsize= 14)\n\n plot2.set_ylim(minrange, maxrange)\n plot2.set_yticks(np.arange(minrange, maxrange + 0.1, incrange))\n plot2.set_ylabel(r\"Door Open\",fontsize = 14, color = 'black')\n\n # Make the y labels bigger.\n for label in plot2.get_yticklabels():\n label.set_size(14)\n label.set_color('black')\n\n plot2.grid(which = 'major', axis = 'both', color = 'LightGrey', linestyle = 'dotted')\n plot2.grid(which = 'minor', axis = 'x', color = 'LightGrey', linestyle = 'dotted')\n # ncol alows you to place the legend labels side by side; set it to n if you have n labels, so it creates n columns for you.\n # bbox_to_anchor allows you to place the legend relative to the plot area with the first number being the x dimension and the second the y dimensions, \n # x and y values ranging from 0 to 1 define the plot area with bottom left being (0,0) and top right (1,1).\n\n #plot2.legend(loc = 2, ncol = 2, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.4, 1.08))\n legend2 = plot2.legend(loc = 2, ncol = 2, fontsize = 14, bbox_to_anchor = (0.0, -0.1))\n frame2 = legend2.get_frame()\n frame2.set_alpha(1.0)\n plot2.text(0.0, 1.1, \"Number of minutes with door open = %6i \" % (doormins), \n transform = plot2.transAxes, horizontalalignment = 'left', fontsize = 18, fontweight = 'bold')\n \n minrange = 0\n maxrange = 30\n incrange = 5\n plot3.plot(range(plotmins), Observations[station], linewidth = 2, color = 'seagreen', label = 'Observations in Minute') \n plot3.set_xlim([0, plotmins])\n\n # Set time (x) axis increment in minutes\n plot3.tick_params(axis = 'x', colors = 'black', direction = 'out', pad = 0, size = 10)\n plot3.set_xticks(np.linspace(0, plotmins, (plotmins // delx) + 1))\n for i in range((plotmins // delx)):\n xlabel[i] = timelabel[i * delx]\n\n plot3.set_xticklabels(xlabel, rotation = 90, ha = 'center', fontsize = 14)\n #plot3.set_xlabel(\"Midnight/Day of the month\", fontsize= 14)\n\n plot3.set_ylim(minrange, maxrange)\n plot3.set_yticks(np.arange(minrange, maxrange + 0.1, incrange))\n plot3.set_ylabel(r\"Observations\", fontsize = 14, color = 'black')\n\n # Make the y labels bigger.\n for label in plot3.get_yticklabels():\n label.set_size(14)\n label.set_color('black')\n\n plot3.grid(which = 'major', axis = 'both', color = 'LightGrey', linestyle = 'dotted')\n plot3.grid(which = 'minor', axis = 'x', color = 'LightGrey', linestyle = 'dotted')\n # ncol alows you to place the legend labels side by side; set it to n if you have n labels, so it creates n columns for you.\n # bbox_to_anchor allows you to place the legend relative to the plot area with the first number being the x dimension and the second the y dimensions, \n # x and y values ranging from 0 to 1 define the plot area with bottom left being (0,0) and top right (1,1).\n\n #plot3.legend(loc = 2, ncol = 2, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.4, 1.08))\n legend3 = plot3.legend(loc = 2, ncol = 2, fontsize = 14, bbox_to_anchor = (0.0, -0.1))\n frame3 = legend3.get_frame()\n frame3.set_alpha(1.0)\n plot3.text(0.0, 1.1, \"Number of minutes with less than 10 obs = %6i \" % (obsmins), \n transform = plot3.transAxes, horizontalalignment = 'left', fontsize = 18, fontweight = 'bold')\n\n minrange = -10\n maxrange = 45\n incrange = 5\n \n plot4.plot(range(plotmins), PanelTemp[station], linewidth = 2, color = 'indigo', label = 'Panel Temperature') \n plot4.set_xlim([0, plotmins])\n\n # Set time (x) axis increment in minutes\n plot4.tick_params(axis = 'x', colors = 'black', direction = 'out', pad = 0, size = 10)\n plot4.set_xticks(np.linspace(0, plotmins, (plotmins // delx) + 1))\n for i in range((plotmins // delx)):\n xlabel[i] = timelabel[i * delx]\n\n plot4.set_xticklabels(xlabel, rotation = 90, ha = 'center', fontsize = 14)\n #plot4.set_xlabel(\"Midnight/Day of the month\", fontsize= 14)\n\n plot4.set_ylim(minrange, maxrange)\n plot4.set_yticks(np.arange(minrange, maxrange + 0.1, incrange))\n plot4.set_ylabel(r\"Temperature ($^{o}$C)\", fontsize = 14, color = 'black')\n\n # Make the y labels bigger.\n for label in plot4.get_yticklabels():\n label.set_size(14)\n label.set_color('black')\n\n plot4.grid(which = 'major', axis = 'both', color = 'LightGrey', linestyle = 'dotted')\n plot4.grid(which = 'minor', axis = 'x', color = 'LightGrey', linestyle = 'dotted')\n # ncol alows you to place the legend labels side by side; set it to n if you have n labels, so it creates n columns for you.\n # bbox_to_anchor allows you to place the legend relative to the plot area with the first number being the x dimension and the second the y dimensions, \n # x and y values ranging from 0 to 1 define the plot area with bottom left being (0,0) and top right (1,1).\n\n #plot4.legend(loc = 2, ncol = 2, fontsize = 14, framealpha = 1.0, bbox_to_anchor = (0.4, 1.08))\n legend4 = plot4.legend(loc = 2, ncol = 2, fontsize = 14, bbox_to_anchor = (0.0, -0.1))\n frame4 = legend4.get_frame()\n frame4.set_alpha(1.0)\n # Plot4 doesn't have text? Should probably be something about panel temperature.\n \n savePath = dir_path + \"/QCplots/%s/%s/%s/\" % (StationNames[station], plotyear, mo)\n if not os.path.exists(savePath):\n os.makedirs(savePath)\n\n figure1.savefig(savePath + \"%s-StatusParameters-%s.png\" % (StationNames[station], date), format='png') #format kw is redundant but used for testing\n plt.close(figure1)\n\n elapsed_time = time.time() - start_time\n print(mo + ' plotting time for ' + StationNames[station]+ ': ' + str(elapsed_time) + '\\n')\n\nprint('Beginning queries...\\n')\n\nfor i in range(len(stationList)):\n main(result, dateStart, dateEnd, cursor, MonthNums, [stationList[i], buddyList[i]])\n\ncursor.close()\ncnx.close()\n\nelapsed_time = time.time() - entire_time\nprint('Total execution time: ' + str(elapsed_time))","sub_path":"Usa.chili.Data/cron/pythonscripts/monthly_QCAllMonths.py","file_name":"monthly_QCAllMonths.py","file_ext":"py","file_size_in_byte":52961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"19296430","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2012 Yahoo! Inc. 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 io\nimport os\nimport stat\n\nfrom devstack import cfg\nfrom devstack import component as comp\nfrom devstack import exceptions\nfrom devstack import libvirt as virsh\nfrom devstack import log as logging\nfrom devstack import settings\nfrom devstack import shell as sh\nfrom devstack import utils\n\nfrom devstack.components import db\nfrom devstack.components import keystone\n\n\n#id\nTYPE = settings.NOVA\nLOG = logging.getLogger('devstack.components.nova')\n\n#special generatedconf\nAPI_CONF = 'nova.conf'\n\n#normal conf\nPASTE_CONF = 'nova-api-paste.ini'\nCONFIGS = [PASTE_CONF]\n\n#this db will be dropped then created\nDB_NAME = 'nova'\n\n#this makes the database be in sync with nova\nDB_SYNC_CMD = [\n {'cmd': ['%BINDIR%/nova-manage', '--flagfile', '%CFGFILE%',\n 'db', 'sync']},\n]\n\n#these setup your dev network\nNETWORK_SETUP_CMDS = [\n #this always happens (even in quantum mode)\n {'cmd': ['%BINDIR%/nova-manage', '--flagfile', '%CFGFILE%',\n 'network', 'create', 'private', '%FIXED_RANGE%', 1, '%FIXED_NETWORK_SIZE%']},\n #these only happen if not in quantum mode\n {'cmd': ['%BINDIR%/nova-manage', '--flagfile', '%CFGFILE%',\n 'floating', 'create', '%FLOATING_RANGE%']},\n {'cmd': ['%BINDIR%/nova-manage', '--flagfile', '%CFGFILE%',\n 'floating', 'create', '--ip_range=%TEST_FLOATING_RANGE%',\n '--pool=%TEST_FLOATING_POOL%']}\n]\n\n#these are used for nova volumens\nVG_CHECK_CMD = [\n {'cmd': ['vgs', '%VOLUME_GROUP%'],\n 'run_as_root': True}\n]\nVG_DEV_CMD = [\n {'cmd': ['losetup', '-f', '--show', '%VOLUME_BACKING_FILE%'],\n 'run_as_root': True}\n]\nVG_CREATE_CMD = [\n {'cmd': ['vgcreate', '%VOLUME_GROUP%', '%DEV%'],\n 'run_as_root': True}\n]\nVG_LVS_CMD = [\n {'cmd': ['lvs', '--noheadings', '-o', 'lv_name', '%VOLUME_GROUP%'],\n 'run_as_root': True}\n]\nVG_LVREMOVE_CMD = [\n {'cmd': ['lvremove', '-f', '%VOLUME_GROUP%/%LV%'],\n 'run_as_root': True}\n]\nRESTART_TGT_CMD = [\n {'cmd': ['stop', 'tgt'], 'run_as_root': True},\n {'cmd': ['start', 'tgt'], 'run_as_root': True}\n]\n\n# NCPU, NVOL, NAPI ... are here as possible subcomponents of nova\nNCPU = \"cpu\"\nNVOL = \"vol\"\nNAPI = \"api\"\nNOBJ = \"obj\"\nNNET = \"net\"\nNCERT = \"cert\"\nNSCHED = \"sched\"\nNCAUTH = \"cauth\"\nNXVNC = \"xvnc\"\nSUBCOMPONENTS = [NCPU, NVOL, NAPI,\n NOBJ, NNET, NCERT, NSCHED, NCAUTH, NXVNC]\n\n#the pkg json files nova requires for installation\nREQ_PKGS = ['general.json', 'nova.json']\n\n# Additional packages for subcomponents\nADD_PKGS = {\n NAPI:\n [\n 'n-api.json',\n ],\n NCPU:\n [\n 'n-cpu.json',\n ],\n NVOL:\n [\n 'n-vol.json',\n ],\n}\n\n# Adjustments to nova paste pipeline for keystone\nPASTE_PIPELINE_KEYSTONE_ADJUST = {\n 'pipeline:ec2cloud': {'pipeline': 'ec2faultwrap logrequest totoken authtoken keystonecontext cloudrequest authorizer ec2executor'},\n 'pipeline:ec2admin': {'pipeline': \"ec2faultwrap logrequest totoken authtoken keystonecontext adminrequest authorizer ec2executor\"},\n 'pipeline:openstack_compute_api_v2': {'pipeline': \"faultwrap authtoken keystonecontext ratelimit osapi_compute_app_v2\"},\n 'pipeline:openstack_volume_api_v1': {'pipeline': \"faultwrap authtoken keystonecontext ratelimit osapi_volume_app_v1\"},\n 'pipeline:openstack_api_v2': {'pipeline': 'faultwrap authtoken keystonecontext ratelimit osapi_app_v2'},\n}\n\n# What to start\nAPP_OPTIONS = {\n #these are currently the core components/applications\n 'nova-api': ['--flagfile', '%CFGFILE%'],\n 'nova-compute': ['--flagfile', '%CFGFILE%'],\n 'nova-volume': ['--flagfile', '%CFGFILE%'],\n 'nova-network': ['--flagfile', '%CFGFILE%'],\n 'nova-scheduler': ['--flagfile', '%CFGFILE%'],\n 'nova-cert': ['--flagfile', '%CFGFILE%'],\n 'nova-objectstore': ['--flagfile', '%CFGFILE%'],\n 'nova-consoleauth': [],\n 'nova-xvpvncproxy': ['--flagfile', '%CFGFILE%'],\n}\n\n# Sub component names to actual app names (matching previous dict)\nSUB_COMPONENT_NAME_MAP = {\n NCPU: 'nova-compute',\n NVOL: 'nova-volume',\n NAPI: 'nova-api',\n NOBJ: 'nova-objectstore',\n NNET: 'nova-network',\n NCERT: 'nova-cert',\n NSCHED: 'nova-scheduler',\n NCAUTH: 'nova-consoleauth',\n NXVNC: 'nova-xvpvncproxy',\n}\n\n#subdirs of the checkout/download\nBIN_DIR = 'bin'\n\n#These are used by NovaConf\nQUANTUM_MANAGER = 'nova.network.quantum.manager.QuantumManager'\nNET_MANAGER_TEMPLATE = 'nova.network.manager.%s'\nDEF_IMAGE_SERVICE = 'nova.image.glance.GlanceImageService'\nDEF_SCHEDULER = 'nova.scheduler.simple.SimpleScheduler'\nDEF_GLANCE_PORT = 9292\n\n#only turned on if vswitch enabled\nQUANTUM_OPENSWITCH_OPS = {\n 'libvirt_vif_type': 'ethernet',\n 'libvirt_vif_driver': 'nova.virt.libvirt.vif.LibvirtOpenVswitchDriver',\n 'linuxnet_interface_driver': 'nova.network.linux_net.LinuxOVSInterfaceDriver',\n 'quantum_use_dhcp': None,\n}\n\n#this is a special conf\nCLEANER_DATA_CONF = 'clean_iptables.sh'\nCLEANER_CMD_ROOT = [sh.joinpths(\"/\", \"bin\", 'bash')]\n\n#pip files that nova requires\nREQ_PIPS = ['general.json', 'nova.json']\n\n\nclass NovaUninstaller(comp.PythonUninstallComponent):\n def __init__(self, *args, **kargs):\n comp.PythonUninstallComponent.__init__(self, TYPE, *args, **kargs)\n self.bindir = sh.joinpths(self.appdir, BIN_DIR)\n\n def pre_uninstall(self):\n self._clear_iptables()\n self._clear_libvirt_domains()\n\n def _clear_iptables(self):\n LOG.info(\"Cleaning up iptables.\")\n cmd = CLEANER_CMD_ROOT + [sh.joinpths(self.bindir, CLEANER_DATA_CONF)]\n sh.execute(*cmd, run_as_root=True)\n\n def _clear_libvirt_domains(self):\n virt_driver = self.cfg.get('nova', 'virt_driver')\n if virt_driver == virsh.VIRT_TYPE:\n inst_prefix = self.cfg.get('nova', 'instance_name_prefix')\n libvirt_type = virsh.default(self.cfg.get('nova', 'libvirt_type'))\n virsh.clear_libvirt_domains(libvirt_type, inst_prefix)\n\n\nclass NovaInstaller(comp.PythonInstallComponent):\n def __init__(self, *args, **kargs):\n comp.PythonInstallComponent.__init__(self, TYPE, *args, **kargs)\n self.bindir = sh.joinpths(self.appdir, BIN_DIR)\n self.paste_conf_fn = self._get_target_config_name(PASTE_CONF)\n self.volumes_enabled = False\n if not self.component_opts or NVOL in self.component_opts:\n self.volumes_enabled = True\n\n def _get_pkgs(self):\n pkgs = list(REQ_PKGS)\n sub_components = self.component_opts or SUBCOMPONENTS\n for c in sub_components:\n fns = ADD_PKGS.get(c)\n if fns:\n pkgs.extend(fns)\n return pkgs\n\n def _get_symlinks(self):\n return {sh.joinpths(self.cfgdir, API_CONF): '/etc/nova/nova.conf'}\n\n def _get_pips(self):\n return list(REQ_PIPS)\n\n def _get_download_locations(self):\n places = list()\n places.append({\n 'uri': (\"git\", \"nova_repo\"),\n 'branch': (\"git\", \"nova_branch\"),\n })\n return places\n\n def warm_configs(self):\n pws = ['rabbit']\n for pw_key in pws:\n self.cfg.get(\"passwords\", pw_key)\n\n def _get_config_files(self):\n return list(CONFIGS)\n\n def _setup_network(self):\n LOG.info(\"Creating your nova network to be used with instances.\")\n mp = dict()\n mp['BINDIR'] = self.bindir\n mp['CFGFILE'] = sh.joinpths(self.cfgdir, API_CONF)\n mp['FLOATING_RANGE'] = self.cfg.get('nova', 'floating_range')\n mp['TEST_FLOATING_RANGE'] = self.cfg.get('nova', 'test_floating_range')\n mp['TEST_FLOATING_POOL'] = self.cfg.get('nova', 'test_floating_pool')\n mp['FIXED_NETWORK_SIZE'] = self.cfg.get('nova', 'fixed_network_size')\n mp['FIXED_RANGE'] = self.cfg.get('nova', 'fixed_range')\n if settings.QUANTUM in self.instances:\n cmds = NETWORK_SETUP_CMDS[0:1]\n else:\n cmds = NETWORK_SETUP_CMDS\n utils.execute_template(*cmds, params=mp, tracewriter=self.tracewriter)\n\n def _sync_db(self):\n LOG.info(\"Syncing the database with nova.\")\n mp = dict()\n mp['BINDIR'] = self.bindir\n mp['CFGFILE'] = sh.joinpths(self.cfgdir, API_CONF)\n utils.execute_template(*DB_SYNC_CMD, params=mp, tracewriter=self.tracewriter)\n\n def post_install(self):\n comp.PkgInstallComponent.post_install(self)\n #extra actions to do nova setup\n self._setup_db()\n self._sync_db()\n self._setup_network()\n self._setup_cleaner()\n # check if we need to do the vol subcomponent\n if self.volumes_enabled:\n self._setup_vol_groups()\n\n def _setup_cleaner(self):\n LOG.info(\"Configuring cleaner template %s.\", CLEANER_DATA_CONF)\n (_, contents) = utils.load_template(self.component_name, CLEANER_DATA_CONF)\n tgt_fn = sh.joinpths(self.bindir, CLEANER_DATA_CONF)\n sh.write_file(tgt_fn, contents)\n\n def _setup_db(self):\n LOG.info(\"Fixing up database named %s.\", DB_NAME)\n db.drop_db(self.cfg, DB_NAME)\n db.create_db(self.cfg, DB_NAME)\n\n def _setup_vol_groups(self):\n LOG.info(\"Attempting to setup volume groups for nova volume management.\")\n mp = dict()\n backing_file = self.cfg.get('nova', 'volume_backing_file')\n # check if we need to have a default backing file\n if not backing_file:\n backing_file = sh.joinpths(self.appdir, 'nova-volumes-backing-file')\n vol_group = self.cfg.get('nova', 'volume_group')\n backing_file_size = utils.to_bytes(self.cfg.get('nova', 'volume_backing_file_size'))\n mp['VOLUME_GROUP'] = vol_group\n mp['VOLUME_BACKING_FILE'] = backing_file\n mp['VOLUME_BACKING_FILE_SIZE'] = backing_file_size\n try:\n utils.execute_template(*VG_CHECK_CMD, params=mp)\n LOG.warn(\"Volume group already exists: %s\" % (vol_group))\n except exceptions.ProcessExecutionError as err:\n # Check that the error from VG_CHECK is an expected error\n if err.exit_code != 5:\n raise\n LOG.info(\"Need to create volume group: %s\" % (vol_group))\n sh.touch_file(backing_file, die_if_there=False, file_size=backing_file_size)\n vg_dev_result = utils.execute_template(*VG_DEV_CMD, params=mp)\n LOG.debug(\"vg dev result:%s\" % (vg_dev_result))\n # Strip the newlines out of the stdout (which is in the first\n # element of the first (and only) tuple in the response\n mp['DEV'] = vg_dev_result[0][0].replace('\\n', '')\n utils.execute_template(*VG_CREATE_CMD, params=mp, tracewriter=self.tracewriter)\n # One way or another, we should have the volume group, Now check the\n # logical volumes\n self._process_lvs(mp)\n # Finish off by restarting tgt, and ignore any errors\n utils.execute_template(*RESTART_TGT_CMD, check_exit_code=False, tracewriter=self.tracewriter)\n\n def _process_lvs(self, mp):\n LOG.info(\"Attempting to setup logical volumes for nova volume management.\")\n lvs_result = utils.execute_template(*VG_LVS_CMD, params=mp, tracewriter=self.tracewriter)\n LOG.debug(\"lvs result: %s\" % (lvs_result))\n vol_name_prefix = self.cfg.get('nova', 'volume_name_prefix')\n LOG.debug(\"Using volume name prefix: %s\" % (vol_name_prefix))\n for stdout_line in lvs_result[0][0].split('\\n'):\n if stdout_line:\n # Ignore blank lines\n LOG.debug(\"lvs output line:%s\" % (stdout_line))\n if stdout_line.startswith(vol_name_prefix):\n # TODO still need to implement the following:\n # tid=`egrep \"^tid.+$lv\" /proc/net/iet/volume | cut -f1 -d' ' | tr ':' '='`\n # if [[ -n \"$tid\" ]]; then\n # lun=`egrep \"lun.+$lv\" /proc/net/iet/volume | cut -f1 -d' ' | tr ':' '=' | tr -d '\\t'`\n # sudo ietadm --op delete --$tid --$lun\n # fi\n # sudo lvremove -f $VOLUME_GROUP/$lv\n raise exceptions.StackException(\"lvs magic not yet implemented\")\n mp['LV'] = stdout_line\n utils.execute_template(*VG_LVREMOVE_CMD, params=mp, tracewriter=self.tracewriter)\n\n def _generate_nova_conf(self):\n LOG.info(\"Generating dynamic content for nova configuration (%s).\" % (API_CONF))\n component_dirs = dict()\n component_dirs['app'] = self.appdir\n component_dirs['cfg'] = self.cfgdir\n component_dirs['bin'] = self.bindir\n conf_gen = NovaConfigurator(self)\n nova_conf = conf_gen.configure(component_dirs)\n tgtfn = self._get_target_config_name(API_CONF)\n LOG.info(\"Writing nova configuration to %s\" % (tgtfn))\n LOG.debug(nova_conf)\n self.tracewriter.make_dir(sh.dirname(tgtfn))\n sh.write_file(tgtfn, nova_conf)\n self.tracewriter.cfg_write(tgtfn)\n\n def _config_adjust(self, contents, config_fn):\n if config_fn == PASTE_CONF and settings.KEYSTONE in self.instances:\n newcontents = contents\n with io.BytesIO(contents) as stream:\n config = cfg.IgnoreMissingConfigParser()\n config.readfp(stream)\n mods = 0\n for section in PASTE_PIPELINE_KEYSTONE_ADJUST.keys():\n if config.has_section(section):\n section_vals = PASTE_PIPELINE_KEYSTONE_ADJUST.get(section)\n for (k, v) in section_vals.items():\n config.set(section, k, v)\n mods += 1\n if mods > 0:\n with io.BytesIO() as outputstream:\n config.write(outputstream)\n outputstream.flush()\n newcontents = cfg.add_header(config_fn, outputstream.getvalue())\n contents = newcontents\n return contents\n\n def _get_source_config(self, config_fn):\n if config_fn == PASTE_CONF:\n #this is named differently than what it will be stored as... arg...\n srcfn = sh.joinpths(self.appdir, \"etc\", \"nova\", 'api-paste.ini')\n contents = sh.load_file(srcfn)\n return (srcfn, contents)\n else:\n return comp.PythonInstallComponent._get_source_config(self, config_fn)\n\n def _get_target_config_name(self, config_fn):\n if config_fn == PASTE_CONF:\n #TODO Don't put nova-api-paste.ini in bin?\n return sh.joinpths(self.appdir, \"bin\", 'nova-api-paste.ini')\n else:\n return comp.PythonInstallComponent._get_target_config_name(self, config_fn)\n\n def _get_param_map(self, config_fn):\n return keystone.get_shared_params(self.cfg)\n\n def configure(self):\n am = comp.PythonInstallComponent.configure(self)\n #this is a special conf so we handle it ourselves\n self._generate_nova_conf()\n return am + 1\n\n\nclass NovaRuntime(comp.PythonRuntime):\n def __init__(self, *args, **kargs):\n comp.PythonRuntime.__init__(self, TYPE, *args, **kargs)\n\n def _get_apps_to_start(self):\n result = list()\n if not self.component_opts:\n apps = sorted(APP_OPTIONS.keys())\n for app_name in apps:\n result.append({\n 'name': app_name,\n 'path': sh.joinpths(self.appdir, BIN_DIR, app_name),\n })\n else:\n for short_name in self.component_opts:\n full_name = SUB_COMPONENT_NAME_MAP.get(short_name)\n if full_name and full_name in APP_OPTIONS:\n result.append({\n 'name': full_name,\n 'path': sh.joinpths(self.appdir, BIN_DIR, full_name),\n })\n return result\n\n def pre_start(self):\n virt_driver = self.cfg.get('nova', 'virt_driver')\n if virt_driver == virsh.VIRT_TYPE:\n virt_type = virsh.default(self.cfg.get('nova', 'libvirt_type'))\n LOG.info(\"Checking that your selected libvirt virtualization type [%s] is working and running.\" % (virt_type))\n if not virsh.virt_ok(virt_type, self.distro):\n msg = (\"Libvirt type %s for distro %s does not seem to be active or configured correctly, \"\n \"perhaps you should be using %s instead.\" % (virt_type, self.distro, virsh.DEFAULT_VIRT))\n raise exceptions.StartException(msg)\n virsh.restart(self.distro)\n\n def _get_param_map(self, app_name):\n params = comp.PythonRuntime._get_param_map(self, app_name)\n params['CFGFILE'] = sh.joinpths(self.cfgdir, API_CONF)\n return params\n\n def _get_app_options(self, app):\n return APP_OPTIONS.get(app)\n\n\n# This class has the smarts to build the configuration file based on\n# various runtime values. A useful reference for figuring out this\n# is at http://docs.openstack.org/diablo/openstack-compute/admin/content/ch_configuring-openstack-compute.html\nclass NovaConfigurator(object):\n def __init__(self, nc):\n self.cfg = nc.cfg\n self.instances = nc.instances\n self.component_root = nc.component_root\n self.appdir = nc.appdir\n self.tracewriter = nc.tracewriter\n self.paste_conf_fn = nc.paste_conf_fn\n self.distro = nc.distro\n self.volumes_enabled = False\n self.xvnc_enabled = False\n if not nc.component_opts or NVOL in nc.component_opts:\n self.volumes_enabled = True\n # TBD, xvnc is a subcomponent of Nova and not of novnc?\n if not nc.component_opts or NXVNC in nc.component_opts:\n self.xvnc_enabled = True\n\n def _getbool(self, name):\n return self.cfg.getboolean('nova', name)\n\n def _getstr(self, name):\n return self.cfg.get('nova', name)\n\n def configure(self, component_dirs):\n nova_conf = NovaConf()\n\n #use more than once\n hostip = self.cfg.get('host', 'ip')\n\n #verbose on?\n if self._getbool('verbose'):\n nova_conf.add_simple('verbose')\n\n #allow the admin api?\n if self._getbool('allow_admin_api'):\n nova_conf.add_simple('allow_admin_api')\n\n #which scheduler do u want?\n scheduler = self._getstr('scheduler')\n if not scheduler:\n scheduler = DEF_SCHEDULER\n nova_conf.add('scheduler_driver', scheduler)\n\n #setup network settings\n self._configure_network_settings(nova_conf, component_dirs)\n\n #setup nova volume settings\n if self.volumes_enabled:\n self._configure_vols(nova_conf)\n\n #where we are running\n nova_conf.add('my_ip', hostip)\n\n #setup your sql connection\n nova_conf.add('sql_connection', self.cfg.get_dbdsn('nova'))\n\n #configure anything libvirt releated?\n virt_driver = self._getstr('virt_driver')\n if virt_driver == virsh.VIRT_TYPE:\n libvirt_type = virsh.default(self._getstr('libvirt_type'))\n self._configure_libvirt(libvirt_type, nova_conf)\n\n #how instances will be presented\n instance_template = self._getstr('instance_name_prefix') + self._getstr('instance_name_postfix')\n nova_conf.add('instance_name_template', instance_template)\n\n #???\n nova_conf.add('osapi_compute_extension', 'nova.api.openstack.compute.contrib.standard_extensions')\n\n #vnc settings\n self._configure_vnc(nova_conf)\n\n #where our paste config is\n nova_conf.add('api_paste_config', self.paste_conf_fn)\n\n #what our imaging service will be\n self._configure_image_service(nova_conf)\n\n #ec2 / s3 stuff\n ec2_dmz_host = self._getstr('ec2_dmz_host')\n if not ec2_dmz_host:\n ec2_dmz_host = hostip\n nova_conf.add('ec2_dmz_host', ec2_dmz_host)\n nova_conf.add('s3_host', hostip)\n\n #how is your rabbit setup?\n nova_conf.add('rabbit_host', self.cfg.get('default', 'rabbit_host'))\n nova_conf.add('rabbit_password', self.cfg.get(\"passwords\", \"rabbit\"))\n\n #where instances will be stored\n instances_path = self._getstr('instances_path')\n if not instances_path:\n instances_path = sh.joinpths(self.component_root, 'instances')\n self._configure_instances_path(instances_path, nova_conf)\n\n #is this a multihost setup?\n self._configure_multihost(nova_conf)\n\n #enable syslog??\n self._configure_syslog(nova_conf)\n\n #handle any virt driver specifics\n self._configure_virt_driver(nova_conf)\n\n #now make it\n conf_lines = sorted(nova_conf.generate())\n complete_file = utils.joinlinesep(*conf_lines)\n\n #add any extra flags in?\n extra_flags = self._getstr('extra_flags')\n if extra_flags:\n full_file = [complete_file, extra_flags]\n complete_file = utils.joinlinesep(*full_file)\n\n return complete_file\n\n def _configure_image_service(self, nova_conf):\n #what image service we will use\n img_service = self._getstr('img_service')\n if not img_service:\n img_service = DEF_IMAGE_SERVICE\n nova_conf.add('image_service', img_service)\n\n #where is glance located?\n if img_service.lower().find(\"glance\") != -1:\n glance_api_server = self._getstr('glance_server')\n if not glance_api_server:\n glance_api_server = \"%s:%d\" % (self.cfg.get('host', 'ip'),\n DEF_GLANCE_PORT)\n nova_conf.add('glance_api_servers', glance_api_server)\n\n def _configure_vnc(self, nova_conf):\n if settings.NOVNC in self.instances:\n vncproxy_url = self._getstr('vncproxy_url')\n nova_conf.add('novncproxy_base_url', vncproxy_url)\n\n if self.xvnc_enabled:\n nova_conf.add('xvpvncproxy_base_url', self._getstr('xvpvncproxy_url'))\n nova_conf.add('vncserver_listen', self._getstr('vncserver_listen'))\n vncserver_proxyclient_address = self._getstr('vncserver_proxyclient_addres')\n\n # If no vnc proxy address was specified, pick a default based on which\n # driver we're using\n virt_driver = self._getstr('virt_driver')\n if not vncserver_proxyclient_address:\n if virt_driver == 'xenserver':\n vncserver_proxyclient_address = '169.254.0.1'\n else:\n vncserver_proxyclient_address = '127.0.0.1'\n\n nova_conf.add('vncserver_proxyclient_address', vncserver_proxyclient_address)\n\n def _configure_vols(self, nova_conf):\n nova_conf.add('volume_group', self._getstr('volume_group'))\n volume_name_template = self._getstr('volume_name_prefix') + self._getstr('volume_name_postfix')\n nova_conf.add('volume_name_template', volume_name_template)\n nova_conf.add('iscsi_help', 'tgtadm')\n\n def _configure_network_settings(self, nova_conf, component_dirs):\n if settings.QUANTUM in self.instances:\n nova_conf.add('network_manager', QUANTUM_MANAGER)\n nova_conf.add('quantum_connection_host', self.cfg.get('quantum', 'q_host'))\n nova_conf.add('quantum_connection_port', self.cfg.get('quantum', 'q_port'))\n if self.cfg.get('quantum', 'q_plugin') == 'openvswitch':\n for (key, value) in QUANTUM_OPENSWITCH_OPS.items():\n if value is None:\n nova_conf.add_simple(key)\n else:\n nova_conf.add(key, value)\n if settings.MELANGE_CLIENT in self.instances:\n nova_conf.add('quantum_ipam_lib', 'nova.network.quantum.melange_ipam_lib')\n nova_conf.add_simple('use_melange_mac_generation')\n nova_conf.add('melange_host', self.cfg.get('melange', 'm_host'))\n nova_conf.add('melange_port', self.cfg.get('melange', 'm_port'))\n else:\n nova_conf.add('network_manager', NET_MANAGER_TEMPLATE % (self._getstr('network_manager')))\n\n #dhcp bridge stuff???\n flag_conf_fn = sh.joinpths(component_dirs.get('cfg'), API_CONF)\n nova_conf.add('dhcpbridge_flagfile', flag_conf_fn)\n\n #Network prefix for the IP network that all the projects for future VM guests reside on. Example: 192.168.0.0/12\n nova_conf.add('fixed_range', self._getstr('fixed_range'))\n\n # The value for vlan_interface may default to the the current value\n # of public_interface. We'll grab the value and keep it handy.\n public_interface = self._getstr('public_interface')\n vlan_interface = self._getstr('vlan_interface')\n if not vlan_interface:\n vlan_interface = public_interface\n\n #do a little check to make sure actually have that interface set...\n known_interfaces = utils.get_interfaces()\n if not public_interface in known_interfaces:\n msg = \"Public interface %s is not a known interface\" % (public_interface)\n raise exceptions.ConfigException(msg)\n if not vlan_interface in known_interfaces:\n msg = \"VLAN interface %s is not a known interface\" % (vlan_interface)\n raise exceptions.ConfigException(msg)\n nova_conf.add('public_interface', public_interface)\n nova_conf.add('vlan_interface', vlan_interface)\n\n #This forces dnsmasq to update its leases table when an instance is terminated.\n nova_conf.add_simple('force_dhcp_release')\n\n def _configure_syslog(self, nova_conf):\n if self.cfg.getboolean('default', 'syslog'):\n nova_conf.add_simple('use_syslog')\n\n def _configure_multihost(self, nova_conf):\n if self._getbool('multi_host'):\n nova_conf.add_simple('multi_host')\n nova_conf.add_simple('send_arp_for_ha')\n\n def _configure_instances_path(self, instances_path, nova_conf):\n nova_conf.add('instances_path', instances_path)\n LOG.debug(\"Attempting to create instance directory: %s\" % (instances_path))\n self.tracewriter.make_dir(instances_path)\n LOG.debug(\"Adjusting permissions of instance directory: %s\" % (instances_path))\n os.chmod(instances_path, stat.S_IRWXO | stat.S_IRWXG | stat.S_IRWXU)\n\n def _configure_libvirt(self, virt_type, nova_conf):\n if virt_type == 'lxc':\n #TODO need to add some goodies here\n pass\n nova_conf.add('libvirt_type', virt_type)\n\n #configures any virt driver settings\n def _configure_virt_driver(self, nova_conf):\n driver = self._getstr('virt_driver')\n drive_canon = driver.lower().strip()\n if drive_canon == 'xenserver':\n nova_conf.add('connection_type', 'xenapi')\n nova_conf.add('xenapi_connection_url', 'http://169.254.0.1')\n nova_conf.add('xenapi_connection_username', 'root')\n nova_conf.add('xenapi_connection_password', self.cfg.get(\"passwords\", \"xenapi_connection\"))\n nova_conf.add_simple('noflat_injected')\n nova_conf.add('flat_interface', 'eth1')\n nova_conf.add('firewall_driver', self._getstr('xen_firewall_driver'))\n nova_conf.add('flat_network_bridge', 'xapi1')\n else:\n nova_conf.add('connection_type', 'libvirt')\n nova_conf.add('firewall_driver', self._getstr('libvirt_firewall_driver'))\n nova_conf.add('flat_network_bridge', self._getstr('flat_network_bridge'))\n flat_interface = self._getstr('flat_interface')\n if flat_interface:\n nova_conf.add('flat_interface', flat_interface)\n\n\n# This class represents the data in the nova config file\nclass NovaConf(object):\n def __init__(self):\n self.lines = list()\n\n def add_list(self, key, *params):\n self.lines.append({'key': key, 'options': params})\n LOG.debug(\"Added nova conf key %s with values [%s]\" % (key, \",\".join(params)))\n\n def add_simple(self, key):\n self.lines.append({'key': key, 'options': None})\n LOG.debug(\"Added nova conf key %s\" % (key))\n\n def add(self, key, value):\n self.lines.append({'key': key, 'options': [value]})\n LOG.debug(\"Added nova conf key %s with value [%s]\" % (key, value))\n\n def _form_key(self, key, has_opts):\n key_str = \"--\" + str(key)\n if has_opts:\n key_str += \"=\"\n return key_str\n\n def generate(self, param_dict=None):\n gen_lines = list()\n for line_entry in self.lines:\n key = line_entry.get('key')\n opts = line_entry.get('options')\n if not key:\n continue\n if opts is None:\n key_str = self._form_key(key, False)\n full_line = key_str\n else:\n key_str = self._form_key(key, True)\n filled_opts = list()\n for opt in opts:\n filled_opts.append(utils.param_replace(str(opt), param_dict))\n full_line = key_str + \",\".join(filled_opts)\n gen_lines.append(full_line)\n return gen_lines\n\n\ndef describe(opts=None):\n description = \"\"\"\n Module: {module_name}\n Description:\n {description}\n Component options:\n {component_opts}\n\"\"\"\n params = dict()\n params['component_opts'] = \"TBD\"\n params['module_name'] = __name__\n params['description'] = __doc__ or \"Handles actions for the nova component.\"\n out = description.format(**params)\n return out.strip(\"\\n\")\n","sub_path":"devstack/components/nova.py","file_name":"nova.py","file_ext":"py","file_size_in_byte":30235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"11721327","text":"# Copyright 2015 Rackspace Hosting\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.\nimport mock\nimport webob.exc\n\nfrom wafflehaus.resource_filter import block_resource\nfrom wafflehaus import tests\n\n\nclass TestResourceFilter(tests.TestCase):\n def setUp(self):\n self.app = mock.Mock()\n\n self.simple_conf1 = {'resource': 'PoST /widget', 'enabled': 'true'}\n self.simple_conf2 = {'resource': 'PoSt GeT /widget', 'enabled': 'true'}\n self.multi_conf = {'resource': 'post GET /widget, GET posT /derp',\n 'enabled': 'true'}\n self.collapse_conf = {'resource': 'posT /widget, GET /widget',\n 'enabled': 'true'}\n self.complex_conf = {'resource': 'posT /widget/{id}/sub/{sub_id}',\n 'enabled': 'true'}\n self.format_conf1 = {'resource': 'POST /widget{.format:json|xml}',\n 'enabled': 'true'}\n\n def test_default_instance_create_simple(self):\n result = block_resource.filter_factory(self.simple_conf1)(self.app)\n self.assertIsNotNone(result)\n self.assertTrue(hasattr(result, 'resources'))\n self.assertTrue(isinstance(result.resources, dict))\n self.assertEqual(1, len(result.resources))\n resources = result.resources\n self.assertTrue('/widget' in resources)\n self.assertEqual(1, len(resources['/widget']))\n\n def test_default_instance_create_simple_multi_method(self):\n result = block_resource.filter_factory(self.simple_conf2)(self.app)\n resources = result.resources\n widget = resources['/widget']\n self.assertEqual(2, len(widget))\n self.assertTrue('POST' in widget)\n self.assertTrue('GET' in widget)\n\n def test_default_instance_create_multi(self):\n result = block_resource.filter_factory(self.multi_conf)(self.app)\n resources = result.resources\n self.assertEqual(2, len(resources))\n for k, res in resources.iteritems():\n self.assertEqual(2, len(res))\n self.assertTrue('POST' in res)\n self.assertTrue('GET' in res)\n\n def test_default_instance_collapse(self):\n result = block_resource.filter_factory(self.collapse_conf)(self.app)\n resources = result.resources\n self.assertEqual(1, len(resources))\n widget = resources['/widget']\n self.assertEqual(2, len(widget))\n self.assertTrue('POST' in widget)\n self.assertTrue('GET' in widget)\n\n def test_match_route(self):\n result = block_resource.filter_factory(self.simple_conf1)(self.app)\n resp = result.__call__.request('/widget', method='POST')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n\n def test_match_formatted_route1(self):\n result = block_resource.filter_factory(self.format_conf1)(self.app)\n resp = result.__call__.request('/cog', method='POST')\n self.assertEqual(self.app, resp)\n\n resp = result.__call__.request('/widget', method='POST')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n resp = result.__call__.request('/widget', method='PUT')\n self.assertEqual(self.app, resp)\n\n resp = result.__call__.request('/widget.json', method='POST')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n resp = result.__call__.request('/widget.json', method='PUT')\n self.assertEqual(self.app, resp)\n\n resp = result.__call__.request('/widget.xml', method='POST')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n resp = result.__call__.request('/widget.xml', method='PUT')\n self.assertEqual(self.app, resp)\n\n resp = result.__call__.request('/widget.derp', method='POST')\n self.assertEqual(self.app, resp)\n resp = result.__call__.request('/widget.derp', method='PUT')\n self.assertEqual(self.app, resp)\n\n def test_match_multi_route(self):\n result = block_resource.filter_factory(self.multi_conf)(self.app)\n resp = result.__call__.request('/widget', method='POST')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n resp = result.__call__.request('/derp', method='POST')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n resp = result.__call__.request('/widget', method='GET')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n resp = result.__call__.request('/derp', method='GET')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n resp = result.__call__.request('/widget', method='PUT')\n self.assertEqual(self.app, resp)\n resp = result.__call__.request('/derp', method='PUT')\n self.assertEqual(self.app, resp)\n\n def test_match_complex_route(self):\n result = block_resource.filter_factory(self.complex_conf)(self.app)\n resp = result.__call__.request('/widget', method='POST')\n self.assertEqual(self.app, resp)\n resp = result.__call__.request('/widget/1234/sub/1234', method='POST')\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n\n def test_fail_to_match_route(self):\n result = block_resource.filter_factory(self.simple_conf1)(self.app)\n resp = result.__call__.request('/willfail', method='POST')\n self.assertEqual(self.app, resp)\n\n def test_fail_to_match_method(self):\n result = block_resource.filter_factory(self.simple_conf1)(self.app)\n resp = result.__call__.request('/widget', method='GET')\n self.assertEqual(self.app, resp)\n\n def test_override_runtime(self):\n self.set_reconfigure()\n result = block_resource.filter_factory(self.simple_conf1)(self.app)\n headers = {'X_WAFFLEHAUS_BLOCKRESOURCE_ENABLED': False}\n resp = result.__call__.request('/widget', method='POST',\n headers=headers)\n self.assertEqual(self.app, resp)\n headers = {'X_WAFFLEHAUS_BLOCKRESOURCE_ENABLED': True}\n resp = result.__call__.request('/widget', method='POST',\n headers=headers)\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n headers = {'X_WAFFLEHAUS_BLOCKRESOURCE_RESOURCE': 'GET /derp'}\n resp = result.__call__.request('/widget', method='POST',\n headers=headers)\n self.assertEqual(self.app, resp)\n resp = result.__call__.request('/derp', method='GET',\n headers=headers)\n self.assertTrue(isinstance(resp, webob.exc.HTTPException))\n","sub_path":"wafflehaus/tests/test_resource_filter.py","file_name":"test_resource_filter.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"226019897","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n load data\n build CNN\n\"\"\"\n\nimport os\nimport keras\nfrom keras.preprocessing import image\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Activation\nfrom keras.layers import Conv2D, MaxPooling2D\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\n\n\nimport config\n\n\ndef load_data(data_dir):\n \"\"\"\n load data\n dataset from:\n - traing data:https://btsd.ethz.ch/shareddata/BelgiumTSC/BelgiumTSC_Training.zip\n - test data:https://btsd.ethz.ch/shareddata/BelgiumTSC/BelgiumTSC_Testing.zip\n IrfanView for ppm view:https://www.irfanview.com/\n \"\"\"\n # gain all subdirectory,every subdirectory as one label\n directories = [d for d in os.listdir(data_dir)\n if os.path.isdir(os.path.join(data_dir, d))]\n labels = []\n images = []\n for d in directories:\n label_dir = os.path.join(data_dir, d)\n file_names = [os.path.join(label_dir, f)\n for f in os.listdir(label_dir)\n if f.endswith('.ppm')]\n for f in file_names:\n # read data by fixed \n image_data = image.load_img(f, target_size=(config.img_rows, config.img_cols))\n # pixel value change to 0-1\n image_data = image.img_to_array(image_data) / 255\n images.append(image_data)\n labels.append(int(d))\n\n print('{} numbers of data be loaded '.format(len(images)))\n # display all classes display\n plt.figure(figsize=(15, 8))\n sns.countplot(pd.Series(labels))\n plt.show()\n\n return images, labels\n\n\ndef display_traffic_signs(images, labels):\n \"\"\"\n show data from all classes\n \"\"\"\n # obtain class\n unique_labels = set(labels)\n\n plt.figure(figsize=(10, 10))\n for i, label in enumerate(unique_labels):\n # select the first image in every class\n image_data = images[labels.index(label)]\n plt.subplot(8, 8, i + 1)\n plt.axis('off')\n # label,sample numbers in this class\n plt.title('Label {0} ({1})'.format(label, labels.count(label)))\n plt.imshow(image_data)\n plt.tight_layout()\n plt.show()\n\n\ndef process_data(images, labels):\n \"\"\"\n process loaded data and label, as CNN input\n \"\"\"\n X = np.array(images)\n y = np.array(labels)\n y = keras.utils.to_categorical(y, config.n_classes)\n\n return X, y\n\n\ndef build_cnn():\n \"\"\"\n CNN structure\n \"\"\"\n print('build CNN')\n input_shape = (config.img_rows, config.img_cols, 3)\n model = Sequential()\n\n # First layer\n model.add(Conv2D(filters=32, kernel_size=(3, 3), padding='same', input_shape=input_shape))\n model.add(Activation('relu'))\n model.add(MaxPooling2D((2, 2)))\n model.add(Dropout(0.25))\n\n # Second layer\n model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same'))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n # Dense\n model.add(Flatten())\n model.add(Dense(512))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(config.n_classes))\n model.add(Activation('softmax'))\n\n # compile model\n model.compile(loss='categorical_crossentropy',\n optimizer=keras.optimizers.Adam(),\n metrics=['accuracy'])\n\n print(model.summary())\n\n return model\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"6632782","text":"# Write a Python file that uploads an image to your \n# Twitter account. Make sure to use the \n# hashtags #UMSI-206 #Proj3 in the tweet.\n# You will demo this live for grading.\n\nprint(\"\"\"No output necessary although you \n\tcan print out a success/failure message if you want to.\"\"\")\n\n\nimport tweepy\nfrom textblob import TextBlob\n\n# Unique code from Twitter\ntwit_id = \"4777211295\"\naccess_token = \"4777211295-b0EzLQuPyL68ZCJhxe5PTmZVjwV5wpGhfUFHOI4\" #may need to add \"id-\" in front\naccess_token_secret = \"lYVpTNH1LY9HuOBGFOqxhWL2iiGkYLCcqKwdfCPDWG6FB\"\nconsumer_key = \"cEUWMmiQJ3pZjzkGxtETlADgA\"\nconsumer_secret = \"EnqNijErzB5syABvJ7YQEws2qydkSVGfSvb1qh77AZQUmi3qwS\"\n\n# Boilerplate code here\nauth = tweepy.OAuthHandler(consumer_key,consumer_secret)\nauth.set_access_token(access_token,access_token_secret)\n\napi = tweepy.API(auth)\n#Now we can Create Tweets, Delete Tweets, and Find Twitter Users\n\nmessage = '#UMSI-206 #Proj3'\nfname = '206more.jpg'\n\napi.update_with_media(fname, status=message)\n\n#polarity -- measures how positive or negative\n#subjectivity -- measures how factual.\n\n#1 Sentiment Analysis - Understand and Extracting Feelings from Data\n","sub_path":"twitterhw3a.py","file_name":"twitterhw3a.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"463652528","text":"from django.contrib import admin\n\nfrom basket.models import (Basket, Line, DeliveryBasket,\n LineAttribute, StockReserve, BasketHistoryReserve,OldReserveLine,)\n\n\nclass LineInline(admin.TabularInline):\n model = Line\n readonly_fields = ('line_reference', 'product', 'price_excl_tax',\n 'price_incl_tax', 'price_currency', 'stockrecord')\n\n\nclass LineAdmin(admin.ModelAdmin):\n list_display = ('id', 'basket', 'product', 'stockrecord', 'quantity',\n 'price_excl_tax', 'price_currency', 'date_created')\n readonly_fields = ('basket', 'stockrecord', 'line_reference', 'product',\n 'price_currency', 'price_incl_tax', 'price_excl_tax',\n 'quantity')\n\n\nclass BasketAdmin(admin.ModelAdmin):\n list_display = ('id', 'owner', 'status', 'num_lines',\n 'date_created', 'date_submitted',\n 'time_before_submit')\n readonly_fields = ('owner', 'date_merged', 'date_submitted')\n inlines = [LineInline]\n\n\nclass LineReserveTimeAdmin(admin.ModelAdmin):\n list_display = ('basket', 'line', 'created_at', 'quantity')\n\n\nclass StockReserveAdmin(admin.ModelAdmin):\n list_display = ('line', 'start_reserve', 'end_reserve','is_active')\n readonly_fields = ('line',)\n\n\nclass BasketHistoryReserveAdmin(admin.ModelAdmin):\n list_display = ('basket','start_time','end_time', 'position')\n\n\nadmin.site.register(Basket, BasketAdmin)\nadmin.site.register(Line, LineAdmin)\nadmin.site.register(LineAttribute)\nadmin.site.register(DeliveryBasket)\nadmin.site.register(StockReserve, StockReserveAdmin)\nadmin.site.register(BasketHistoryReserve, BasketHistoryReserveAdmin)\nadmin.site.register(OldReserveLine)","sub_path":"basket/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"339475549","text":"# -*- coding: iso-8859-1 -*-\n#\n# Copyright (C) 2011 Mikael Relbe \n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at http://trac.edgewall.com/license.html.\n#\n# Author: Mikael Relbe \n\n\"\"\"Use boxes to give wiki pages a modern look.\n\"\"\"\nimport os\n\nfrom pkg_resources import resource_filename\n\nfrom trac.util.html import tag\n\nfrom trac.config import BoolOption, IntOption\nfrom trac.core import implements, Component, TracError\nfrom trac.util.compat import cleandoc\nfrom trac.util.translation import _\nfrom trac.web.api import IRequestFilter, IRequestHandler\nfrom trac.web.chrome import ITemplateProvider, add_stylesheet\nfrom trac.wiki import IWikiMacroProvider, format_to_html, parse_args\n\nfrom tracwikiextras.icons import Icons\nfrom tracwikiextras.util import sanitize_attrib\n\n\n# Urgency levels\nWARN = 0\nHIGHLIGHT = 1\nELABORATE = 2\nNEWS = 3\nNORMAL = 4\n\n\nclass Boxes(Component):\n \"\"\"WikiProcessors for inserting boxes in a wiki page.\n\n Four processors are defined for creating boxes:\n * `box` -- The core box processor.\n * `rbox` (`lbox`) -- Display a right (left) aligned box to show\n side notes and warnings etc. This will probably be the most\n used box.\n * `newsbox` -- Display news in a right aligned box. ''(This box\n corresponds to the well-known ''`NewsFlash`'' macro.)''\n * `imagebox` -- Display a single image with caption in a centered box.\n\n The visual appearance of `box`, `rbox` and `lbox` is set by a\n `type` parameter, which comes in a dozen or so flavors to call for\n attention in an appropriate manner when displayed. Use the\n `AboutWikiBoxes` macro for a demonstration.\n\n The width of right aligned boxes is adjustable and configured in the\n `[wikiextras]` section in `trac.ini`.\n\n The visual appearance of content tables presented to the right, generated\n by the built in `PageOutline` macro, is adjusted to be in line with these\n boxes. The width of the content boxes can be set to coincide with the other\n boxes, or be as narrow as possible. This is configured in the\n `[wikiextras]` section in `trac.ini`.\n\n **The Icons component must be activated** since warning boxes and the like\n uses the icon library.\n \"\"\"\n\n implements(IRequestFilter, IRequestHandler, ITemplateProvider,\n IWikiMacroProvider)\n\n rbox_width = IntOption('wikiextras', 'rbox_width', 300,\n \"Width of right aligned boxes.\")\n lbox_width = IntOption('wikiextras', 'lbox_width', 300,\n \"\"\"Width of left aligned boxes (defaults to\n `rbox_width`).\"\"\")\n wide_toc = BoolOption('wikiextras', 'wide_toc', 'false',\n \"\"\"Right aligned boxes with table of contents,\n produced by the `PageOutline` macro, are either\n as wide as ordinary right aligned boxes (`true`) or\n narrow (`false`).\"\"\")\n\n shadowless = BoolOption('wikiextras', 'shadowless_boxes', 'false',\n \"Use shadowless boxes.\")\n\n urgency_label = [(WARN, \"warn\"), (HIGHLIGHT, \"highlight\"),\n (ELABORATE, \"elaborate\"), (NEWS, \"news\"),\n (NORMAL, \"normal\")]\n\n urgency_bg = {WARN: 'red', HIGHLIGHT: 'yellow', ELABORATE: 'blue',\n NEWS: 'green', NORMAL: 'white'}\n\n # map -> (, , []\n types = {'comment': (ELABORATE, 'comment', []),\n 'configure': (NORMAL, 'configure', ['configuration', 'tool']),\n 'details': (NORMAL, 'details', ['look', 'magnifier']),\n 'discussion': (ELABORATE, 'discussion', ['chat', 'talk']),\n 'information': (HIGHLIGHT, 'information', ['note']),\n 'news': (NEWS, None, []),\n 'nok': (ELABORATE, 'nok', ['bad', 'no']),\n 'ok': (ELABORATE, 'ok', ['good', 'yes']),\n 'question': (HIGHLIGHT, 'question', ['help']),\n 'stop': (WARN, 'stop', ['critical']),\n 'tips': (HIGHLIGHT, 'tips', []),\n 'warning': (WARN, 'warning', ['bug', 'error', 'important']),\n }\n\n def __init__(self):\n self.word2type = {}\n for name, data in self.types.iteritems():\n self.word2type[name] = name\n for synonym in data[2]:\n self.word2type[synonym] = name\n\n # IRequestFilter methods\n\n #noinspection PyUnusedLocal\n def pre_process_request(self, req, handler):\n return handler\n\n def post_process_request(self, req, template, data, content_type):\n add_stylesheet(req, 'wikiextras/css/boxes.css')\n add_stylesheet(req, '/wikiextras/dynamicboxes.css')\n if self.shadowless:\n add_stylesheet(req, 'wikiextras/css/boxes-shadowless.css')\n return template, data, content_type\n\n # IRequestHandler methods\n\n def match_request(self, req):\n return req.path_info == '/wikiextras/dynamicboxes.css'\n\n def process_request(self, req):\n csstext = ('.wikiextras.box.right { width: %dpx; }\\n'\n '.wikiextras.box.icon.center, '\n '.wikiextras.box.icon.right { width: %dpx; }\\n' %\n (self.rbox_width - 22, self.rbox_width - 57))\n if self.wide_toc:\n csstext += ('.wiki-toc { width: %dpx !important; }\\n' %\n (self.rbox_width - 22))\n else:\n csstext += '.wiki-toc { width: auto !important; }\\n'\n\n req.send(csstext, 'text/css', status=200)\n\n return None\n\n # ITemplateProvider methods\n\n def get_htdocs_dirs(self):\n return [('wikiextras', resource_filename(__name__, 'htdocs'))]\n\n def get_templates_dirs(self):\n return []\n\n # IWikiMacroProvider methods\n\n def get_macros(self):\n yield 'box'\n yield 'rbox'\n yield 'lbox'\n yield 'newsbox'\n yield 'imagebox'\n\n def _get_type_description(self, line_prefix=''):\n urgency = {} # {'urgency': ('color', [\"type -words\"])}\n # color\n for u, color in self.urgency_bg.iteritems():\n urgency[u] = (color, [])\n # words\n for type, data in self.types.iteritems():\n urg, icon, words = data\n urgency[urg][1].append(type)\n for w in words:\n urgency[urg][1].append(w)\n descr = [\"%s||= Urgency ''(box color)'' =||= type =||\" % line_prefix]\n for urg, label in self.urgency_label:\n data = urgency[urg]\n color = data[0]\n words = data[1]\n words.sort()\n descr.append(\"%s||= %s ''(%s)'' =|| %s ||\" %\n (line_prefix, label, color,\n ', '.join('`%s`' % w for w in words)))\n return '\\n'.join(descr)\n\n #noinspection PyUnusedLocal\n def get_macro_description(self, name):\n if name == 'box':\n return cleandoc(\"\"\"\\\n View wiki text in a box.\n\n Syntax:\n {{{\n {{{#!box type align=... width=...\n wiki text\n }}}\n }}}\n or preferably when content is short:\n {{{\n [[box(wiki text, type=..., align=..., width=...)]]\n }}}\n where\n * `type` is an optional flag, or parameter, to call for\n attention depending on type of matter. When `type` is set,\n the box is decorated with an icon (except for `news`) and\n colored, depending on what ''urgency'' the type represents:\n %s\n `type` may be abbreviated as long as the abbreviation is\n unique for one of the keywords above.\n * `align` is optionally one of `right`, `left` or `center`.\n The `rbox` macro is an alias for `align=right`.\n * `width` is optional and sets the width of the box (defaults\n `auto` except for right aligned boxes which defaults a fixed\n width). `width` should be set when `align=center` for\n proper results.\n\n Examples:\n {{{\n {{{#!box warn\n = Warning\n Beware of the bugs\n }}}\n\n [[box(Beware of the bugs, type=warn)]]\n }}}\n\n A `style` parameter is also accepted, to allow for custom\n styling of the box. See also the `rbox`, `newsbox` and\n `imagebox` macros (processors).\n \"\"\") % self._get_type_description(' ' * 5)\n elif name in ('rbox', 'lbox'):\n return cleandoc(\"\"\"\\\n\n View a %(direction)s-aligned box. (This is a shorthand for\n `box align=%(direction)s`)\n\n Syntax:\n {{{\n {{{#!%(name)s type width=...\n wiki text\n }}}\n }}}\n or preferably when content is short:\n {{{\n [[%(name)s(wiki text, type=..., width=...)]]\n }}}\n where\n * `type` is an optional flag, or parameter, to call for\n attention depending on type of matter. When `type` is set,\n the box is decorated with an icon (except for `news`) and\n colored, depending on what ''urgency'' the type represents:\n %(type_description)s\n `type` may be abbreviated as long as the abbreviation is\n unique for one of the keywords above.\n * `width` is optional and sets the width of the box (defaults\n a fixed width). Use `width=auto` for an automatically sized\n box.\n\n Examples:\n {{{\n {{{#!%(name)s warn\n = Warning\n Beware of the bugs\n }}}\n\n [[%(name)s(Beware of the bugs, type=warn)]]\n }}}\n\n A `style` parameter is also accepted, to allow for custom\n styling of the box. See also the `box`, `newsbox` and\n `imagebox` macros (processors).\n \"\"\") % {\n 'name': name,\n 'direction': 'right' if name is 'rbox' else 'left',\n 'type_description': self._get_type_description(' ' * 5),\n }\n elif name == 'newsbox':\n return cleandoc(\"\"\"\\\n Present a news box to the right. (This is a shorthand for\n `rbox news`)\n\n Syntax:\n {{{\n {{{#!newsbox\n wiki text\n }}}\n }}}\n\n The following parameters are also accepted:\n * `width` -- Set the width of the box (defaults a fixed\n width).\n * `style` -- Custom styling of the box.\n\n See also the `box`, `rbox` and `imagebox` macros (processors).\n ''(Comment: This box corresponds to the well-known\n ''`NewsFlash`'' macro.)''\n \"\"\")\n elif name == 'imagebox':\n return cleandoc(\"\"\"\\\n Present a centered box suitable for one image.\n\n Syntax:\n {{{\n {{{#!imagebox\n wiki text\n }}}\n }}}\n\n This box is typically used together with the `Image` macro:\n {{{\n {{{#!imagebox\n [[Image(file)]]\n\n Caption\n }}}\n }}}\n\n Note that the `size` parameter of the `Image` macro may not\n behave as expected when using relative sizes (`%`).\n\n The following parameters are also accepted:\n * `align` -- One of `right`, `left` or `center` (defaults\n `center`).\n * `width` -- Set the width of the box (defaults `auto` except\n for right aligned boxes which defaults a fixed width).\n * `style` -- Custom styling of the box.\n\n See also the `box`, `rbox` and `newsbox` macros (processors).\n \"\"\")\n\n def _get_type(self, word):\n # Accept unique abbrevs. of type\n if not word:\n return ''\n if word in self.word2type:\n return self.word2type[word]\n type_ = ''\n for w in self.word2type.iterkeys():\n try:\n if w.startswith(word):\n t = self.word2type[w]\n if type_ and type_ != t:\n return # 2nd found, not unique\n type_ = t\n except TypeError as e:\n raise TracError(_(\"Invalid argument %(arg)s (%(type)s)\",\n arg=word, type=type(word)))\n return type_\n\n def _has_icon(self, type):\n if type in self.types:\n return self.types[type][1] is not None\n\n #noinspection PyUnusedLocal\n def expand_macro(self, formatter, name, content, args=None):\n class_list = ['wikiextras', 'box']\n style_list = []\n if args is None:\n content, args = parse_args(content)\n\n #noinspection PyArgumentList\n if not Icons(self.env).shadowless:\n class_list.append('shadow')\n\n class_arg = args.get('class', '')\n if class_arg:\n class_list.append(class_arg)\n\n align = ('right' if name in ('newsbox', 'rbox') else\n 'center' if name == 'imagebox' else\n 'left' if name == 'lbox' else\n '')\n align = args.get('align', align)\n if align:\n class_list.append(align)\n\n if name == 'newsbox':\n type = 'news'\n elif name == 'imagebox':\n type = 'image'\n else:\n type = args.get('type')\n if not type:\n for flag, value in args.iteritems():\n if value is True:\n type = flag\n break\n type = self._get_type(type)\n if type in self.types:\n td = self.types[type] # type data\n if td[1]: #icon\n class_list += ['icon', td[1]]\n else:\n class_list.append(type)\n bg = self.urgency_bg.get(td[0])\n if bg:\n class_list.append(bg)\n del td\n elif type:\n class_list.append(type)\n\n style = args.get('style', '')\n if style:\n style_list.append(style)\n\n width = args.get('width', '')\n if width:\n if width.isdigit():\n width = '%spx' % width\n if width.endswith('px'):\n # compensate for padding\n if self._has_icon(type):\n width = '%dpx' % (int(width[:-2]) - 57)\n else:\n width = '%dpx' % (int(width[:-2]) - 22)\n style_list.append('width:%s' % width)\n\n html = format_to_html(self.env, formatter.context, content)\n class_ = ' '.join(class_list)\n style = ';'.join(style_list)\n div = sanitize_attrib(self.env, tag.div(class_=class_, style=style))\n div(html)\n return div\n\n\nclass AboutWikiBoxes(Component):\n \"\"\"Macro for displaying a wiki page on how to use boxes.\n\n Create a wiki page `WikiBoxes` and insert the following line to show\n detailed instructions to wiki authors on how to use boxes in wiki pages:\n {{{\n [[AboutWikiBoxes]]\n }}}\n \"\"\"\n\n implements(IWikiMacroProvider)\n\n # IWikiMacroProvider methods\n\n def get_macros(self):\n yield 'AboutWikiBoxes'\n\n #noinspection PyUnusedLocal\n def get_macro_description(self, name):\n return \"Display a wiki page on how to use boxes.\"\n\n #noinspection PyUnusedLocal\n def expand_macro(self, formatter, name, content, args=None):\n help_file = resource_filename(__name__, 'doc/WikiBoxes')\n fd = open(help_file, 'r')\n wiki_text = fd.read()\n fd.close()\n return format_to_html(self.env, formatter.context, wiki_text)\n","sub_path":"TracWikiExtras-1.3.1.dev0-py2.7.egg/tracwikiextras/boxes.py","file_name":"boxes.py","file_ext":"py","file_size_in_byte":16496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"28914130","text":"\nimport sys\n\ndef main():\n s = input()\n\n p = s.find('f')\n if p == -1:\n print(-2)\n else:\n p = s.find('f', p+1)\n if p == -1:\n print(-1)\n else:\n print(p)\n\nif __name__ == '__main__':\n main()\n sys.exit(0)\n","sub_path":"pysnakify/05secondoccur.py","file_name":"05secondoccur.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"55347679","text":"#Creazione Struttura solid_model_3D\n\n\nfrom pyplasm import*\n\n#Creo una funzione per convertire colori RGB in Plasm\ndef rgbToPlasmColor(color):\n\treturn [color[0]/255., color[1]/255., color[2]/255.]\n\n\n#Creazione della base. Approssimata 69x33\nbase1_vertici = [ [0,0], [0,69], [33,69], [33,0] ];\nbase1_num_lati = [range(1,5)] \nbase1_2D = MKPOL([base1_vertici, base1_num_lati, None])\n\n#Porto in 2,5D\nfloor1 = PROD([base1_2D, Q(1)])\n\n#Coloro \nfloor1 = COLOR(rgbToPlasmColor([255,255,255]))(floor1)\n\n\n#Creo la seconda base.Approssimata 68x32\nbase2_vertici = [ [0,0], [0,68], [32,68], [32,0] ];\nbase2_num_lati = [range(1,5)] \nbase2_2D = MKPOL([base2_vertici, base2_num_lati, None])\n\n#Porto in 2,5D\nfloor2 = PROD([base2_2D, Q(1)])\n\n#Coloro \nfloor2 = COLOR(rgbToPlasmColor([147,147,147]))(floor2)\n\n\n#Creo la terza base su cui poggeranno le colonne: 68x30\nbase3_vertici = [ [0,0], [0,67], [31,67], [31,0] ];\nbase3_num_lati = [range(1,5)] \nbase3_2D = MKPOL([base3_vertici, base3_num_lati, None])\n\n#Porto in 2,5D\nfloor3 = PROD([base3_2D, Q(1)])\n\n#Coloro \nfloor3 = COLOR(rgbToPlasmColor([95,95,95]))(floor3)\n\n\n#Creo la la base posizionata sotto il tetto\nbase4_vertici = [ [0,0], [0,67], [31,67], [31,0] ]; \nbase4_num_lati = [range(1,5)] \nbase4_2D = MKPOL([base4_vertici, base4_num_lati, None])\n\n#Porto in 2,5D\nfloor4 = PROD([base4_2D, Q(3)])\n\n#Coloro \nfloor4 = COLOR(rgbToPlasmColor([128,128,128]))(floor4)\n\n\n#Creo il tetto.Approssimato 69x33x5\nfrom pyplasm import*\ntetto_vertici = [ [0,0], [33,0], [16,5], ];\ntetto_num_lati = [range(1,4)] \ntetto_2D = MKPOL([tetto_vertici, tetto_num_lati, None])\n\n#Porto in 2,5D\nfloor5 = PROD([tetto_2D, Q(69)])\n\n\n#Assemblo le 3 basi e il tetto\nfloor2=T([1,2,3])([0.5,0.5,1])(floor2)\nfloor3=T([1,2,3])([1,1,2])(floor3)\nfloor4=T([1,2,3])([1,1,15])(floor4)\n\n\nfloor5=MAP([S1,S3,S2])(floor5)\nfloor5=T([3])([18])(floor5)\n\n#Coloro il tetto dopo la traslazione.\nfloor5 = COLOR(rgbToPlasmColor([147,147,147]))(floor5)\n\n#Creo la struttura 2,5D\nOrizontal_model=STRUCT([floor1,floor2,floor3,floor4,floor5])\n\n#Creo una funzione per la circonferenza delle colonne esterne\ndef base(p): \n u,v = p\n return [v*COS(u), v*SIN(u)]\ndomain2D = PROD([INTERVALS(2*PI)(20), INTERVALS(1)(3)])\n\n#Creo una funzione per la circonferenza delle colonne interne\ndef base2(p): \n u,v = p\n return [(v/2)*COS(u), (v/2)*SIN(u)]\n\n #Creo una colonna esterna\nbase_colonna1=MAP(base)(domain2D) \nbase_colonna=PROD([base_colonna1,Q(11)])\n\n#Creo una colonna interna\nbase_colonnina1=MAP(base2)(domain2D)\nbase_colonnina=PROD([base_colonnina1,Q(11.5)])\n\n#Creo il blocchetto da mettere sopra la colonna esterna\nblocchetto_coords = [ [0,0], [0,2.5], [2.5,2.5], [2.5,0] ];\nblocchetto_num_lati = [range(1,5)] \nblocchetto_2D = MKPOL([blocchetto_coords, blocchetto_num_lati, None])\nblocchetto = PROD([blocchetto_2D, Q(1)])\n\n#Posiziono il blocchetto della colonna esterna\nblocchetto=T([1,2,3])([-1.25,-1.25,11])(blocchetto)\n\n#Creo la struttura con colonna e blocchetto\ncolonna=STRUCT([blocchetto,base_colonna])\n\n#Creo il blocchetto della colonna interna\nblocchetto2_coords = [ [0,0], [0,1.5], [1.5,1.5], [1.5,0] ];\nblocchetto2_num_lati = [range(1,5)] \nblocchetto2_2D = MKPOL([blocchetto2_coords, blocchetto2_num_lati, None])\nblocchetto2 = PROD([blocchetto2_2D, Q(0.5)])\n\n#Posiziono il blocchetto sulla colonna interna\nblocchetto2=T([1,2,3])([-0.80,-0.80,11.5])(blocchetto2)\n\n#Creo la struttura con colonna interna e blocchetto\ncolonna_int=STRUCT([blocchetto2,base_colonnina])\n\n#Traslo la colonna\ncolonna=T([1,2,3])([2.2,2.2,3])(colonna)\n\n#Traslo la colonna interna\ncolonna_int=T([1,2,3])([8.2,8.2,3])(colonna_int)\n\n#Creo le colonne frontali e le posiziono\ncolonne_temp=[T(1)(4),colonna]\ncolonne_frontali=STRUCT(NN(8)(colonne_temp))\ncolonne_frontali=T(1)(-3.80)(colonne_frontali)\n#Coloro\ncolonne_frontali = COLOR(rgbToPlasmColor([95,95,95]))(colonne_frontali)\n\n#Creo le colonne interne frontali\ncolonne_int_temp=[T(1)(4),colonna_int]\ncolonne_int_frontali=STRUCT(NN(6)(colonne_int_temp))\ncolonne_int_frontali=T(1)(-5.80)(colonne_int_frontali)\n#Coloro\ncolonne_int_frontali = COLOR(rgbToPlasmColor([255,255,255]))(colonne_int_frontali)\n\n\n#Creo le mura interne frontali\nmura4_vertici = [ [0,0], [1,0], [0,5], [1,5] ];\nmura4_num_lati = [range(1,5)] \nmura4_2D = MKPOL([mura4_vertici, mura4_num_lati, None])\nmura4 = PROD([mura4_2D, Q(12)])\n\nmura4=T([1,2,3])([20,-26.5,3])(mura4)\nmura4=ROTATE([1,2])(PI/2)(mura4)\nmura4 = COLOR(rgbToPlasmColor([178,178,178]))(mura4)\n\nmura5_vertici = [ [1,1], [2,1], [1,6], [2,6] ];\nmura5_num_lati = [range(1,5)] \nmura5_2D = MKPOL([mura5_vertici, mura5_num_lati, None])\nmura5 = PROD([mura5_2D, Q(12)])\n\nmura5=T([1,2,3])([19,-12.5,3])(mura5)\nmura5=ROTATE([1,2])(PI/2)(mura5)\nmura5 = COLOR(rgbToPlasmColor([178,178,178]))(mura5)\n\nmura_frontali=STRUCT([mura4,mura5])\n\n#Creo la struttua frontale\nnorth=STRUCT([colonne_frontali,colonne_int_frontali,mura_frontali])\n\n#Creo le colonne posteriori e le posiziono\ncolonne_posteriori=T(2)(64)(colonne_frontali)\n#Coloro\ncolonne_posteriori = COLOR(rgbToPlasmColor([95,95,95]))(colonne_posteriori)\n\n#Creo le colonne interne posteriori\ncolonne_int_posteriori=T(2)(52)(colonne_int_frontali)\n\n#Creo le mura interne posteriori\nmura3_vertici = [ [0,0], [1,0], [0,20], [1,20] ];\nmura3_num_lati = [range(1,5)] \nmura3_2D = MKPOL([mura3_vertici, mura3_num_lati, None])\nmura3 = PROD([mura3_2D, Q(12)])\n\nmura3=T([1,2,3])([50,-26.5,3])(mura3)\nmura3=ROTATE([1,2])(PI/2)(mura3)\nmura3 = COLOR(rgbToPlasmColor([178,178,178]))(mura3)\n\n#Creo la struttura posteriore\nsud=STRUCT([colonne_posteriori,colonne_int_posteriori,mura3])\n\n#Creo le colonne esterne sx e le posiziono\ncolonne_sx=STRUCT(NN(15)(colonne_temp))\ncolonne_sx=ROTATE([1,2])(PI/2)(colonne_sx)\ncolonne_sx=T(1)(4.3)(colonne_sx)\n#Coloro\ncolonne_sx = COLOR(rgbToPlasmColor([95,95,95]))(colonne_sx)\n\n#Creo le mura sx e le posiziono\nmura1_vertici = [ [0,0], [1,0], [0,45], [1,45] ];\nmura1_num_lati = [range(1,5)] \nmura1_2D = MKPOL([mura1_vertici, mura1_num_lati, None])\nmura1 = PROD([mura1_2D, Q(12)])\nmura1=T([1,2,3])([6.2,11.2,3])(mura1)\n\n#Coloro\nmura1 = COLOR(rgbToPlasmColor([178,178,178]))(mura1)\n\n#Creo la struttura sx\novest=STRUCT([colonne_sx,mura1])\n\n#Creo le colonne esterne dx e le posiziono\ncolonne_dx=STRUCT(NN(15)(colonne_temp))\ncolonne_dx=ROTATE([1,2])(PI/2)(colonne_dx)\ncolonne_dx=T(1)(32.8)(colonne_dx)\n#Coloro\ncolonne_dx = COLOR(rgbToPlasmColor([95,95,95]))(colonne_dx)\n\n#Creo le mura dx e le posiziono\nmura2_vertici = [ [5,0], [6,0], [5,45], [6,45] ];\nmura2_num_lati = [range(1,5)] \nmura2_2D = MKPOL([mura2_vertici, mura2_num_lati, None])\nmura2 = PROD([mura2_2D, Q(12)])\n\nmura2=T([1,2,3])([21,11.2,3])(mura2)\n#Coloro\nmura2 = COLOR(rgbToPlasmColor([178,178,178]))(mura2)\n\n#Creo la struttura sx\nest=STRUCT([colonne_dx,mura2])\n\n\n#Creo la struttura finale solida 3D\nVertical_model=STRUCT([north,sud,ovest,est])\nsolid_model_3D=STRUCT([Orizontal_model,Vertical_model])\nVIEW(solid_model_3D)\n\n","sub_path":"2014-03-21/python/exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":6868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"483468805","text":"from sampler import RandomFieldSPDE\nfrom fenics import *\nfrom ufl import tanh\nimport numpy as np\n\nmesh = Mesh(\"flower.xml\")\nbfun = MeshFunction(\"size_t\",mesh,mesh.topology().dim()-1)\nFile(\"flower_facet_region.xml\") >> bfun\n\nfe = FiniteElement(\"P\",mesh.ufl_cell(),1)\nV = FunctionSpace(mesh,fe)\n\nd = mesh.topology().dim()\nu,v = TrialFunction(V),TestFunction(V)\n\n# harmonic interpolation\ndist = Function(V,name=\"distance\")\nbcs = [DirichletBC(V,0.0,bfun,3),DirichletBC(V,1.0,bfun,2)]\nsolve(inner(grad(u),grad(v))*dx==Constant(0.0)*v*dx(mesh),dist,bcs)\n\ndist2 = Function(V,name=\"distance2\")\nnormalized = lambda g: g/sqrt(dot(g,g))\nsolve(inner(grad(u),grad(v))*dx==inner(normalized(grad(dist)),grad(v))*dx,\n dist2,DirichletBC(V,0.0,bfun,3))\n\nsf = Constant(10.0,name=\"sf\")\nst = Constant(1.0,name=\"st\")\nt = normalized(grad(dist2))\nfib = as_vector([t[1],-t[0]])\n\nff = outer(fib,fib)\nR0 = Constant(0.5)\nee = Constant(0.05)\nsfhump = st + (sf-st)/2.0*(1-tanh((dist2-R0)/ee))\nsthump = st/sfhump\nD = sfhump*ff + sthump*(Identity(d) - ff)\n\nwith XDMFFile(f\"rand_flower.xdmf\") as ofile:\n ofile.parameters['functions_share_mesh'] = True\n ofile.parameters['rewrite_function_mesh'] = False\n for N in [1,5,10]:\n sampler = RandomFieldSPDE(V,N=N,rho=0.05,D=D)\n s = next(sampler.sample(1))\n ofile.write(s,float(N))\n\n","sub_path":"SPDE/randflower.py","file_name":"randflower.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"614300261","text":"N, M = map(int, input().split())\n\n\ndef backTracking(n, numberList, m):\n if len(numberList) == m:\n result.append(numberList[:])\n return\n\n for num in range(1, n + 1):\n if num not in numberList:\n if len(numberList) == 0 or len(numberList) != 0 and numberList[-1] < num:\n numberList.append(num)\n backTracking(n, numberList, m)\n numberList.pop()\n\n\nresult = []\nbackTracking(N, [], M)\n\nfor numbers in result:\n for number in numbers:\n print(number, end=\" \")\n print()","sub_path":"baekjun/back-tracking/N과 M (2).py","file_name":"N과 M (2).py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"599849747","text":"#!/usr/bin/env python2\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct 28 17:53:59 2017\r\n\r\n@author: yangx\r\n\"\"\"\r\n\r\n\r\ndef batchBatch(analysisMode):\r\n import os\r\n import glob\r\n# import tkFileDialog\r\n import tkinter as tk\r\n from tkinter import filedialog\r\n# import time\r\n\r\n# defaultFolder = '/media/yangx/YXHD-01/data_shared/mouseTouchData4Analysis/'\r\n# defaultFolder = 'C:\\\\Users\\\\Admin\\\\Documents\\\\mouseTouchData'\r\n defaultFolder = 'D:/Data/mouseTouchData4Analysis'\r\n currentpath = os.getcwd()\r\n os.chdir(defaultFolder)\r\n root = tk.Tk()\r\n# foldersPath = tkFileDialog.askdirectory()\r\n foldersPath = filedialog.askdirectory()\r\n folderList = glob.glob(os.path.join(foldersPath, '*'))\r\n folderList.sort()\r\n# time.sleep(4200)\r\n root.destroy()\r\n for folderPath in folderList:\r\n if os.path.isdir(folderPath):\r\n batchProcessingPKU(analysisMode, folderPath)\r\n os.chdir(currentpath)\r\n return(0)\r\n\r\n\r\ndef batchProcessingPKU(analysisMode, folderPath=None, parallel=False, type='top'):\r\n import os\r\n import glob\r\n# import tkFileDialog\r\n import tkinter as tk\r\n from tkinter import filedialog\r\n from joblib import delayed\r\n from joblib import Parallel\r\n import time\r\n from mouseTouch import vs\r\n from mouseTouch import tr\r\n from mouseTouch import ta\r\n from mouseTouch import va\r\n# from vs import videoStitchingPKU\r\n# from tr import timeReadingPKU\r\n# from ta import timelineAligningPKU\r\n# from ta import correctTSmanuallyPKU\r\n# from va import videoClipPKU\r\n# import pdb\r\n# pdb.set_trace()\r\n fcnBegin = time.time()\r\n# defaultFolder = '/media/yangx/YXHD-01/data_shared/mouseTouchData4Analysis/'\r\n# defaultFolder = 'C:\\\\Users\\\\Admin\\\\Documents\\\\mouseTouchData'\r\n defaultFolder = 'D:/Data/mouseTouchData4Analysis'\r\n currentpath = os.getcwd()\r\n os.chdir(defaultFolder)\r\n if folderPath is None:\r\n root = tk.Tk()\r\n folderPath = filedialog.askdirectory()\r\n# folderPath = tkFileDialog.askdirectory()\r\n root.destroy()\r\n print(folderPath)\r\n txtList = glob.glob(os.path.join(folderPath, '*.txt'))\r\n txtList.sort()\r\n# time.sleep(4200)\r\n if type=='top':\r\n camNum = 3\r\n if type=='side':\r\n camNum = 4\r\n if parallel:\r\n if analysisMode & 1 == 1:\r\n status_lst = Parallel(n_jobs=5)(delayed(vs.videoStitchingPKU)(\r\n filename.replace('\\\\', '/'), camNum) for filename in txtList)\r\n if analysisMode & 4 == 4:\r\n status_lst = Parallel(n_jobs=5)(delayed(ta.timelineAligningPKU)(\r\n filename.replace('\\\\', '/'), camType=camNum) for filename in txtList)\r\n if analysisMode & 8 == 8:\r\n status_lst = Parallel(n_jobs=5)(delayed(va.videoClipPKU)(\r\n filename.replace('\\\\', '/'), 70, camNum) for filename in txtList)\r\n if analysisMode & 64 == 64:\r\n status_lst = Parallel(n_jobs=5)(delayed(va.vidCalRes2)(\r\n filename.replace('\\\\', '/')) for filename in txtList)\r\n if analysisMode & 128 == 128:\r\n status_lst = Parallel(n_jobs=5)(delayed(ta.alignByLED)(\r\n filename.replace('\\\\', '/'), camType=camNum) for filename in txtList)\r\n if analysisMode & 256 == 256:\r\n status_lst = Parallel(n_jobs=5)(delayed(vs.videoCompressingPKU)(\r\n filename.replace('\\\\', '/'), camNum) for filename in txtList)\r\n print(status_lst)\r\n else:\r\n if analysisMode & 1 == 1:\r\n root = tk.Tk()\r\n tfPath = filedialog.askdirectory()\r\n root.destroy()\r\n for filename in txtList:\r\n filename = filename.replace('\\\\', '/')\r\n print(filename)\r\n if analysisMode & 1 == 1:\r\n vs.videoStitchingOnlyPKU(filename, camNum, tfPath)\r\n if analysisMode & 2 == 2:\r\n tr.timeReadingPKU3(filename, camType=camNum)\r\n if analysisMode & 4 == 4:\r\n ta.timelineAligningPKU(filename, camType=camNum)\r\n if analysisMode & 8 == 8:\r\n va.videoClipPKU(filename, 70, camNum)\r\n if analysisMode & 16 == 16:\r\n # timeError=(timeStampCorrected-timeStamp)-(Origin-L)\r\n ta.correctTSmanuallyPKU(filename, -23, camNum)\r\n if analysisMode & 32 == 32:\r\n va.delVideoPKU(filename, camNum)\r\n if analysisMode & 64 == 64:\r\n va.vidCalRes2(filename)\r\n if analysisMode & 128 == 128:\r\n ta.alignByLED(filename, camType=camNum)\r\n if analysisMode & 256 == 256:\r\n # vs.videoCompressingPKU(filename, camNum)\r\n vs.videoRenamePKU(filename, 2)\r\n# vs.deleteVideoPKU(filename, camNum)\r\n if analysisMode & 2 == 2:\r\n restart_kernel()\r\n\r\n os.chdir(currentpath)\r\n fcnEnd = time.time()\r\n telapse = (fcnEnd-fcnBegin)/60\r\n print('time elapse is %.1f min\\n' % telapse)\r\n return(0)\r\n\r\n\r\ndef batchFreezingPKU():\r\n import os\r\n import glob\r\n# import tkFileDialog\r\n import tkinter as tk\r\n from tkinter import filedialog\r\n import numpy as np\r\n# from va import freezingDetectionPKU\r\n# from va import arenaMaskPKU\r\n from mouseTouch import va\r\n# import mouseTouch\r\n# defaultFolder = '/media/yangx/YXHD-01/data_shared/mouseTouchData4Analysis/'\r\n# defaultFolder = 'C:\\\\Users\\\\Admin\\\\Documents\\\\mouseTouchData'\r\n defaultFolder = 'D:/Data/mouseTouchData4Analysis'\r\n currentpath = os.getcwd()\r\n os.chdir(defaultFolder)\r\n root = tk.Tk()\r\n# folderPath = tkFileDialog.askdirectory()\r\n folderPath = filedialog.askdirectory()\r\n txtList = glob.glob(os.path.join(folderPath, '*.txt'))\r\n txtList.sort()\r\n root.destroy()\r\n# time.sleep(4200)\r\n\r\n# analysisfolder = '/media/yangx/YXHD-01/data_shared/AnalysisPKU'\r\n# analysisfolder = 'C:\\\\Users\\\\Admin\\\\Documents\\\\Analysis'\r\n analysisfolder = 'D:/Data/AnalysisPKU'\r\n# analysisSetupFolder = os.path.join(analysisfolder,setupFolder)\r\n prefix = 'YiV'\r\n begin = True\r\n\r\n for filePath in txtList:\r\n if begin:\r\n va.arenaMaskPKU(filePath)\r\n begin = False\r\n# parentfolder = os.path.split(filePath)[0]\r\n# parentfolder = os.path.split(parentfolder)[1]\r\n filename = os.path.split(filePath)[1]\r\n filename = os.path.splitext(filename)[0]\r\n if filename[0] == 'S' or filename[0] == 's':\r\n setupFolder = filename[0:3]\r\n parentfolder = filename[4:12]\r\n else:\r\n setupFolder = 'siat'\r\n parentfolder = filename[0:8]\r\n subfolder = 'A'+filename\r\n folderpath = os.path.join(\r\n analysisfolder, setupFolder, parentfolder, subfolder)\r\n video2read = prefix+filename+'-L??.mp4'\r\n mp4List = glob.glob(os.path.join(folderpath, video2read))\r\n for iloop in range(np.size(mp4List)):\r\n va.freezingDetectionPKU(filePath, iloop+1)\r\n os.chdir(currentpath)\r\n return(0)\r\n\r\n\r\ndef batchBatchAnalysis(analysisMode):\r\n import os\r\n import glob\r\n# import tkFileDialog\r\n import tkinter as tk\r\n from tkinter import filedialog\r\n# defaultFolder = '/media/yangx/YXHD-01/data_shared/mouseTouchData4Analysis/'\r\n# defaultFolder = 'C:\\\\Users\\\\Admin\\\\Documents\\\\mouseTouchData'\r\n defaultFolder = '' # user defines, like 'D:/Data/mouseTouchData4Analysis'\r\n currentpath = os.getcwd()\r\n os.chdir(defaultFolder)\r\n root = tk.Tk()\r\n# foldersPath = tkFileDialog.askdirectory()\r\n foldersPath = filedialog.askdirectory()\r\n folderList = glob.glob(os.path.join(foldersPath, '*'))\r\n folderList.sort()\r\n# time.sleep(4200)\r\n root.destroy()\r\n for folderPath in folderList:\r\n if os.path.isdir(folderPath):\r\n batchAnalysisPKU(analysisMode, folderPath)\r\n os.chdir(currentpath)\r\n return(0)\r\n\r\n\r\ndef batchAnalysisPKU(analysisMode, folderPath=None, parallel=False):\r\n import os\r\n import glob\r\n# import tkFileDialog\r\n import tkinter as tk\r\n from tkinter import filedialog\r\n import numpy as np\r\n from joblib import delayed, Parallel\r\n# from va import freezingDetectionPKU\r\n# from va import behaviorAnalysis\r\n# from va import arenaMaskPKU\r\n from mouseTouch import va\r\n\r\n \r\n if analysisMode & 4 == 4:\r\n from mouseTouch import mouseDetection as md\r\n elif analysisMode & 8 == 8: \r\n from mouseTouch import recordAlignment as ra\r\n elif analysisMode & 16 == 16:\r\n from mouseTouch import behaviorTagging as bt\r\n elif analysisMode & 32 == 32:\r\n from mouseTouch import randomForest4unclear as rf\r\n elif analysisMode & 64 == 64:\r\n from mouseTouch import tagCluster as tc\r\n elif analysisMode & 128 == 128: \r\n from mouseTouch import caption as st\r\n import time\r\n\r\n fcnBegin = time.time()\r\n# defaultFolder = '/media/yangx/YXHD-01/data_shared/mouseTouchData4Analysis/'\r\n defaultFolder = '' # user defines, like 'D:/data/mouseTouchData4Analysis/data4stat/'\r\n currentpath = os.getcwd()\r\n os.chdir(defaultFolder)\r\n if folderPath is None:\r\n root = tk.Tk()\r\n folderPath = filedialog.askdirectory()\r\n root.destroy()\r\n print(folderPath)\r\n txtList = glob.glob(os.path.join(folderPath, '*.txt'))\r\n txtList.sort()\r\n# time.sleep(4200)\r\n\r\n# analysisfolder = '/media/yangx/YXHD-01/data_shared/AnalysisPKU'\r\n# analysisfolder = 'D:/data/Data/AnalysisPKU'\r\n# analysisSetupFolder = os.path.join(analysisfolder,setupFolder)\r\n# prefix = 'YiV'\r\n# begin = True\r\n if analysisMode & 1 == 1:\r\n va.arenaMaskPKU(txtList[0].replace('\\\\', '/'))\r\n if parallel:\r\n if analysisMode & 1 == 1:\r\n status_lst = Parallel(n_jobs=5)(delayed(va.freezingDetectionPKU)(\r\n filename.replace('\\\\', '/')) for filename in txtList)\r\n if analysisMode & 2 == 2:\r\n status_lst = Parallel(n_jobs=5)(delayed(va.behaviorAnalysis)(filename.replace(\r\n '\\\\', '/'), wholeVid=True) for filename in txtList)\r\n if analysisMode & 4 == 4:\r\n status_lst = Parallel(n_jobs=3)(delayed(md.mouseDetection)(filename.replace(\r\n '\\\\', '/'), np.mod(i, 3)+1, 3) for i, filename in enumerate(txtList))\r\n if analysisMode & 8 == 8:\r\n status_lst = Parallel(n_jobs=5)(delayed(ra.recordAlignment)(filename.replace(\r\n '\\\\', '/'), camType=4) for filename in txtList)\r\n if analysisMode & 16 == 16:\r\n status_lst = Parallel(n_jobs=5)(delayed(bt.behaviorTagging)(filename.replace(\r\n '\\\\', '/'), camType=4) for filename in txtList)\r\n\r\n else:\r\n for filePath in txtList:\r\n print(filePath)\r\n fps = 30\r\n if analysisMode & 1 == 1:\r\n va.freezingDetectionPKU(filePath.replace('\\\\', '/'))\r\n if analysisMode & 2 == 2:\r\n va.behaviorAnalysis(filePath.replace('\\\\', '/'))\r\n if analysisMode & 4 == 4:\r\n md.mouseDetection(\r\n filePath.replace('\\\\', '/'), camType = 3)\r\n if analysisMode & 8 == 8:\r\n ra.recordAlignment(filePath.replace(\r\n '\\\\', '/'), camType = 4)\r\n if analysisMode & 16 == 16:\r\n bt.behaviorTagging(filePath.replace(\r\n '\\\\', '/'), camType = 4) \r\n if analysisMode & 32 == 32:\r\n rf.randomForest4unclearTag(filePath.replace(\r\n '\\\\', '/'))\r\n # rf.tagBySavedModel(filePath.replace(\r\n # '\\\\', '/'))\r\n # ra.frameSelectionbyLocation(filePath.replace(\r\n # '\\\\', '/'), camType=3)\r\n # ra.frameSelectionbyLocation(filePath.replace(\r\n # '\\\\', '/'), camType=4)\r\n if analysisMode & 64 == 64:\r\n # tc.tagCluster(filePath.replace(\r\n # '\\\\', '/'))\r\n tc.clusterByModel(filePath.replace(\r\n '\\\\', '/'))\r\n if analysisMode & 128 == 128:\r\n st.srt4vid(filePath.replace(\r\n '\\\\', '/'))\r\n# if begin and analysisMode&1==1:\r\n# va.arenaMaskPKU(filePath)\r\n# begin = False\r\n# parentfolder = os.path.split(filePath)[0]\r\n# parentfolder = os.path.split(parentfolder)[1]\r\n\r\n# filename = os.path.split(filePath)[1]\r\n# filename = os.path.splitext(filename)[0]\r\n# if filename[0]=='S' or filename[0]=='s':\r\n# setupFolder = filename[0:3]\r\n# parentfolder = filename[4:12]\r\n# else:\r\n# setupFolder = 'siat'\r\n# parentfolder = filename[0:8]\r\n# subfolder = 'A'+filename\r\n# folderpath = os.path.join(analysisfolder,setupFolder,parentfolder,subfolder)\r\n# video2read = prefix+filename+'-L??.mp4'\r\n# mp4List = glob.glob(os.path.join(folderpath,video2read))\r\n# for iloop in range(np.size(mp4List)):\r\n# if analysisMode&1==1:\r\n# va.freezingDetectionPKU(filePath,iloop+1)\r\n# if analysisMode&2==2:\r\n# va.behaviorAnalysis(filePath,iloop+1)\r\n\r\n os.chdir(currentpath)\r\n fcnEnd = time.time()\r\n telapse = (fcnEnd-fcnBegin)/60\r\n print('\\nTime elapse is %.1f min\\n' % telapse)\r\n return(0)\r\n\r\n\r\ndef restart_kernel():\r\n import time\r\n import sys\r\n import os\r\n\r\n print('Python kernel will restart after 3 seconds.')\r\n time.sleep(3)\r\n python = sys.executable\r\n os.execl(python, python, *sys.argv)\r\n","sub_path":"bp.py","file_name":"bp.py","file_ext":"py","file_size_in_byte":13722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"10841601","text":"# coding: utf8\n\ntry:\n import ujson as json\nexcept ImportError:\n import json\n\nimport uvloop\nimport asyncio\nimport logging\nfrom yarl import URL\nfrom aiohttp import ClientSession\nfrom datetime import datetime\nfrom lxml.etree import HTML\nfrom aioauth_client import TwitterClient\nfrom motor.motor_asyncio import AsyncIOMotorClient as MongoClient\n\nfrom scripture import settings\n\nlogging.basicConfig(\n format='%(asctime)s %(name)s %(levelname)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n)\n\nlogger = logging.getLogger('twitter.news')\n\nurl = 'https://userstream.twitter.com/1.1/user.json'\n\nproxy = 'http://172.17.1.198:1118'\n\ntweet = TwitterClient(\n consumer_key='buAFwd0vZPgRkk92GdNkqWobf',\n consumer_secret='LNvjEUQzFqKszTeh5jnz2otZrEowZ06ShN1FOWmJ79TPpEYX1j',\n oauth_token='879182607505793024-UhuTlH1bABSVw5TpR1ejiA1PsFJQsAn',\n oauth_token_secret='suWywcV5ezZwSiCXTZm2xwIYW1xz7SQcuyTnhqGO7x3xo',\n base_url='https://userstream.twitter.com/1.1/',\n request_params={'proxy': proxy}\n)\n\nmc = MongoClient(settings.MONGO)\n\n\nasync def parse_location(tree):\n tree = HTML(html)\n tree.xpath()\n return None\n\n\nasync def parse_tags(html):\n pass\n\n\nclass BaseModel:\n\n connection = None\n database_name = None\n collection_name = None\n\n @classmethod\n def set_connection(cls, connection):\n cls.connection = connection\n cls.database_name = connection.get_default_database().name\n cls.collection_name = cls.collection_name \\\n or cls.to_snake_case(cls.__name__)\n return cls\n\n @classmethod\n def to_snake_case(cls, camel_case):\n return (\n ''.join([\n \"_\" + x.lower()\n if i < len(camel_case) - 1 and x.isupper() and out[i + 1].islower() # noqa\n else x.lower() + \"_\"\n if i < len(camel_case) - 1 and x.islower() and out[i + 1].isupper() # noqa\n else x.lower() for i, x in enumerate(list(camel_case))])\n ) \\\n .lstrip('_') \\\n .replace('__', '_')\n\n def __getattr__(self, attr):\n try:\n self[attr]\n except KeyError:\n raise AttributeError(f'Model object has no attribute {attr}') # noqa\n\n def __setattr__(self, attr, value):\n self[attr] = value\n return value\n\n async def find_one(**args):\n return self.connection.find_one()\n\n\ndef Base(connection):\n BaseModel.set_connection(connection)\n return BaseModel\n\n\nModel = BaseModel(mc)\n\n\nclass TweetNews(Model):\n database_name = 'scripture'\n collection_name = 'twitter_news'\n\n\nclass BBC:\n\n def __init__(self, tweet_id, url):\n self.news_src = URL(url)\n self.tweet_id = tweet_id\n self.tags = []\n\n def news_tags(self, tree):\n tags = []\n first_tag = tree.xpath(\n '//span[@id=\"comp-index-title\"]/span/a/text()'\n )\n if first_tag:\n tags.append(first_tag[0])\n xp = '//div[@id=\"site-container\"]/div[contains(@class, \"site-brand\")]'\n xp += '/div[contains(@class, \"secondary-navigation\")]/nav/ul/li/a/span'\n xp += '/text()'\n other_tags = tree.xpath(xp)\n tags.extend(other_tags)\n return tags\n\n def sport_tags(self):\n self.tags = []\n\n def _location(self):\n self.location = ''\n\n async def parse(self):\n async with ClientSession() as request:\n async with request.get(url, proxy=proxy) as resp:\n html = await resp.text()\n\n tree = HTML(html)\n\n if self.news_tags.path.startswith('/sport/live'):\n self.tags = ['sport', 'live']\n elif self.news_tags.path.startswith('/news'):\n self.tags = self.news_tags(tree)\n else:\n pass\n\n self._location()\n\n def save(self):\n pass\n\n\nasync def parse_news(url, type):\n tree = HTML(html)\n\n\nasync def main():\n\n stream = await tweet.request('get', 'user.json')\n\n async for line in stream.content:\n line = line.strip()\n if line == b'':\n print('empty line')\n continue\n n = json.loads(line)\n if 'friends' in n:\n logger.debug(n)\n continue\n\n print(n)\n continue\n\n now = datetime.now()\n\n if 'delete' in n:\n dlt = await mc.scripture.twitter_news.update_one(\n {'id': n['status']['id'], 'user.id': n['status']['user_id']}, # noqa\n {'deleted_at': now}\n )\n logger.info(f'To mark {n[\"id\"]} as deleted {dlt.modified_count}') # noqa\n else:\n n['inserted_at'] = now\n ist = await mc.scripture.twitter_news.insert_one(n)\n logger.info('Added %s', ist.inserted_id)\n\n\nif __name__ == '__main__':\n asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n","sub_path":"flashtripdemo/scripture/scripture/scripts/twitter_news.py","file_name":"twitter_news.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"462010769","text":"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport numpy as np\nimport re\n\n\ndef get_data():\n \"\"\"\n This function extracts data from the NCDC website and stores it as a pandas dataframe' \n \"\"\"\n PAGE_URL = \"https://covid19.ncdc.gov.ng/\"\n \n # Response Data\n response_data = requests.get(PAGE_URL).text\n\n # Initializing the BeautifulSoup package and the specifying the parser\n soup = BeautifulSoup(response_data, 'lxml')\n content_table = soup.find(\"table\", id=\"custom1\")\n\n # Extracting the Table header names \n table_headers = content_table.thead.findAll(\"tr\")\n for k in range(len(table_headers)):\n data = table_headers[k].find_all(\"th\")\n column_names = [j.string.strip() for j in data]\n\n # Extracting the data in the Table's body (values)\n table_data = content_table.tbody.findAll('tr')\n values = []\n keys = []\n data_dict = {}\n for k in range(len(table_data)):\n key = table_data[k].find_all(\"td\")[0].string.strip()\n value = [j.string.strip() for j in table_data[k].find_all(\"td\")]\n keys.append(key)\n values.append(value)\n data_dict[key] = value\n \n #Convert dictionary to dataframe \n data = pd.DataFrame(data_dict).T\n data.columns = ['states', 'confirmed_cases', 'cases(on admission)', 'recovered', 'deaths']\n data = data.reset_index(drop=True)\n \n #Removing the commas ( , ) between the numbers e.g 6,239\n data['confirmed_cases'] = data['confirmed_cases'].apply(lambda x: int(re.sub(\"[^0-9]\", \"\", x)) )\n data['cases(on admission)'] = data['cases(on admission)'].apply(lambda x: int(re.sub(\"[^0-9]\", \"\", x)) )\n data['recovered'] = data['recovered'].apply(lambda x: int(re.sub(\"[^0-9]\", \"\", x)) )\n data['deaths'] = data['deaths'].apply(lambda x: int(re.sub(\"[^0-9]\", \"\", x)) )\n\n return data\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Data_extraction.py","file_name":"Data_extraction.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"148218329","text":"\n''' this module serves as the tree repesentation of the website\n'''\n\ntry:\n from urllib.parse import urlparse\nexcept:\n from urlparse import urlparse \n\nclass treeNode:\n def __init__(self, content=None, type=-1, parent=None):\n self.children = {} # dictionary of department name to treeNode\n self.parent = parent\n\n # type: 1: website homepage, 2: department homepage 3: faculty main page, 4: program main page\n # 5: professor page1, 6: professor page2, 7: program page others\n self.type = type\n # self.url = url\n self.content = content\n # self.title = None\n\n\n\nclass websiteTree:\n def __init__(self, homepage):\n self.root = treeNode(\"root\", 0)\n\n def insert_node(self, url):\n if '//' in url[8:]:\n url = url[:9] + url[9:].replace('//', '/')\n urlparseResult = urlparse(url)\n\n if urlparseResult.netloc not in self.root.children:\n self.root.children[urlparseResult.netloc] = treeNode(content=urlparseResult.netloc, parent=self.root)\n currentRoot = self.root.children[urlparseResult.netloc]\n self._insert_node_aux(currentRoot, urlparseResult.path.strip('/'))\n\n def _insert_node_aux(self, root, url):\n # if not url:\n # return\n currentDirectory = url\n pos = url.find('/')\n if pos != -1:\n currentDirectory = url[:pos]\n if currentDirectory not in root.children:\n root.children[currentDirectory] = treeNode(content=currentDirectory, parent=root)\n newRoot = root.children[currentDirectory]\n if pos != -1:\n self._insert_node_aux(newRoot, url[pos + 1:])\n else:\n newRoot.children[''] = None\n\n def get_level_one(self):\n for child in self.root.children.values():\n yield child\n\n def get_level_two(self):\n for child1 in self.root.children.values():\n for child2 in child1.children.values():\n yield child2\n\n def get_level_three(self):\n for child1 in self.root.children.values():\n for child2 in child1.children.values():\n for child3 in child2.children.values():\n yield child3\n\n def get_level_four(self):\n for child1 in self.root.children.values():\n for child2 in child1.children.values():\n for child3 in child2.children.values():\n for child4 in child3.children.values():\n yield child4\n\n def get_url_from_node(self, node):\n url = \"\"\n while node.parent:\n url = node.content + '/' + url\n node = node.parent\n # url = node.content + '/' + url\n\n def check_url(self, url):\n pathSplitted = urlparse(url).path.strip('/').replace('//', '/').split('/')\n if not urlparse(url).netloc in self.root.children:\n return False\n\n currentNode = self.root.children[urlparse(url).netloc]\n\n level = 0\n exist = True\n while level < len(pathSplitted):\n if currentNode == None:\n print(\"?????????currentNode=None??????????\")\n print(url)\n print(currentNode)\n return False\n if pathSplitted[level] in currentNode.children:\n currentNode = currentNode.children[pathSplitted[level]]\n level += 1\n else:\n return False\n if '' in currentNode.children:\n exist = True\n else:\n exist = False\n\n return exist\n\n def get_node(self, url):\n pathSplitted = urlparse(url).path.strip('/').split('/')\n if not urlparse(url).netloc in self.root.children:\n return None\n\n currentNode = self.root.children[urlparse(url).netloc]\n\n level = 0\n while level < len(pathSplitted):\n if pathSplitted[level] in currentNode.children:\n currentNode = currentNode.children[pathSplitted[level]]\n level += 1\n else:\n return None\n\n return currentNode\n\n def get_all_url(self):\n # return a list, huge memory!!!\n urlList = []\n for url, node in self.root.children.items():\n self._get_all_url_aux(urlList, url, node)\n # for x in self._get_all_url_aux(url, node):\n # yield x\n return urlList\n\n def _get_all_url_aux(self, urlList, url, root):\n if '' in root.children:\n urlList.append(url.strip(\"/:\\t \\n\"))\n for url2, node in root.children.items():\n if url2:\n self._get_all_url_aux(urlList, url + '/' + url2, node)\n\n def find_keyword_in_url(self, keyword, maxDepth=10):\n urlList = []\n for url, node in self.root.children.items():\n self._find_keyword_in_url_aux(keyword, urlList, url, node)\n return urlList\n\n def _find_keyword_in_url_aux(self, keyword, urlList, url, root):\n for url2, node in root.children.items():\n if keyword in url2:\n # add the whole tree\n self._get_all_url_aux(urlList, url + '/' + url2, node)\n else:\n if url2:\n self._find_keyword_in_url_aux(keyword, urlList, url + '/' + url2, node)\n\n def get_root_content(self, url):\n if not url.startswith('http://'):\n url = 'http://' + url\n urlParseResult = urlparse(url)\n root = self.root.children[urlParseResult.netloc]\n return root.content\n","sub_path":"worker/websiteTree.py","file_name":"websiteTree.py","file_ext":"py","file_size_in_byte":5538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"579927401","text":"import threading\nimport time\nimport queue\nfrom multiprocessing import Queue\nimport cv2\nframes = Queue(10)\n\nclass ImageGrabber(threading.Thread):\n def __init__(self, ID):\n threading.Thread.__init__(self)\n self.ID=ID\n self.cam=cv2.VideoCapture(ID)\n\n def Run(self):\n global frames\n while True:\n ret,frame=self.cam.read()\n frames.put(frame)\n time.sleep(0.1)\n\n\nclass Main(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n global frames\n while True:\n if(not frames.empty()):\n self.Currframe=frames.get()\n\n\n\ngrabber = ImageGrabber(0)\nmain = Main()\n\ngrabber.start()\nmain.start()\nmain.join()\ngrabber.join()","sub_path":"SVE SLIKE/RGB -slike 640-380/Threading cameras.py","file_name":"Threading cameras.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"277762559","text":"import requests # library for making http requests\nimport json\n\nclass PostcodesConnection:\n\n def __init__(self):\n self.parameter = ''\n self.path = 'https://api.postcodes.io/postcodes/'\n self.result = ''\n self. status = ''\n\n def look_up_one_postcode(self, post_code):\n connection = requests.get(self.path + post_code) # creating the connection with the API using the path and the parameter-(the postcode)\n #print(connection)\n\n dictionary_of_connection = connection.json() # creating the json (a hash) of all the data (postcodes)\n print(type(dictionary_of_connection))\n\n status = dictionary_of_connection['status'] # status key\n results = dictionary_of_connection['result'] # the result key\n\n self.result = results\n self.status = status\n\n #print(self.result)\n\n for item in self.result.keys():\n print(item, \":\", self.result[item])\n\n\n def output_region_country(self):\n\n print(self.result.keys())\n print(self.result['country'])\n print(self.result['region'])\n\n\n def output_lat_long(self):\n print(self.result['latitude'])\n print(self.result['longitude'])\n\n def output_all_details(self):\n\n for key in self.result:\n print(key, \":\", self.result[key])\n\n def output_one_value(self):\n print(\"\")\n\n def post_requestsssss(self,post_code):\n self.post_code = post_code\n self.path = 'https://api.postcodes.io/postcodes/'\n\n self.post_request_to_postcodes = ''\n self.json_body = json.dumps({\"postcodes\": self.post_code})\n self.headers = {'Content-Type': 'application/json'}\n\n print(self.json_body)\n\n self.post_request_postcodes = requests.post(self.path, headers=self.headers, data=self.json_body)\n\n\n","sub_path":"postcodes_requests.py","file_name":"postcodes_requests.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"306671401","text":"from django.contrib import admin\nfrom django.urls import path\nfrom todo.views import todoView,addTodo,deleteTodo,homePage\n\nurlpatterns = [\n path('', homePage),\n path('admin/', admin.site.urls),\n path('todo/', todoView),\n path('addTodo/', addTodo),\n path('deleteTodo//', deleteTodo)\n]\n","sub_path":"todo_list/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"594390323","text":"# -*- coding: utf-8 -*-\nimport sys\nimport re\nimport os\nimport io\nfrom alchemist import management\nimport py\n\n\ndef strip_colors(text):\n return re.sub(\"\\x1b\\[\\d+m\", \"\", text)\n\n\nclass BaseTest:\n\n def setup(self):\n # Unload all alchemist.* modules and test packages.\n for name in list(sys.modules.keys()):\n for test in ['a', 'a.b', 'a.b.c', 'example', 'alchemist']:\n if name.startswith(test) and name in sys.modules:\n del sys.modules[name]\n\n\nclass TestDiscover:\n\n def setup(self):\n self.cwd = os.getcwd()\n self.base = os.path.join(os.path.dirname(__file__), '..')\n\n def teardown(self):\n os.chdir(self.cwd)\n\n def test_same_level(self):\n os.chdir(os.path.join(self.base, 'packages'))\n\n application = management.discover()\n\n assert application is not None\n assert application.name == 'a'\n\n def test_nested(self):\n os.chdir(os.path.join(self.base, 'discover', 'nested'))\n\n application = management.discover()\n\n assert application is not None\n assert application.name == 'a'\n\n def test_nested_too_low(self):\n os.chdir(os.path.join(self.base, 'discover'))\n\n application = management.discover()\n\n assert application is None\n\n def test_basic(self):\n os.chdir(os.path.join(self.base, 'discover', 'basic', 'src'))\n\n application = management.discover()\n\n assert application is not None\n assert application.name == 'basic'\n\n def test_up_one_level(self):\n os.chdir(os.path.join(self.base, 'packages', 'a'))\n\n application = management.discover()\n\n assert application is not None\n assert application.name == 'a'\n\n def test_up_two_levels(self):\n os.chdir(os.path.join(self.base, 'packages', 'a', 'b'))\n\n application = management.discover()\n\n assert application is not None\n assert application.name == 'a'\n\n def test_up_three_levels(self):\n os.chdir(os.path.join(self.base, 'packages', 'a', 'b', 'c'))\n\n application = management.discover()\n\n assert application is not None\n assert application.name == 'a'\n\n\nclass TestCommand(BaseTest):\n\n def setup(self):\n self.argv = sys.argv\n self.cwd = os.getcwd()\n self.base = os.path.join(os.path.dirname(__file__), '..')\n\n def teardown(self):\n sys.argv = self.argv\n os.chdir(self.cwd)\n\n def test_show_nested(self):\n os.chdir(os.path.join(self.base, 'packages', 'a'))\n\n capture = py.io.StdCaptureFD()\n management.run(['show'])\n\n out, _ = capture.done()\n\n assert out.read() == \"\\n\"\n\n def test_run_show(self):\n os.chdir(os.path.join(self.base, 'packages', 'a'))\n sys.argv = ['alchemist', 'show']\n\n # Prevent exit.\n exit = sys.exit\n sys.exit = lambda status: status\n\n capture = py.io.StdCaptureFD()\n management.Manager().run()\n\n out, _ = capture.done()\n\n assert out.read() == \"\\n\"\n\n # Undo exit prevention.\n sys.exit = exit\n\n def test_db_init_nested(self):\n os.chdir(os.path.join(self.base, 'packages', 'a'))\n\n capture = py.io.StdCaptureFD()\n management.run(['db', 'init'])\n\n out, err = capture.done()\n\n text = strip_colors(err.read())\n lines = [x.strip() for x in text.split('\\n')]\n\n assert lines[0] == 'alchemist db init a'\n assert lines[3] == 'alchemist db init a.b'\n\n def test_db_init_nested_name(self):\n os.chdir(os.path.join(self.base, 'packages', 'a'))\n\n capture = py.io.StdCaptureFD()\n management.run(['db', 'init', 'a'])\n\n out, err = capture.done()\n\n text = strip_colors(err.read())\n lines = [x.strip() for x in text.split('\\n')]\n\n assert lines[0] == 'alchemist db init a'\n assert len(lines) == 4\n\n def test_db_clear_nested(self):\n os.chdir(os.path.join(self.base, 'packages', 'a'))\n\n capture = py.io.StdCaptureFD()\n management.run(['db', 'clear'])\n\n out, err = capture.done()\n\n text = strip_colors(err.read())\n lines = [x.strip() for x in text.split('\\n')]\n\n assert lines[0] == 'alchemist db clear a.b'\n assert lines[1] == 'alchemist db clear a'\n\n def test_db_flush_nested(self):\n os.chdir(os.path.join(self.base, 'packages', 'a'))\n\n capture = py.io.StdCaptureFD()\n management.run(['db', 'flush'])\n\n out, err = capture.done()\n\n text = strip_colors(err.read())\n lines = [x.strip() for x in text.split('\\n')]\n\n assert lines[0] == 'alchemist db flush a.b'\n assert lines[1] == 'alchemist db flush a'\n\n def test_shell_context(self):\n os.chdir(os.path.join(self.base, 'packages', 'a'))\n\n application = management.discover()\n with application.app_context():\n from alchemist.commands import shell\n from a import models\n\n context = shell._make_context(quiet=True)\n\n assert 'session' in context\n assert 'db' in context\n assert 'ABlock' in context\n assert context['ABlock'] == models.ABlock\n","sub_path":"tests/alchemist/test_management.py","file_name":"test_management.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"85322146","text":"import os\nfrom flask import json\nfrom bson import ObjectId\nfrom pymongo import MongoClient\n\nclass CommonModel:\n def __init__(self):\n self.db = MongoClient('localhost', 27017).iins_sys\n\n def get_insurance_company_list(self):\n result = list(self.db.insurance_companies.find())\n for res in result:\n res['_id'] =str(res['_id'])\n return result\n\n def get_insurance_company(self,id):\n result = self.db.insurance_companies.find_one({\"_id\":id})\n result['_id'] =str(result['_id'])\n return result\n\n def get_provinces_list(self):\n result = list(self.db.canada_provinces.find())\n for res in result:\n res['_id'] =str(res['_id'])\n return result\n\nclass InitDatabaseModel:\n\n db= MongoClient('localhost', 27017).iins_sys\n path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'json')\n\n def initializeConfigurationDatabase(self):\n if self.db.configuration.find({}).count() == 0:\n with open(os.path.join(self.path, 'configuration.json')) as data:\n params = json.load(data)\n data.close()\n self.db.configuration.update_one({'paramsName': params['paramsName']}, {\"$set\": params}, upsert=True)\n if self.db.users.find({'username': 'Admin'}).count() == 0:\n with open(os.path.join(self.path, 'accounts.json')) as data:\n params = json.load(data)\n data.close()\n self.db.users.update_one({'username': params['username']}, {\"$set\": params}, upsert=True)\n\n def initializeCommonDatabase(self):\n if self.db.workflow_temp.find({}).count() == 0:\n with open(os.path.join(self.path, 'workflow.json')) as data:\n params = json.load(data)\n data.close()\n for param in params:\n self.db.workflow_temp.update_one({'jobID': param['jobID'],'taskID': param['taskID']}, {\"$set\": param}, upsert=True)\n\n if self.db.insurance_companies.find({}).count() == 0:\n with open(os.path.join(self.path, 'insurance_companies.json')) as data:\n params = json.load(data)\n data.close()\n for param in params:\n self.db.insurance_companies.update_one({'_id': param['IC_ID']}, {\"$set\": param}, upsert=True)\n\n if self.db.canada_provinces.find({}).count() == 0:\n with open(os.path.join(self.path, 'canada_provinces.json')) as data:\n params = json.load(data)\n data.close()\n for param in params:\n self.db.canada_provinces.update_one({\"Abbr\":param['Abbr']}, {\"$set\": param}, upsert=True)\n\n","sub_path":"gameServer/common/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"614630863","text":"from django.conf.urls import url,include\nfrom django.contrib import admin\nfrom basic_app import views\n\n#TEMPLATE URLS!\n\napp_name = \"basic_app\"\n\nurlpatterns = [\n url(r\"^register/$\",views.register,name=\"register\"),\n url(r'^user_login/$',views.user_login,name=\"login\"),\n url(r'^logout/$',views.user_logout,name=\"logout\"),\n url(r'^special/',views.special,name=\"special\"),\n]\n","sub_path":"learning_users/basic_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"647110608","text":"# encoding: utf-8\n\nimport os\n\nimport numpy as np\n\nfrom histolab.slide import Slide\nfrom histolab.tiler import GridTiler, RandomTiler, ScoreTiler\nfrom histolab.scorer import NucleiScorer\n\nfrom ..fixtures import SVS\nfrom ..util import load_expectation\n\n\nclass DescribeRandomTiler:\n def it_locates_tiles_on_the_slide(self, tmpdir):\n slide = Slide(SVS.CMU_1_SMALL_REGION, os.path.join(tmpdir, \"processed\"))\n slide.save_scaled_image(10)\n random_tiles_extractor = RandomTiler(\n tile_size=(512, 512), n_tiles=2, level=0, seed=42, check_tissue=False\n )\n expectation = load_expectation(\n \"tiles-location-images/cmu-1-small-region-tiles-location-random\",\n type_=\"png\",\n )\n tiles_location_img = random_tiles_extractor.locate_tiles(slide, scale_factor=10)\n\n np.testing.assert_array_almost_equal(\n np.asarray(tiles_location_img), expectation\n )\n\n\nclass DescribeGridTiler:\n def it_locates_tiles_on_the_slide(self, tmpdir):\n slide = Slide(SVS.CMU_1_SMALL_REGION, os.path.join(tmpdir, \"processed\"))\n grid_tiles_extractor = GridTiler(\n tile_size=(512, 512),\n level=0,\n check_tissue=False,\n )\n expectation = load_expectation(\n \"tiles-location-images/cmu-1-small-region-tiles-location-grid\", type_=\"png\"\n )\n tiles_location_img = grid_tiles_extractor.locate_tiles(slide, scale_factor=10)\n\n np.testing.assert_array_almost_equal(\n np.asarray(tiles_location_img), expectation\n )\n\n\nclass DescribeScoreTiler:\n def it_locates_tiles_on_the_slide(self, tmpdir):\n slide = Slide(SVS.CMU_1_SMALL_REGION, os.path.join(tmpdir, \"processed\"))\n scored_tiles_extractor = ScoreTiler(\n scorer=NucleiScorer(),\n tile_size=(512, 512),\n n_tiles=100,\n level=0,\n check_tissue=False,\n )\n expectation = load_expectation(\n \"tiles-location-images/cmu-1-small-region-tiles-location-scored\",\n type_=\"png\",\n )\n scored_location_img = scored_tiles_extractor.locate_tiles(\n slide, scale_factor=10\n )\n\n np.testing.assert_array_almost_equal(\n np.asarray(scored_location_img), expectation\n )\n","sub_path":"tests/integration/test_tiler.py","file_name":"test_tiler.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"583413733","text":"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals \n\nimport time\nimport os\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import pearsonr\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Dropout, Activation, Flatten\nfrom keras.optimizers import SGD, Adadelta, Adagrad, Adam\nfrom keras.regularizers import l2\nfrom keras.datasets import mnist\nfrom keras.utils import np_utils\n\nimport tensorflow as tf\n\nimport sys\nsys.path.append('../') \n\nimport random\nrandom.seed(5001)\nfrom influence.logisticRegressionWithLBFGS import LogisticRegressionWithLBFGS\nfrom tensorflow.contrib.learn.python.learn.datasets import base\nfrom influence.dataset import DataSet\n\nfrom keras.backend.tensorflow_backend import set_session, clear_session\nfrom influence.small_CNN import SmallCNN\n\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.2\nclear_session()\nset_session(tf.Session(config=config))\n\n\nExperiments = 3\n\nbatch_size = 128\nnb_classes = 10\n\n#use a large number of epochs\nnb_epoch = 50\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n# number of convolutional filters to use\nnb_filters = 32\n\n# size of pooling area for max pooling\nnb_pool = 5\n# convolution kernel size\nnb_conv = 3\n\nscore=0\nall_accuracy = 0\nacquisition_iterations = 98\n\ninitial_learning_rate = 0.001 \ndecay_epochs = [1000, 10000]\n\n\n#use a large number of dropout iterations\ndropout_iterations = 100\n\nQueries = 10\n\nExperiments_All_Accuracy = np.zeros(shape=(acquisition_iterations+1))\n\n\nfor e in range(Experiments):\n print('Experiment Number ', e)\n\n # the data, shuffled and split between tran and test sets\n (X_train_All, y_train_All), (X_test, y_test) = mnist.load_data()\n\n X_train_All = X_train_All.reshape(X_train_All.shape[0], img_rows, img_cols, 1)\n\n random_split = np.asarray(random.sample(range(0,X_train_All.shape[0]), X_train_All.shape[0]))\n\n X_train_All = X_train_All[random_split, :, :, :]\n y_train_All = y_train_All[random_split]\n\n\n X_valid = X_train_All[10000:15000, :, :, :]\n y_valid = y_train_All[10000:15000]\n\n X_Pool = X_train_All[20000:60000, :, :, :]\n y_Pool = y_train_All[20000:60000]\n\n\n X_train_All = X_train_All[0:10000, :, :, :]\n y_train_All = y_train_All[0:10000]\n\n\n #training data to have equal distribution of classes\n idx_0 = np.array( np.where(y_train_All==0) ).T\n idx_0 = idx_0[0:2,0]\n X_0 = X_train_All[idx_0, :, :, :]\n y_0 = y_train_All[idx_0]\n\n idx_1 = np.array( np.where(y_train_All==1) ).T\n idx_1 = idx_1[0:2,0]\n X_1 = X_train_All[idx_1, :, :, :]\n y_1 = y_train_All[idx_1]\n\n idx_2 = np.array( np.where(y_train_All==2) ).T\n idx_2 = idx_2[0:2,0]\n X_2 = X_train_All[idx_2, :, :, :]\n y_2 = y_train_All[idx_2]\n\n idx_3 = np.array( np.where(y_train_All==3) ).T\n idx_3 = idx_3[0:2,0]\n X_3 = X_train_All[idx_3, :, :, :]\n y_3 = y_train_All[idx_3]\n\n idx_4 = np.array( np.where(y_train_All==4) ).T\n idx_4 = idx_4[0:2,0]\n X_4 = X_train_All[idx_4, :, :, :]\n y_4 = y_train_All[idx_4]\n\n idx_5 = np.array( np.where(y_train_All==5) ).T\n idx_5 = idx_5[0:2,0]\n X_5 = X_train_All[idx_5, :, :, :]\n y_5 = y_train_All[idx_5]\n\n idx_6 = np.array( np.where(y_train_All==6) ).T\n idx_6 = idx_6[0:2,0]\n X_6 = X_train_All[idx_6, :, :, :]\n y_6 = y_train_All[idx_6]\n\n idx_7 = np.array( np.where(y_train_All==7) ).T\n idx_7 = idx_7[0:2,0]\n X_7 = X_train_All[idx_7, :, :, :]\n y_7 = y_train_All[idx_7]\n\n idx_8 = np.array( np.where(y_train_All==8) ).T\n idx_8 = idx_8[0:2,0]\n X_8 = X_train_All[idx_8, :, :, :]\n y_8 = y_train_All[idx_8]\n\n idx_9 = np.array( np.where(y_train_All==9) ).T\n idx_9 = idx_9[0:2,0]\n X_9 = X_train_All[idx_9, :, :, :]\n y_9 = y_train_All[idx_9]\n\n X_train = np.concatenate((X_0, X_1, X_2, X_3, X_4, X_5, X_6, X_7, X_8, X_9), axis=0 )\n y_train = np.concatenate((y_0, y_1, y_2, y_3, y_4, y_5, y_6, y_7, y_8, y_9), axis=0 )\n\n\n print('X_train shape:', X_train.shape)\n print(X_train.shape[0], 'train samples')\n\n print('Distribution of Training Classes:', np.bincount(y_train))\n\n\n X_train = X_train.astype('float32')\n X_test = X_test.astype('float32')\n X_valid = X_valid.astype('float32')\n X_Pool = X_Pool.astype('float32')\n X_train /= 255\n X_valid /= 255\n X_Pool /= 255\n X_test /= 255\n\n Y_test = y_test#np_utils.to_categorical(y_test, nb_classes)\n Y_valid = y_valid#np_utils.to_categorical(y_valid, nb_classes)\n Y_Pool = y_Pool#np_utils.to_categorical(y_Pool, nb_classes)\n\n #loss values in each experiment\n Pool_Valid_Loss = np.zeros(shape=(nb_epoch, 1)) \n Pool_Train_Loss = np.zeros(shape=(nb_epoch, 1)) \n Pool_Valid_Acc = np.zeros(shape=(nb_epoch, 1)) \n Pool_Train_Acc = np.zeros(shape=(nb_epoch, 1)) \n x_pool_All = np.zeros(shape=(1))\n\n Y_train = y_train # np_utils.to_categorical(y_train, nb_classes)\n\n data_sets = base.Datasets(train = DataSet(X_train, Y_train), \n \t\t\t validation = DataSet(X_valid, Y_valid),\n \t\t\t test = DataSet(X_test, Y_test))\n\n model = SmallCNN(\n batch_size=batch_size,\n data_sets=data_sets,\n num_classes = nb_classes,\n initial_learning_rate = initial_learning_rate,\n decay_epochs=decay_epochs,\n mini_batch=True,\n train_dir='output', \n log_dir='log',\n model_name='mnist_all_cnn_c')\n\n hist = model.train(num_epochs=nb_epoch)\n\n Train_Result_Optimizer = hist.history\n Train_Loss = np.asarray(Train_Result_Optimizer.get('loss'))\n Train_Loss = np.array([Train_Loss]).T\n Valid_Loss = np.asarray(Train_Result_Optimizer.get('val_loss'))\n Valid_Loss = np.asarray([Valid_Loss]).T\n Train_Acc = np.asarray(Train_Result_Optimizer.get('acc'))\n Train_Acc = np.array([Train_Acc]).T\n Valid_Acc = np.asarray(Train_Result_Optimizer.get('val_acc'))\n Valid_Acc = np.asarray([Valid_Acc]).T\n\n Pool_Train_Loss = Train_Loss\n Pool_Valid_Loss = Valid_Loss\n Pool_Train_Acc = Train_Acc\n Pool_Valid_Acc = Valid_Acc\n\n print('Evaluating Test Accuracy Without Acquisition')\n\n score, acc = model.evaluate()\n\n all_accuracy = acc\n\n print('Starting Active Learning in Experiment ', e)\n\n for i in range(acquisition_iterations):\n \n print('POOLING ITERATION', i)\n\n pool_subset = 2000\n pool_subset_dropout = np.asarray(random.sample(range(0,X_Pool.shape[0]), pool_subset))\n X_Pool_Dropout = X_Pool[pool_subset_dropout, :, :, :]\n y_Pool_Dropout = y_Pool[pool_subset_dropout]\n\n approx_params={'scale':100, 'recursion_depth':5000, 'damping':0.1, 'batch_size':1, 'num_samples':10}\n influences = model.get_influence_on_test_loss_unlab(X_unlab=X_Pool_Dropout, Y_unlab=y_Pool_Dropout, \n approx_params=approx_params)\n x_pool_index = influences.argsort()[:Queries]\n\n #store all the pooled images indexes\n x_pool_All = np.append(x_pool_All, x_pool_index)\n\n #saving pooled images\n\n # #save only 3 images per iteration\n # for im in range(x_pool_index[0:2].shape[0]):\n # Image = X_Pool[x_pool_index[im], :, :, :]\n # img = Image.reshape((28,28))\n #sp.misc.imsave('/home/ri258/Documents/Project/Active-Learning-Deep-Convolutional-Neural-Networks/ConvNets/Cluster_Experiments/Dropout_Bald/Pooled_Images/' + 'Experiment_' + str(e) + 'Pool_Iter'+str(i)+'_Image_'+str(im)+'.jpg', img)\n\n print(X_Pool_Dropout.shape)\n\n Pooled_X = X_Pool_Dropout[x_pool_index, 0:32,0:32,0:3]\n Pooled_Y = y_Pool_Dropout[x_pool_index] \n\n #first delete the random subset used for test time dropout from X_Pool\n #Delete the pooled point from this pool set (this random subset)\n #then add back the random pool subset with pooled points deleted back to the X_Pool set\n delete_Pool_X = np.delete(X_Pool, (pool_subset_dropout), axis=0)\n delete_Pool_Y = np.delete(y_Pool, (pool_subset_dropout), axis=0)\n\n delete_Pool_X_Dropout = np.delete(X_Pool_Dropout, (x_pool_index), axis=0)\n delete_Pool_Y_Dropout = np.delete(y_Pool_Dropout, (x_pool_index), axis=0)\n\n X_Pool = np.concatenate((X_Pool, X_Pool_Dropout), axis=0)\n y_Pool = np.concatenate((y_Pool, y_Pool_Dropout), axis=0)\n \n print('Acquised Points added to training set')\n\n X_train = np.concatenate((X_train, Pooled_X), axis=0)\n y_train = np.concatenate((y_train, Pooled_Y), axis=0)\n\n\n # convert class vectors to binary class matrices\n Y_train = y_train\n\n clear_session()\n\n data_sets = base.Datasets(train = DataSet(X_train, Y_train), \n validation = DataSet(X_valid, Y_valid),\n test = DataSet(X_test, Y_test))\n\n model = SmallCNN(\n batch_size=batch_size,\n data_sets=data_sets,\n num_classes = nb_classes,\n initial_learning_rate = initial_learning_rate,\n decay_epochs=decay_epochs,\n mini_batch=True,\n train_dir='output', \n log_dir='log',\n model_name='mnist_all_cnn_c')\n\n hist = model.train(num_epochs=nb_epoch)\n Train_Result_Optimizer = hist.history\n Train_Loss = np.asarray(Train_Result_Optimizer.get('loss'))\n Train_Loss = np.array([Train_Loss]).T\n Valid_Loss = np.asarray(Train_Result_Optimizer.get('val_loss'))\n Valid_Loss = np.asarray([Valid_Loss]).T\n Train_Acc = np.asarray(Train_Result_Optimizer.get('acc'))\n Train_Acc = np.array([Train_Acc]).T\n Valid_Acc = np.asarray(Train_Result_Optimizer.get('val_acc'))\n Valid_Acc = np.asarray([Valid_Acc]).T\n\n #Accumulate the training and validation/test loss after every pooling iteration - for plotting\n Pool_Valid_Loss = np.append(Pool_Valid_Loss, Valid_Loss, axis=1)\n Pool_Train_Loss = np.append(Pool_Train_Loss, Train_Loss, axis=1)\n Pool_Valid_Acc = np.append(Pool_Valid_Acc, Valid_Acc, axis=1)\n Pool_Train_Acc = np.append(Pool_Train_Acc, Train_Acc, axis=1) \n\n print('Evaluate Model Test Accuracy with pooled points')\n\n score, acc = model.evaluate()\n print('Test score:', score)\n print('Test accuracy:', acc)\n all_accuracy = np.append(all_accuracy, acc)\n\n print('Use this trained model with pooled points for Dropout again')\n\n print('Storing Accuracy Values over experiments')\n Experiments_All_Accuracy = Experiments_All_Accuracy + all_accuracy\n\n\n print('Saving Results Per Experiment')\n root = \"tmp/\"\n np.save( root + 'Influence_Q10_N1000_Train_Loss_'+ 'Experiment_' + str(e) + '.npy', Pool_Train_Loss)\n np.save( root + 'Influence_Q10_N1000_Valid_Loss_'+ 'Experiment_' + str(e) + '.npy', Pool_Valid_Loss)\n np.save( root + 'Influence_Q10_N1000_Train_Acc_'+ 'Experiment_' + str(e) + '.npy', Pool_Train_Acc)\n np.save( root + 'Influence_Q10_N1000_Valid_Acc_'+ 'Experiment_' + str(e) + '.npy', Pool_Valid_Acc)\n np.save( root +'Influence_Q10_N1000_Pooled_Image_Index_'+ 'Experiment_' + str(e) + '.npy', x_pool_All)\n np.save( root + 'Influence_Q10_N1000_Accuracy_Results_'+ 'Experiment_' + str(e) + '.npy', all_accuracy)\n\nprint('Saving Average Accuracy Over Experiments')\n\nAverage_Accuracy = np.divide(Experiments_All_Accuracy, Experiments)\n\nnp.save( root + 'Influence_Q10_N1000_Average_Accuracy'+'.npy', Average_Accuracy)\n\n\n\n\n","sub_path":"ifa/run_training.py","file_name":"run_training.py","file_ext":"py","file_size_in_byte":11612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"305311302","text":"import sys,os,logging,re,pprint,string,datetime,gc,json\nimport courseraLib as co\nLOGGING_LVL={\n\t\"debug\":logging.DEBUG,\n\t\"info\":logging.INFO,\n\t\"warning\":logging.WARNING,\n\t\"error\":logging.ERROR,\n\t\"critical\":logging.CRITICAL,\n}\nlogging.basicConfig(level=LOGGING_LVL.get(sys.argv[1],'debug'),format='%(asctime)s-%(levelname)s-%(message)s')\n\n\n#loading training files\nlogging.debug(os.getcwd())\nif input('debug or run?\\n')=='run':\n\tdataFilePath=os.path.join(os.getcwd(),'training-data')\nelse:\n\tdataFilePath=os.path.join(os.getcwd(),'mini-data')\ndataFileDict={}\nfor file in os.listdir(dataFilePath):\n\tlogging.debug(file)\n\tlogging.debug(type(file))\n\tlogging.debug(str(os.path.getsize(os.path.join(dataFilePath,file))/1024/1024)+' MB')\n\tfileName=file.split(\"-\")\n\tdataFileDict[fileName[0]]=\\\n\t{\n\t\"path\":os.path.join(dataFilePath,file),\n\t\"size\":os.path.getsize(os.path.join(dataFilePath,file))\n\t}\npprint.pprint(dataFileDict)\n\n\n# open desired text file\nfile2read=input(\"which file to read?\\n type all to generate all\\n\"+\" \".join(dataFileDict.keys())+\"\\n\")\nfileList=[]\nif file2read.lower()==\"all\":\n\tfileList=list(dataFileDict.keys())\nelse:\n\tfileList.append(file2read)\n\nn_model=int(input('the n value in n-gram model?\\n'))\nr_max=int(input('output_length?(put a number)\\n'))\nskim=input('skim?(y/n)\\n').lower()\nskim_ct=int(input('skim threshold?(put a number)\\n'))\n\nfor f in fileList:\n\tprint(\"Working on \",f,\"...\\n\")\n\tCorpus=co.prepareCorpus(dataFileDict[f]['path'])\n\tngramDictObj=co.ExtractCorpus(Corpus,n_model)\n\tif skim=='y':\n\t\tco.skimDict(ngramDictObj,mm=skim_ct)\n\tco.rankingDict(ngramDictObj,parent_ct=ngramDictObj['_c'],max=r_max)\n\tco.skimVacantDict(ngramDictObj)\n\tsavetopath=os.path.join(os.getcwd(),'ignoredFiles','DictOutput',f+'-nGramDict.json')\n\tf1=open(savetopath,\"w\")\n\tjson.dump(ngramDictObj,f1)\n\tf1.close\n\tgc.collect()\n","sub_path":"testing/make-dict.py","file_name":"make-dict.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"430271604","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom flask import Flask\nfrom flask import request\nfrom flask import Response, send_from_directory\nimport flask\n# from flask_cors import CORS\nfrom sys import argv\nimport os, sys\nimport json\n\n# json.dumps(cardsets[29])\npng_folder = sys.argv[1]\napp = Flask(__name__)\n\nalready_selected = set(eval(open(\"icon-selected.txt\", encoding='utf8').read()))\n\n@app.route(\"/list\")\ndef get_all():\n print(list(already_selected))\n return json.dumps(list(already_selected))\n\n@app.route(\"/\")\ndef home():\n return open(\"emoji-png-categories.html\", encoding='utf8').read()\n\n@app.route(\"/add\", methods = ['POST'])\ndef add():\n if request.method == 'POST':\n c = request.data.decode('utf-8')\n # already_selected.add(c.replace('http://localhost:5000/png/', ''))\n if c in already_selected:\n already_selected.remove(c)\n else:\n already_selected.add(c)\n # f = open(\"icon-selected.txt\", 'a', encoding='utf8')\n f = open(\"icon-selected.txt\", 'w', encoding='utf8')\n # f.write(repr(c)+'\\n')\n f.write(repr(already_selected))\n f.close()\n return \"received and wrote %s\"%repr(c)\n else:\n return \"PLZ POST\"\n\n\n@app.route('/png/')\ndef send_png(path):\n # print(png_folder, path)\n return send_from_directory(png_folder, path)\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n\n\n","sub_path":"_projlab/emoji/icon-select.py","file_name":"icon-select.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"486811270","text":"# %%\n'''\n## How to Train the Generator Model\nThe weights in the generator model are updated based on the performance of the discriminator\nmodel. When the discriminator is good at detecting fake samples, the generator is updated more,\nand when the discriminator model is relatively poor or confused when detecting fake samples,\nthe generator model is updated less. This defines the zero-sum or adversarial relationship\nbetween these two models. There may be many ways to implement this using the Keras API,\nbut perhaps the simplest approach is to create a new model that combines the generator and\ndiscriminator models.\n\nSpecifically, a new GAN model can be defined that stacks the generator and discriminator\nsuch that the generator receives as input random points in the latent space and generates8.5. How to Train the Generator Model 151\nsamples that are fed into the discriminator model directly, classified, and the output of this\nlarger model can be used to update the model weights of the generator. To be clear, we are not\ntalking about a new third model, just a new logical model that uses the already-defined layers\nand weights from the standalone generator and discriminator models. Only the discriminator\nis concerned with distinguishing between real and fake examples, therefore the discriminator\nmodel can be trained in a standalone manner on examples of each, as we did in the section on\nthe discriminator model above.\n\nThe generator model is only concerned with the discriminator’s performance on fake examples.\nTherefore, we will mark all of the layers in the discriminator as not trainable when it is part\nof the GAN model so that they cannot be updated and overtrained on fake examples. When\ntraining the generator via this logical GAN model, there is one more important change. We\nwant the discriminator to think that the samples output by the generator are real, not fake.\nTherefore, when the generator is trained as part of the GAN model, we will mark the generated\nsamples as real (class = 1).\n\nWhy would we want to do this? We can imagine that the discriminator will then classify\nthe generated samples as not real (class = 0) or a low probability of being real (0.3 or 0.5). The\nbackpropagation process used to update the model weights will see this as a large error and will\nupdate the model weights (i.e. only the weights in the generator) to correct for this error, in\nturn making the generator better at generating good fake samples. Let’s make this concrete.\n❼ Inputs: Point in latent space, e.g. a 100-element vector of Gaussian random numbers.\n❼ Outputs: Binary classification, likelihood the sample is real (or fake).\n\nThe define gan() function below takes as arguments the already-defined generator and\ndiscriminator models and creates the new, logical third model subsuming these two models.\nThe weights in the discriminator are marked as not trainable, which only affects the weights as\nseen by the GAN model and not the standalone discriminator model. The GAN model then\nuses the same binary cross-entropy loss function as the discriminator and the efficient Adam\nversion of stochastic gradient descent with the learning rate of 0.0002 and momentum of 0.5,\nrecommended when training deep convolutional GANs.\n'''\n\n# %%\n# demonstrate creating the three models in the gan\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Reshape\nfrom keras.layers import Flatten\nfrom keras.layers import Conv2D\nfrom keras.layers import Conv2DTranspose\nfrom keras.layers import LeakyReLU\nfrom keras.layers import Dropout\nfrom keras.utils.vis_utils import plot_model\n\n# define the standalone discriminator model\ndef define_discriminator(in_shape=(32,32,3)):\n\tmodel = Sequential()\n\t# normal\n\tmodel.add(Conv2D(64, (3,3), padding='same', input_shape=in_shape))\n\tmodel.add(LeakyReLU(alpha=0.2))\n\t# downsample\n\tmodel.add(Conv2D(128, (3,3), strides=(2,2), padding='same'))\n\tmodel.add(LeakyReLU(alpha=0.2))\n\t# downsample\n\tmodel.add(Conv2D(128, (3,3), strides=(2,2), padding='same'))\n\tmodel.add(LeakyReLU(alpha=0.2))\n\t# downsample\n\tmodel.add(Conv2D(256, (3,3), strides=(2,2), padding='same'))\n\tmodel.add(LeakyReLU(alpha=0.2))\n\t# classifier\n\tmodel.add(Flatten())\n\tmodel.add(Dropout(0.4))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = Adam(lr=0.0002, beta_1=0.5)\n\tmodel.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])\n\treturn model\n\n# define the standalone generator model\ndef define_generator(latent_dim):\n\tmodel = Sequential()\n\t# foundation for 4x4 image\n\tn_nodes = 256 * 4 * 4\n\tmodel.add(Dense(n_nodes, input_dim=latent_dim))\n\tmodel.add(LeakyReLU(alpha=0.2))\n\tmodel.add(Reshape((4, 4, 256)))\n\t# upsample to 8x8\n\tmodel.add(Conv2DTranspose(128, (4,4), strides=(2,2), padding='same'))\n\tmodel.add(LeakyReLU(alpha=0.2))\n\t# upsample to 16x16\n\tmodel.add(Conv2DTranspose(128, (4,4), strides=(2,2), padding='same'))\n\tmodel.add(LeakyReLU(alpha=0.2))\n\t# upsample to 32x32\n\tmodel.add(Conv2DTranspose(128, (4,4), strides=(2,2), padding='same'))\n\tmodel.add(LeakyReLU(alpha=0.2))\n\t# output layer\n\tmodel.add(Conv2D(3, (3,3), activation='tanh', padding='same'))\n\treturn model\n\n# define the combined generator and discriminator model, for updating the generator\ndef define_gan(g_model, d_model):\n\t# make weights in the discriminator not trainable\n\td_model.trainable = False\n\t# connect them\n\tmodel = Sequential()\n\t# add generator\n\tmodel.add(g_model)\n\t# add the discriminator\n\tmodel.add(d_model)\n\t# compile model\n\topt = Adam(lr=0.0002, beta_1=0.5)\n\tmodel.compile(loss='binary_crossentropy', optimizer=opt)\n\treturn model\n\n# size of the latent space\nlatent_dim = 100\n# create the discriminator\nd_model = define_discriminator()\n# create the generator\ng_model = define_generator(latent_dim)\n# create the gan\ngan_model = define_gan(g_model, d_model)\n# summarize gan model\ngan_model.summary()\n# plot gan model\nplot_model(gan_model, to_file='gan_plot.png', show_shapes=True, show_layer_names=True)\n\n# %%\nfrom PIL import Image\nfrom IPython.display import display # to display images\n\nimage = Image.open('gan_plot.png')\ndisplay(image)","sub_path":"chapter_08/07_summarize_composite.py","file_name":"07_summarize_composite.py","file_ext":"py","file_size_in_byte":6143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"160031543","text":"import fingerpi as fp\nimport fingerfunc as ff\nimport time\nimport RPi.GPIO as GPIO\nimport logging\nfrom states import *\n\n'''TODO\nName programm aendern\n'''\n####Logging Config\nlogging.basicConfig(level=logging.DEBUG, filename=\"logfileFinger\", filemode=\"a+\",\n format=\"%(asctime)-15s %(levelname)-8s %(message)s\")\n \nMOTOR_UP = 3\nMOTOR_DOWN = 5\nSTOPPER_UP = 11\nSTOPPER_DOWN = 13\nLED_RED=18\nLED_GREEN=16\nKEY=12\n\ndef userMode(finger,mode):\n finger.CmosLed()\n if ff.checkMotorState() == states['closed']:\n logging.info('Motor auf')\n err=ff.motor(actions['open'])\n if err == -1:\n ff.ledNotification(states['not_ok'])\n else: \n ff.ledSwitch(LED_RED)\n ff.ledSwitch(LED_GREEN,True)\n waittime=time.clock()\n while GPIO.input(KEY) !=1 and (time.clock() - waittime) < 300:\n #if ((time.clock()-waittime)>18): ff.ledNotification(states['not_ok'])\n pass \n ff.ledSwitch(LED_RED,True)\n ff.ledSwitch(LED_GREEN) \n if ff.checkMotorState() == states['opened']:\n logging.info('Motor schliessen')\n err=ff.motor(actions['close'])\n if err == -1:\n ff.ledNotification(states['not_ok'])\n logging.info('UserLogout')\n finger.CmosLed(True)\n \ndef adminMode(finger,mode):\n ff.ledSwitch(LED_GREEN, True)\n while mode == modes['Admin']:\n ff.waitforFinger(finger,states['Not_Pressed'])\n ff.waitforFinger(finger,states['Pressed'])\n err=ff.adminAction(finger,ff.getAdminCommand(ff.identifyFingerID(finger)))\n if err == -1:\n mode = modes['Default']\n logging.info('AdminLogout')\n ff.ledSwitch(LED_GREEN)\n\n#===============================================================================\nlogging.info('GPIO Init')\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(MOTOR_UP,GPIO.OUT)\nGPIO.setup(MOTOR_DOWN,GPIO.OUT)\nGPIO.setup(LED_GREEN,GPIO.OUT)\nGPIO.setup(LED_RED,GPIO.OUT)\nGPIO.setup(KEY,GPIO.IN,pull_up_down = GPIO.PUD_DOWN)\nGPIO.setup(STOPPER_UP,GPIO.IN,pull_up_down = GPIO.PUD_DOWN)\nGPIO.setup(STOPPER_DOWN,GPIO.IN,pull_up_down = GPIO.PUD_DOWN)\n#===============================================================================\nff.ledSwitch(LED_GREEN)\nff.ledSwitch(LED_RED,True)\nGPIO.output(MOTOR_UP,False)\nGPIO.output(MOTOR_DOWN,False)\nif ff.checkMotorState() ==states['opened']:\n err=ff.motor(actions['close'])\n if err == -1:\n ff.ledNotification(states['not_ok'])\n#===============================================================================\nlogging.info('Fingerprint Sensor Init')\nfinger = fp.FingerPi()\nfinger.Open(extra_info = True, check_baudrate = True)\nfinger.ChangeBaudrate(115200)\nfinger.CmosLed()\nlogging.info('ready')\n#===============================================================================\n\n#=========================SetAdmin_one==========================================\n# logging.info('SetAdminMode')\n# \n# logging.info('erster Admin')\n# finger.DeleteId(0)\n# ff.Enrollment(finger,0)\n# \n# logging.info('AdminCommand adminEnroll_NewUser')\n# finger.DeleteId(1)\n# ff.Enrollment(finger,1)\n# \n# logging.info('AdminCommand adminDetele_All_Users')\n# finger.DeleteId(2)\n# ff.Enrollment(finger,2)\n# \n# logging.info('AdminCommand adminOpenBox')\n# finger.DeleteId(3)\n# ff.Enrollment(finger,3)\n#===============================================================================\n\n#===============================================================================\n# #SetAdmin_two\n# #logging.info('zweiter Admin')\n# #finger.DeleteId(1)\n# #ff.Enrollment(finger,10)\n#===============================================================================\n\n#===============================================================================\n# logging.info('Delete all')\n# finger.DeleteAll()\n# response = finger.GetEnrollCount()\n# logging.info('EnrollCountNew: %d', response[0]['Parameter'])\n#===============================================================================\n\n#==========================NormalMode===========================================\nwhile(1):\n if GPIO.input(KEY) ==1:\n finger.CmosLed(True)\n logging.info('NormalMode')\n ff.waitforFinger(finger,states['Not_Pressed'])\n ff.waitforFinger(finger,states['Pressed'])\n mode = ff.setUserMode(ff.identifyFingerID(finger))\n if mode == modes['Admin']:\n logging.info('Adminmodus')\n adminMode(finger,mode)\n elif mode == modes['User']:\n logging.info('Usermodus')\n ff.ledNotification(states['ok'])\n userMode(finger,mode)\n else: \n logging.info('Defaultmodus')\n ff.ledNotification(states['not_ok'])\n finger.CmosLed() \n#===============================================================================\nlogging.info('Close Connection')\nfinger.CmosLed(False)\nfinger.Close()\nGPIO.cleanup()\n","sub_path":"fingerprint/fingerGo.py","file_name":"fingerGo.py","file_ext":"py","file_size_in_byte":4967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"358128752","text":"# 시작점이 물이 있는 위치인 넓이 우선 탐색 알고리즘\n\n\n# 대부분의 경우 일반 list보다 deque가 빠릅니다.\nfrom collections import deque \n\nWATER = 1\n\nclass Solution:\n def highestPeak(self, isWater):\n queue = deque([])\n \n # 지면의 높이를 저장할 리스트 제작.\n level = [[-1] * len(isWater[0]) for _ in range(len(isWater))]\n \n # 일단 물이 어디있는지를 탐색\n for i in range(len(isWater)):\n for j in range(len(isWater[0])):\n if isWater[i][j] == WATER:\n queue.append((i,j))\n level[i][j] = 0\n \n \n while(queue):\n i,j = queue.popleft()\n \n # 4방향을 보며 범위 밖으로 나가지 않았으면서 아직 다른 값으로 채워지지 않았으면 채우기\n if 0 <= i-1 and level[i-1][j] == -1:\n level[i-1][j] = level[i][j] + 1\n queue.append((i-1, j))\n \n if i+1 < len(level) and level[i+1][j] == -1:\n level[i+1][j] = level[i][j] + 1\n queue.append((i+1, j))\n \n if 0 <= j-1 and level[i][j-1] == -1:\n level[i][j-1] = level[i][j] + 1\n queue.append((i, j-1))\n \n if j+1 < len(level[0]) and level[i][j+1] == -1:\n level[i][j+1] = level[i][j] + 1\n queue.append((i, j+1))\n \n return level\n","sub_path":"algorithm/2022/0809_329_Longest_Increasing_Path_in_a_Matrix/myunghak.py","file_name":"myunghak.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"30005689","text":"import requests\nimport sys\n\ndef get_all_results(url, results=[]):\n data = requests.get(url).json()\n if data['next']:\n return get_all_results(data['next'], results)\n else:\n return results+data['results']\n\ndef is_build_complete(list_of_testjobs):\n if len(list_of_testjobs) < 1:\n return False\n for testrun in testjobs:\n if not testrun['fetched']:\n return False\n return True\n\nproject_slug = \"linux-mainline-oe\"\nbuilds_to_check = 10\nbase_url = \"https://qa-reports.linaro.org/api/\"\n\nproject_url = \"{}projects/?slug={}\".format(base_url, project_slug)\nprojects = requests.get(project_url).json()\nassert projects['count'] == 1\nbuilds = requests.get(projects['results'][0]['builds']).json()\n\nfor i in range(builds_to_check):\n testjobs = get_all_results(builds['results'][i]['testjobs'])\n if not is_build_complete(testjobs):\n sys.exit(\"Error, build {} in project {} has not yet completed\".\n format(builds['results'][i]['version'], project_slug))\n\n","sub_path":"lkft/api/check_mainline.py","file_name":"check_mainline.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"639728482","text":"# Material do Curso \n# Dominando Listas em Python\n# ministrado por Deyvison Borges \n# \n# Contatos\n# e-mail: web.dborges@gmail.com\n# github.com/deeborges\n# linkedin.com/in/deyvisonborges\n# insta: @dee.borges\n\nanimais = [\"gato\", \"cachorro\", \"peixe\", \"leao\"]\n\n# Parâmetros\n# animais[(indice inicial):(indice onde termina (sem inclui-lo))] '''\n\n#Exemplos\nanimais[0:3]\nanimais[:1]","sub_path":"11-slices.py","file_name":"11-slices.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"586346602","text":"#!/usr/bin/python\n# Filename: prepare_leap.py\n# Support Python 2.6/2.7\n# According to the leap-nodes.csv:\n# [IP, Hostname, Port, User, Password, Machine_type]\n# 1. Bypass ssh password from Manager node to other nodes\n# 2. Set all node's hostname according to csv file\n# 3. Synchronize /etc/hosts for nodes and set repo.leap.com to Manager node\n\nimport os\nimport sys\nimport re\nimport getopt\nimport ConfigParser\nimport time\nimport thread\n\n\n# Debug log\ndef dprint(info):\n if(debug):\n print(\"\\033[7;34;40m%s\" % info)\n\n\n# Step log\ndef sprint_start(info):\n if(debug == 0):\n progress.start(info)\n\n\ndef sprint_end(info):\n if(debug == 0):\n progress.stop()\n\n\n# Process log\ndef sprint(info):\n if (debug == 0):\n print(\"\\033[1;32;40m%s\" % info)\n\n\n# Process log\ndef pprint(info):\n if (silent == 0):\n print(\"\\033[7;32;40m%s\" % info)\n\n\n# Print to verify\ndef vprint(info):\n print(\"\\033[7;33;40m%s\" % info)\n\n\n# Print error log\ndef eprint(info):\n print(\"\\033[7;31;40m%s\" % info)\n\n\n# Exit with error code\ndef lexit(errcode):\n eprint(\"errcode %d\" % errcode)\n eprint(\"###########Leap Preparation Failed! ##############\")\n print(\"\\033[0m\")\n exit(errcode)\n\n\n# Convert \"./\" to getcwd()\ndef convert_dir(olddir):\n if olddir.startswith(\"./\"):\n return olddir.replace(\".\", os.getcwd(), 1)\n if olddir.startswith(\"/\"):\n return olddir\n else:\n return os.getcwd() + \"/\" + olddir\n\n\nclass Progress:\n def __init__(self):\n self._flag = False\n\n def timer(self, info):\n i = 0\n length = 6\n pg = ['|', '/', '-', '\\\\']\n while self._flag:\n sys.stdout.write(\"\\r%s %s\" % (info, length * pg[i]))\n sys.stdout.flush()\n i = (i + 1) % 4\n time.sleep(0.09)\n print(\"\\r%s\\033[1;32;40m%s\\033[0m\" % (info, \" [DONE]\"))\n thread.exit_thread()\n\n def start(self, info):\n self._flag = True\n thread.start_new_thread(self.timer, (info, ))\n\n def stop(self):\n self._flag = False\n time.sleep(1)\n\n\n# Default parameters\ndebug = 0\nsilent = 1\nstart_step = 1\nml_file = \"./leap-nodes.conf\"\ncentos_mount_point = \"/mnt/leap-os\"\nleap_work_dir = \"/opt/leap\"\ninstall_mode = \"link\"\nsetup_path = \"SETUP\"\nruntime_path = \"LEAP_RUNTIME\"\nleap_conf = \"./%s/leap.conf\" % setup_path\nleap_version = \"\"\nleap_os = \"\"\nleap_os_iso = \"\"\nleap_os_iso_path = \"\"\nleap_installer = \"\"\nmanager_rpms = []\nclient_rpms = []\n\n\n# Usage for help\ndef usage():\n print(\"Leap Installment Preparation Usage:\")\n print(\"prepare_leap.py \\\n [ -c | -d | -f ml.csv | -h | -n | -t step ]\")\n print(\"prepare_leap.py [--file=ml.csv]\")\n print(\"default machine-list.csv = ./machine-list.csv\")\n\n\n# Parse the argv[]\nargv_parse = [\"help\", \"mlfile=\"]\ntry:\n opts, args = getopt.getopt(sys.argv[1:], \"hcdf:i:o:t:\", argv_parse)\nexcept getopt.GetoptError:\n usage()\n lexit(-1)\nfor opt, arg in opts:\n if opt in (\"-h\", \"--help\"):\n usage()\n sys.exit()\n elif opt == '-c':\n install_mode = \"copy\"\n elif opt == '-d':\n debug = 1\n elif opt in (\"-f\", \"--file\"):\n ml_file = convert_dir(arg)\n elif opt == '-n':\n silent = 0\n elif opt == '-t':\n start_step = int(arg)\n\n# read leap config from leap.conf\nconf = ConfigParser.ConfigParser()\nconf.read(leap_conf)\nsections = conf.sections()\ndprint(sections)\nkvs = conf.items(\"leap\")\nfor kv in kvs:\n (key, value) = kv\n if key == 'version':\n leap_version = value\n if key == 'os':\n leap_os = value\n if key == 'os_iso':\n leap_os_iso = value\n leap_os_iso_path = \"%s/%s/%s\" \\\n % (os.getcwd(), runtime_path, leap_os_iso)\n if key == 'installer':\n leap_installer = \"./%s/%s\" % (setup_path, value)\n if key == 'work_dir':\n leap_work_dir = value\n\nkvs = conf.items(\"rpm preinstall\")\nfor kv in kvs:\n (key, value) = kv\n if value == 'manager':\n manager_rpms += [key]\n if value == 'client':\n client_rpms += [key]\n if value == 'all':\n manager_rpms += [key]\n client_rpms += [key]\n\n# Disable error log when silent mode is true\nif silent == 1:\n silent_log = \">/dev/null\"\nelse:\n silent_log = \" \"\n\n# Get [IP, Hostname, Port, User, Password, Machine_Type] list in\n# machine-list.csv\n\nif os.path.exists(ml_file):\n dprint(\"Machine-list file is OK\")\nelse:\n eprint(\"Please specify machine list file\")\n lexit(-1)\n\nmachines = []\nms_number = 0\nnn_number = 0\ncl_number = 0\nnumber = 0\nmanager_ip = ''\nf = file(ml_file)\nml_list = f.readlines()\nfor i in ml_list:\n dprint(i)\n number = number + 1\n machine = re.split(\"[\\t |,]\", i.replace(\"\\r\", \"\").replace(\"\\n\", \"\"))\n dprint(machine)\n ip = machine[0]\n hostname = machine[1]\n if machine[2] == '':\n port = 22\n else:\n port = machine[2]\n user = machine[3]\n password = machine[4]\n if machine[5] == 'MS':\n machine_type = \"Manager Node\"\n manager_ip = ip\n ms_number = ms_number + 1\n dprint(\"Manager ip = %s\" % manager_ip)\n elif machine[5] == 'NN':\n machine_type = \"Name Node\"\n nn_number = nn_number + 1\n elif machine[5] == \"C\":\n machine_type = \"Compute Node\"\n cl_number = cl_number + 1\n else:\n eprint(\"No %d's Machine type %s is wrong \" % (number, machine[4]))\n lexit(-2)\n\n re_ip = ('^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}'\n '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')\n if re.match(re_ip, ip) is None:\n eprint(\"No %d's ip address %s is wrong!\" % (number, ip))\n lexit(-3)\n\n re_port = '^\\d+$'\n if re.match(re_port, port) is None:\n eprint(\"No %d's port %s is wrong\" % (number, port))\n lexit(-4)\n\n re_fqdn = '^[a-zA-Z](\\w|\\-)+\\.(\\w|\\-)+.\\w+$'\n if re.match(re_fqdn, hostname) is None:\n eprint(\"No %d's hosname %s don't satisfy FQDN rule\" %\n (number, hostname))\n lexit(-5)\n\n machines.append([ip, hostname, user, password, port, machine_type])\n\nif (ms_number == 0):\n eprint(\"No Manager server defined\")\n lexit(-6)\n\n\nnumber = 0\ndprint(\"machine list:\")\nfor machine in machines:\n [ip, hostname, user, password, port, machine_type] = machine\n number = number + 1\n dprint(\"No %d: %s|%s|%s|%s|%s|%s\" %\n (number, ip, hostname, user, password, port, machine_type))\ndprint(\"Total machines number = %d\" % number)\ndprint(\"Manager Server number = %d\" % ms_number)\ndprint(\"NameNode Server number = %d\" % nn_number)\ndprint(\"Compute Node number = %d\" % cl_number)\n\nsprint(\"====================================\"\n \"LEAP Install Configuration\"\n \"====================================\")\nsprint(\"** LEAP version : %s\" % leap_version)\nsprint(\"** LEAP host os : %s\" % leap_os)\nsprint(\"** LEAP os_iso : %s\" % leap_os_iso)\nsprint(\"** LEAP installer : %s\" % leap_installer)\nsprint(\"** LEAP workdir : %s\" % leap_work_dir)\nsprint(\"** LEAP nodes number : %d\" % number)\nsprint(\"====================================\"\n \"==========================\"\n \"====================================\")\n\n\nresult = raw_input(\"\\033[1;32;40m\"\n \"Press Yes(Y) to start install LEAP to %d machines.\"\n \" (Yes or No):\" % number)\nif result.upper() == 'YES' or result.upper() == 'Y':\n os.system(\"clear\")\n print(\"\\033[0m\"\n \"====================================\"\n \"LEAP preparation is starting!\"\n \"====================================\")\nelse:\n exit(-107)\n\n\nprogress = Progress()\n\n\n# Step 1. Install the HOST OS ISO into the Master machine.\n# Copy os.iso file from media\n# Mount os.iso to /mnt/leap-os\nsprint_start(\" Step 1: Install host os iso into LEAP local yum server.\"\n \" \")\nif start_step <= 1:\n mkdir_cmd = \"mkdir -p %s ; echo $?\" % leap_work_dir\n lines = os.popen(mkdir_cmd).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n dprint(\"Make Leap work dir done\")\n else:\n eprint(\"Fail to make Leap work dir\")\n lexit(-101)\n\n if install_mode == \"copy\":\n pprint(\"Start to copy iso file to /mnt/leap-os-iso, please wait...\")\n\n copy_file_cmd = \"mkdir -p /mnt/leap-os-iso \" \\\n \"&& rsync -a --progress %s /mnt/leap-os-iso/ 1>&2 \" \\\n \" %s ; echo $?\" % (leap_os_iso_path, silent_log)\n\n lines = os.popen(copy_file_cmd).readlines()\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Copy iso file done\")\n else:\n eprint(\"Fail to copy isos\")\n lexit(-102)\n else:\n pprint(\"Start to link iso file to /mnt/leap-os-iso, please wait...\")\n mount_source = \"/mnt/leap-os-iso/%s\" % leap_os_iso\n link_file_cmd = \"mkdir -p /mnt/leap-os-iso \" \\\n \"&& if test -f %s; then rm %s; fi\" \\\n \"&& link %s %s 1>&2 %s; echo $?\" \\\n % (mount_source, mount_source, leap_os_iso_path, mount_source, silent_log)\n lines = os.popen(link_file_cmd).readlines()\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Link iso file done\")\n else:\n eprint(\"Fail to link isos\")\n lexit(-103)\n\n mount_cmd = \"umount /mnt/leap-os 2>/dev/null\" \\\n \"|| mkdir -p /mnt/leap-os \" \\\n \"&& mount -o loop /mnt/leap-os-iso/%s /mnt/leap-os; \" \\\n \"echo $?\" % leap_os_iso\n lines = os.popen(mount_cmd).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Mount OS ISO done\")\n else:\n eprint(\"Fail to mount iso\")\n lexit(-104)\n# link /mnt/leap-os to /var/www/html/leap-centos and\n# create /etc/fstab to auto mount iso\n link_command = \"rm /var/www/html/leap-centos 2>/dev/null; \" \\\n \"ln -s /mnt/leap-os /var/www/html/leap-centos; echo $?\"\n lines = os.popen(link_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"link centos to html directory ok\")\n else:\n eprint(\"Fail to link centos\")\n lexit(-105)\n automount_line = \"/mnt/leap-os-iso/%s /mnt/leap-os \" \\\n \"iso9660 defaults,ro,loop 0 0 \" % leap_os_iso\n automount_command = \"grep -e \\\"^/mnt/leap-os-iso\\\" /etc/fstab >/dev/null\" \\\n \"|| echo \\\"%s\\\" >> /etc/fstab ; echo $?\" % automount_line\n dprint(automount_command)\n lines = os.popen(automount_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Set leap os automount ok\")\n else:\n eprint(\"Fail to automount centos\")\n lexit(-106)\nsprint_end(\" [DONE]\")\n\n\n# Step2 : Broadcast the id_rsa.pub to all the machines to bypass password\nsprint_start(\" Step 2: Build the no-passwd connections from LEAP master \"\n \"to LEAP nodes. \")\nif start_step <= 2:\n copy_file_cmd = \"if test ! -f /usr/bin/sshpass; then \" \\\n \"cp -f ./%s/sshpass* /usr/bin/sshpass\" \\\n \"&& chmod +x /usr/bin/sshpass; fi; echo $?\" % runtime_path\n lines = os.popen(copy_file_cmd).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Install sshpass done\")\n else:\n eprint(\"Fail to install sshpass\")\n lexit(-201)\n\n keygen_cmd = \"if test ! -f ~/.ssh/id_rsa.pub; then \" \\\n \"ssh-keygen -f ~/.ssh/id_rsa -P \\'\\' 2>/dev/null; fi; echo $?\"\n lines = os.popen(keygen_cmd).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Produce rsa key done\")\n else:\n eprint(\"Fail to produce rsa key\")\n lexit(-202)\n\n if user == 'root':\n local_kfile = \"/root/.ssh/id_rsa.pub\"\n remote_authkeys = \"/root/.ssh/authorized_keys\"\n else:\n local_kfile = \"/home/%s/.ssh/id_rsa.pub\" % user\n remote_authkeys = \"/home/%s/.ssh/authorized_keys\" % user\n if os.path.exists(local_kfile):\n dprint(\"id_rsa.pub exists\")\n else:\n eprint(\"Please run ssh-keygen to produce %s at first!\" % local_kfile)\n lexit(-203)\n\n for machine in machines:\n [ip, hostname, user, password, port, machine_type] = machine\n # cat ~/.ssh/id_rsa.pub | sshpass -p 123456 ssh -p 22 -o\n # StrictHostKeyChecking=no 10.100.123.48 'cat >>~/.ssh/authorized_keys'\n remote_authkeys = \"~/.ssh/authorized_keys\"\n nohostcheck = '-o StrictHostKeyChecking=no'\n nopassword = '-o PasswordAuthentication=no'\n bypass_command = \"cat %s | \" \\\n \"sshpass -p \\'%s\\' ssh -p %s %s %s \" \\\n \"\\\"mkdir -p ~/.ssh/ ; cat >> %s \\\" 2>/dev/null; echo $?\" \\\n % (local_kfile, password, port, nohostcheck, ip, remote_authkeys)\n dprint(bypass_command)\n result = os.popen(bypass_command).readlines()[-1].replace(\"\\n\", \"\")\n if result == '0':\n dprint(\"Success bypass password!\")\n else:\n eprint(\"Fail bypass password!\")\n lexit(-204)\n\n # check command = ssh -p 22 10.100.123.48 'hostname; uname -mrn;\n check_command = \"ssh -p %s %s %s 'hostname;' 2>/dev/null; \" \\\n \"echo $?\" % (port, nopassword, ip)\n dprint(check_command)\n result = os.popen(check_command).readlines()[-1].replace(\"\\n\", \"\")\n dprint(result)\n if result == '0':\n pprint(\"Success to bypass %s's %s password!\" % (ip, user))\n else:\n eprint(\"Fail to bypass %s password!\" % ip)\n lexit(-205)\n\n # ssh -p 22 10.100.123.48 'hostname'\"\n gethostname_command = \"ssh -p %s %s 'hostname' 2>/dev/null;\" \\\n \" echo $? \" % (port, ip)\n lines = os.popen(gethostname_command).readlines()\n result = lines[-1].replace(\"\\n\", \"\")\n dprint(result)\n if result == '0':\n remote_hostname = lines[-2].replace(\"\\n\", \"\")\n dprint(\"Get %s's hostname: %s\" % (ip, remote_hostname))\n else:\n eprint(\"Fail to get %s's hostname\" % (ip))\n lexit(-206)\n\n if hostname == '': # do not need to change hostname\n hostname = remote_hostname\n else: # need to change hostname\n dprint(\"Change %s's hostname to %s\" % (ip, hostname))\n network_file = \"/etc/sysconfig/network\"\n # ssh -p 22 10.100.123.48 'hostname namenode-1.leap.com &&\n # sed -i 's/^HOSTNAME=/#&/g' /etc/sysconfig/network\n # && echo \"HOSTNAME=linst\" >> /etc/sysconfig/network\n sethostname_command = \"ssh -p %s %s \\\"hostname %s && \" \\\n \"sed -i 's/^HOSTNAME=/#&/g' %s && \" \\\n \"echo \\\"HOSTNAME=%s\\\" >> %s \\\" 2>/dev/null;echo $?\" \\\n % (port, ip, hostname, network_file, hostname, network_file)\n dprint(sethostname_command)\n lines = os.popen(sethostname_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Set %s's hostname to %s\" % (ip, hostname))\n else:\n eprint(\"Fail to set %s's hostname to %s\" % (ip, hostname))\n lexit(-207)\nsprint_end(\" [DONE]\")\n\n\n# Step 3 : Produce /etc/hosts files and broadcast to all machines\n# Host files examples:\n# 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\n# 10.100.99.101 node1.leap.cctv.com\n# 10.100.99.102 node2.leap.cctv.com\n# 10.100.99.103 node3.leap.cctv.com\n# 10.100.99.104 node4.leap.cctv.com\n# #Internal leap repo source\n# 10.100.99.101 repo.leap.com\n# 10.100.99.101 ntpd.leap.com\nsprint_start(\" Step 3: Synchronize the /etc/hosts to all LEAP nodes.\"\n \" \")\nif start_step <= 3:\n dprint(machines)\n local_hosts_file = \"./%s/hosts.tmp\" % setup_path\n hosts_file = open(local_hosts_file, \"w+\")\n hosts_file.writelines(\n \"127.0.0.1 localhost localhost.localdomain \\\n localhost4 localhost4.localdomain4\\n\")\n for machine in machines:\n [ip, hostname] = [machine[0], machine[1]]\n host_line = \"%s %s\\n\" % (ip, hostname)\n hosts_file.writelines(host_line)\n hosts_file.writelines(\"#Internal leap repo source\\n\")\n hosts_file.writelines(\"%s repo.leap.com\\n\" % manager_ip)\n hosts_file.writelines(\"%s ntpd.leap.com\\n\" % manager_ip)\n hosts_file.close()\n if silent == 0:\n hosts_list = file(local_hosts_file).readlines()\n dprint(hosts_list)\n pprint(\"/etc/hosts files:\")\n vprint(\"\"),\n for host in hosts_list:\n print(host),\n pprint(\"\")\n pprint(\"Make sure the /etc/hosts file are right!\")\n result = raw_input(\n \"Press Yes to update the files to all the machines (Yes or No):\")\n if result.upper() == 'YES' or result.upper() == 'Y':\n pprint(\"Start to update machines's /etc/hosts\")\n else:\n eprint(\"User don't allow to update /etc/hosts\")\n lexit(-301)\n\n for machine in machines:\n [ip, hostname, port] = [machine[0], machine[1], machine[4]]\n # cat ./hosts.tmp | ssh -p 22222 10.100.123.48 'cat > /etc/hosts'\n syn_hosts_command = \"cat %s | \" \\\n \"ssh -p %s %s 'cat > /etc/hosts' 2>/dev/null;\" \\\n \"echo $?\" % (local_hosts_file, port, ip)\n dprint(syn_hosts_command)\n lines = os.popen(syn_hosts_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Set %s's /etc/hosts : Done\" % machine[0])\n else:\n eprint(\"Fail to Sync %s's /etc/hosts\" % machine[0])\n lexit(-302)\n# produce [IP, Hostname] for Leap Manager Server (leap_hosts.ini)\n# exmaple:\n# 10.100.99.101 node1.leap.cctv.com root password port\n# 10.100.99.102 node2.leap.cctv.com root password port\n# 10.100.99.103 node3.leap.cctv.com root password port\n# 10.100.99.104 node4.leap.cctv.com root password port\n reverse_host_file = \"%s/leap_hosts.ini\" % leap_work_dir\n hosts_file = open(reverse_host_file, \"w+\")\n for machine in machines:\n [ip, hostname, user, password, port, machine_type] = machine\n host_line = \"%s %s %s %s %s \\n\" % (ip, hostname, user, password, port)\n hosts_file.writelines(host_line)\n hosts_file.close()\nsprint_end(\" [DONE]\")\n\n\n# Step 4 produce ntp.conf\n# Manager server works as ntpd server in the leap machines group,\n# The other servers work as ntpd client in the leap machines group\n# Configures:\n# restrict default kod nomodify notrap nopeer noquery\n# restrict -6 default kod nomodify notrap nopeer noquery\n# restrict 127.0.0.1\n# restrict -6 ::1\n# restrict 0.0.0.0 mask 255.255.255.0 nomodify\n# restrict ${NTPSERVER}\n# server ${NTPSERVER} prefer\n# server 1.cn.pool.ntp.org\n# server 127.127.1.0\n# fudge 127.127.1.0 stratum 8\n# driftfile /var/lib/ntp/drift\n# for ntpd server: NTPSERVER = {0.rhel.pool.ntp.org|1.cn.pool.ntp.org}\n# for ntpd client: NTPSERVER = ntpd.leap.com\n# sed -i 's/restrict ntpd.leap.com/\n# restrict 0.0.0.0 mask 255.255.255.0 nomodify/g'\n# ntp.conf\n# sed -i 's/server ntpd.leap.com prefer/\n# server 0.rhel.pool.ntp.org prefer\\nserver 1.cn.pool.ntp.org/g'\n# ntp.conf\nsprint_start(\" Step 4: Setup NTPD service in all LEAP nodes.\"\n \" \")\nif start_step <= 4:\n ntpd_sed_rule1 = \"s/restrict ntpd.leap.com/\" \\\n \"restrict 0.0.0.0 mask 255.255.255.0 nomodify/g\"\n ntpd_sed_rule2 = \"s/server ntpd.leap.com prefer/\" \\\n \"server 0.rhel.pool.ntp.org prefer\\\\nserver 1.cn.pool.ntp.org\\\\n\" \\\n \"server 127.127.1.0\\\\nfudge 127.127.1.0 stratum 8/g\"\n ntpd_command = \"sed -i '%s' /etc/ntp.conf \" \\\n \"&& sed -i '%s' /etc/ntp.conf; \" \\\n \"echo $?\" % (ntpd_sed_rule1, ntpd_sed_rule2)\n lines = os.popen(ntpd_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Update manager ntpd.conf Done\")\n else:\n eprint(\"Fail to update ntpd.conf\")\n lexit(-401)\n\n ntpd_server_command = \"service ntpd restart 2>&1 1>/dev/null \" \\\n \"&& sleep 8; echo $?\"\n lines = os.popen(ntpd_server_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Restart manager ntpd server done\")\n else:\n eprint(\"Fail to restart manager ntpd server\")\n lexit(-402)\n\n for machine in machines:\n [ip, hostname, port] = [machine[0], machine[1], machine[4]]\n if ip != manager_ip:\n ntpd_command = \"ssh -p %s %s 'service ntpd restart' \" \\\n \" 2>/dev/null; echo $?\" % (port, ip)\n lines = os.popen(ntpd_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Restart %s ntpd Done\" % hostname)\n else:\n eprint(\"Fail to restart %s's ntpd\" % hostname)\n lexit(-403)\n if ip != manager_ip:\n ntp_server = manager_ip\n else:\n ntp_server = \"0.rhel.pool.ntp.org\"\n ntpd_update_command = \"ssh -p %s %s 'ntpdate -u %s 2>/dev/null' \" \\\n \"; echo $?\" % (port, ip, ntp_server)\n dprint(ntpd_update_command)\n lines = os.popen(ntpd_update_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Update %s to ntpd server first time Done\" % hostname)\n else:\n dprint(\"Warning: Fail to update time %s at first\" % hostname)\nsprint_end(\" [DONE]\")\n\n\n# Step 5 preinstall rpm list\n# rpm -ivh *.rpm\nsprint_start(\" Step 5: Pre-install rpm packages.\"\n \" \")\nif start_step <= 5:\n local_rpm_dir = centos_mount_point + \"/Packages/\"\n dprint(\"Os Package dir = %s\" % local_rpm_dir)\n rpm_number = 0\n rpm_list = \"\"\n for rpm in manager_rpms:\n rpm_list += \" %s/%s \" % (local_rpm_dir, rpm.replace(\"\\n\", \" \"))\n rpm_number += 1\n dprint(rpm_list)\n rpm_install_command = \"rpm -ivh %s 2>&1 >/dev/null;echo $?\" % rpm_list\n dprint(rpm_install_command)\n lines = os.popen(rpm_install_command).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if int(result) == rpm_number:\n pprint(\"%s rpm packages install ok\" % result)\n else:\n eprint(\"Fail to install rpms in preinstall_file\")\n lexit(-501)\nsprint_end(\" [DONE]\")\n\n\n# Step 6 comment the line \"Defaults requiretty\" from /etc/sudoers\nsprint_start(\" Step 6: Setting LEAP runtime environment.\"\n \" \")\nif start_step <= 6:\n sed_cmd = \"chmod +w /etc/sudoers && \" \\\n \"sed -i 's/^Defaults requiretty/# Defaults requiretty/g' \" \\\n \"/etc/sudoers && chmod -w /etc/sudoers\"\n for machine in machines:\n [ip, hostname, port] = [machine[0], machine[1], machine[4]]\n remote_cmd = \" ssh -p %s %s \\\"%s\\\" ;echo $?\" \\\n % (port, ip, sed_cmd)\n dprint(remote_cmd)\n lines = os.popen(remote_cmd).readlines()\n dprint(lines)\n result = lines[-1].replace(\"\\n\", \"\")\n if result == '0':\n pprint(\"Enable %s remote sudo done\" % hostname)\n else:\n eprint(\"Fail to enable %s remote sudo\" % hostname)\n lexit(-601)\nsprint_end(\" [DONE]\")\n\npprint(\"#####Leap Preparation is done. Start running installer #######\")\n\nprint(\"\\033[0m\\n\\n\\n\")\n\n# Final step, call installer\ninstaller_command = \"chmod +x %s; %s 1>&2\" % (leap_installer, leap_installer)\nos.popen(installer_command)\n","sub_path":"setup_env.py","file_name":"setup_env.py","file_ext":"py","file_size_in_byte":23816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"234407741","text":"import numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.seq2seq as Seq\nfrom tensorflow.python.layers.core import Dense\nfrom warnings import simplefilter\nsimplefilter(action = 'ignore',category = FutureWarning)\n\ndef extract_character_vocab(data):\n #构造映射表\n #将原文本的每行字符提取出来,构造每个字母对应一个数字编号,同时加入sepeicial_words,作为特殊标识。特殊标识也有相应的编号。\n special_words = ['','','','']\n set_words = list(set(character for line in data.split('\\n') for character in line)) #创建无序不重复集合\n int_to_vocab = {idx:word for idx, word in enumerate(special_words + set_words)}\n vocab_to_int = {word:idx for idx, word in int_to_vocab.items()} \n return int_to_vocab,vocab_to_int\n\n#找出每个批次中的最长序列长度值,将每个较短的序列的尾部增加pad标识编码,补齐到和最长序列长度一致。\ndef pad_sentence_batch(sentence_batch,pad_int):\n max_sentence = max([len(sentence) for sentence in sentence_batch])\n return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]\n\ndef get_batches(targets,sources,batch_size,source_pad_int,target_pad_int):\n #定义生成器,用来获取batch\n #用(len(sources) -1)//batch_size +1,能确保所有的数据集都能被切分到训练集中。\n #假设len(sources)为100,batch_size为20,结果是5。假设len(sources)为101,batch_size是20,结果则是6.\n for batch_i in range(0,len(sources)//batch_size):\n start_i = batch_i * batch_size\n sources_batch = sources[start_i : start_i + batch_size]\n targets_batch = targets[start_i : start_i + batch_size]\n \n pad_sources_batch = np.array(pad_sentence_batch(sources_batch,source_pad_int))\n pad_targets_batch = np.array(pad_sentence_batch(targets_batch,target_pad_int))\n \n targets_lengths = []\n for target in targets_batch:\n targets_lengths.append(len(target))\n \n sources_lengths = []\n for source in sources_batch:\n sources_lengths.append(len(source))\n \n yield pad_targets_batch,pad_sources_batch,targets_lengths,sources_lengths\n\ndef get_inputs():\n #定义6个张量\n inputs= tf.placeholder(tf.int32,[None,None],name = 'inputs')\n targets = tf.placeholder(tf.int32,[None,None],name = 'targets') #实际输出值,并非预测值\n learning_rate = tf.placeholder(tf.float32,name= 'learning_rate') #学习率占位,是为了调参么??\n keep_prob = tf.placeholder(tf.float32,name = 'keep_prob')\n \n #定义输出的序列的最大长度,及每组输入、输出序列的长度\n #需注意的是这个序列长度的数据,是一维的,用的是小括号表示维度。而上面的输入和输出,则是高维的,用中括号表示维度。\n target_seq_len = tf.placeholder(tf.int32,(None,),name = 'target_seq_len')\n max_target_seq_len = tf.reduce_max(target_seq_len,name = 'max_target_seq_len') #求某个维度上的最大值\n source_seq_len = tf.placeholder(tf.int32,(None,),name= 'source_seq_len') \n return inputs,targets,learning_rate,target_seq_len,max_target_seq_len,source_seq_len,keep_prob\n\ndef get_encoder_layer(input_data,rnn_size,num_layers,source_seq_len,source_vocab_size,\n encoding_embedding_size,keep_prob):\n#构造编码层Encoder。\n# input_data:输入的张量,对于实际来说,是每个batch输入的序列。\n# rnn_size: rnn隐层结点数量,外部定义,对该例,其值为50,也就是每层隐藏层的神经元个数。\n# num_layers:隐藏层的层数,对本例,值为2.需注意的是,这样的设置要求每层神经元的个数保持一致。\n# source_seq_len: 输入序列的长度。对每个输入序列,其序列的长度是不固定的。此变量为一个数值。\n# source_vocab_size : 输入序列的词典大小,也就是输入序列中涉及到的编码数量(包含特殊字符对应的编码)\n# encoding_embedding_size : embedding的大小,就是嵌入矩阵的大小,人为指定。\n\n# tf的embed_sequence方法用于构造嵌入矩阵,每个参数的含义:经过处理的���入序列,输入序列的词汇表大小,嵌入矩阵的维度\n# 输入序列的词汇表大小是指总共有多少类词汇,也就是涉及到几种字母(包含特殊字符)。source_vocab_size = len(source_letter_to_int)\n# 这里用tf的word2vec方法,将原始的数据转成了嵌入矩阵。\n# 比如指定嵌入矩阵的维度是15,对编码23,将会转成一行15列的数字(word2vec用softmax激活,使15个数值均位于(0,1))\n encoder_embed_input = tf.contrib.layers.embed_sequence(input_data,source_vocab_size,\n encoding_embedding_size)\n \n def get_lstm_cell(rnn_size,keep_prob):\n # tf.contrib.rnn.LSTMCell中,rnn_size代表每层隐藏层的神经元个数,\n # initializer是初始化权重参数,类似kernel_initializer。注意这里没有初始化偏置。\n # tf.truncated_normal_initializer用于生成指定均值和标准差的正态分布数值(且为两端截断的正态分布,数值相对比较集中)\n # 这个与ttf.random_normal_initializer的区别在于有无两端截断。按照mnist集的做法,truncated_normal效果更好\n lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size,\n initializer=tf.truncated_normal_initializer(stddev=0.1,seed=2))\n #增加DropOut层\n lstm_cell = tf.nn.rnn_cell.DropoutWrapper(lstm_cell,input_keep_prob=keep_prob)\n return lstm_cell\n # 获取指定层数(num_layers)的多层神经元网络结构,也就是整合多层神经网络。\n cell = tf.contrib.rnn.MultiRNNCell([get_lstm_cell(rnn_size,keep_prob) for _ in range(num_layers)])\n # tf.nn.dynamic_rnn的输出包括最终的输出,及最终的状态输出。\n # output输出的是【batch-size,max_time,cell.out_size】的输出形状。\n # state表示最后一层的状态输出。这里需要作为解码层的输入的一部分\n # tf.nn.dynamic_rnn:cell,inputs,sequence_length,initial_state,dtype,parallel_iterations,swap_memory,time_major,scope\n # cell就是神经元的一个实例,要定义好层数,每层的神经元个数\n # inputs要注意和time_major匹配。因inputs的shape需要是【batch_size,max_time,input_size】,此时time_major =False。\n # 否则 time_major = True时,max_time和batch_size要对调,且输出也会对调。\n #sequence_length代表输入序列的长度,每个序列的长度不固定。\n encoder_output,encoder_state = tf.nn.dynamic_rnn(cell,encoder_embed_input,\n sequence_length=source_seq_len,dtype =tf.float32)\n return encoder_output,encoder_state\n\ndef process_decoder_input(data,vocab_to_int,batch_size):\n # 补充,并移除最后一个字符\n # ending的结果是将数据集切除最后一个字符。\n # tf.strided_slice方法的参数:输入数据,开始切片处,终止切片处,步长。\n # 这里由于数据是二维的,因此要说明清楚对行和列如何进行切割。\n # 按照当前的做法是,起始是0行0列开始,结束于batch_size行,倒数第二列。也因此切除了最后一列值。\n # 这里也只是对目标序列进行处理。因为目标序列尾部增加了一列结束标记编码,切除后并未损失数据。\n ending = tf.strided_slice(data,[0,0],[batch_size,-1],[1,1])\n # tf.fill 创建一个维度为dims,值为value的tensor对象(tf.fill(dims,values,name =None)).fill创建的值是唯一值。\n # tf.concat 用于拼接张量。在这里也就是在ending前面统一增加一个字符对应的编码。作为解码层的输入。\n decoder_input =tf.concat([tf.fill([batch_size,1],vocab_to_int['']),ending],axis=1) #按照第一维进行合并\n return decoder_input\n\ndef decoding_layer(target_letter_to_int,decoding_embedding_size,num_layers,rnn_size,batch_size,\n target_seq_len,max_target_seq_len,encoder_output,encoder_state,decoder_input,keep_prob):\n #构造Decoder层\n #target_letter_to_int: target数据的映射表。该映射表生成后,不再改动,以便后期查找核对。\n #decoding_embedding_size:embed向量大小\n #num_layers: 堆叠的RNN单元数量\n #rnn_size: RNN单元的隐层节点数量\n #target_seq_len: target数据序列长度\n #max_target_seq_len : target序列的最大长度\n #encoder_state: encoder端编码的状态向量\n #decoder_input: decoder端输入\n target_vocab_size = len(target_letter_to_int) #目标词向量长度,也就是目标序列中涉及到的字母种类数量。\n # 本例中,由于是将序列进行重新排序,因此目标序列的字母种类与输入的是一致的。\n # 对于常规情况,则很可能不一样。因为是拿原始序列进行输出预测,输出是什么序列,并不一定。\n # tf.random_uniform用于生成指定范围的随机数\n decoder_embeddings = tf.Variable(tf.random_uniform([target_vocab_size,decoding_embedding_size]))\n #选取一个张量里面索引对应的元素.这里是提取decoder_embeddings里的数据,数据的索引号是decoder_input\n decoder_embed_input = tf.nn.embedding_lookup(decoder_embeddings,decoder_input) \n \n def get_decoder_cell(rnn_size,keep_prob):\n #同样的,创建一个解码层的LSTM模块,每层神经元个数是rnn_size个\n decoder_cell = tf.contrib.rnn.LSTMCell(rnn_size,\n initializer =tf.truncated_normal_initializer(stddev=0.1,seed=2))\n #增加dropout层\n decoder_cell = tf.nn.rnn_cell.DropoutWrapper(decoder_cell,input_keep_prob=keep_prob)\n return decoder_cell\n # 将解码层的神经网络模型,扩充成相同结构的几个隐藏层,层数为num_layers\n cell = tf.contrib.rnn.MultiRNNCell([get_decoder_cell(rnn_size,keep_prob) for _ in range(num_layers)])\n #输出是解码层的输出,其最后一层是全连接层。\n #target_vocab_size是目标序列涉及到的单词种类个数,在本例中是字母种类个数。\n #Dense全连接层中的参数kernel_initializer代表权重矩阵的初始化函数(不含偏置)。偏置初始化:bias_initializer\n # tf.truncated_normal_initializer用于生成指定均值和标准差的正态分布数值(且为两端截断的正态分布,数值相对比较集中)\n # 这个与ttf.random_normal_initializer的区别在于有无两端截断。按照mnist集的做法,truncated_normal效果更好\n \n output_layer = Dense(target_vocab_size,\n kernel_initializer = tf.truncated_normal_initializer(stddev=0.1))\n #增加Attention机制\n attn_mesh = Seq.BahdanauAttention(rnn_size,encoder_output,source_seq_len,normalize=False,\n name = 'BahdanauAttention')\n \n cell = Seq.AttentionWrapper(cell,attention_mechanism=attn_mesh,attention_layer_size=rnn_size)\n \n initial_state = cell.zero_state(batch_size=batch_size, dtype=tf.float32).clone(cell_state=encoder_state)\n\n #tf.variable_scope是用来获取tf的变量名,以实现变量共享。\n #由于CNN和RNN等类型的神经网络,其不少变量是共享的,比如RNN中的权值W,需要共享。因此就需要设置这个variable_scope\n #如果将这些共享变量设置为全局变量,但这样会打破封装性。tf提供的这种Variable_scope机制就可以避免这个问题。\n with tf.variable_scope('decode'):\n #解码部分,才会用到seq2seq模块。\n #TrainingHelper中inputs的形状是【batch_size,sequence_len,embedding_size】。这里的time_major需设置为False\n #如果time_major设置为True,inputs的形状需要将batch_size和sequence_len对调。\n #sequence_len是指batch中每个输入序列的长度。\n #TrainingHelper,用于训练阶段,预测阶段用的是GreedyEmbeddingHelper.\n #这里同样存在time_major的问题,注意输入数据的形状\n training_helper = Seq.TrainingHelper(inputs=decoder_embed_input,\n sequence_length=target_seq_len,\n time_major = False)\n # BasicDecoder是定义一个封装了decoder功能的实例,根据Helper实例的不同,decoder可以实现不同的功能\n # initial_state是增加了attention机制的初始状态。\n training_decoder = Seq.BasicDecoder(cell,training_helper,\n initial_state,output_layer)\n #将定义好的decoder实例传入,返回解码层处理后的输出.\n #dynamic_decode称动态解码,返回三个值。因此如只接收一个变量时,需要设置2个下划线。\n training_decoder_output,_ ,_ = Seq.dynamic_decode(training_decoder,impute_finished=True,\n maximum_iterations = max_target_seq_len)\n #这里用到的reuse,因为前面刚刚应用到这个scope这个变量名称。 \n with tf.variable_scope('decode',reuse=True): \n #tf.tile :input,shape.用于复制自身数据,将原始的input,按照指定的shape,进行扩展复制。\n start_tokens = tf.tile(tf.constant([target_letter_to_int['']],dtype=tf.int32),[batch_size],\n name='start_tokens')\n # 用于inference阶段的helper,将output输出后的logits使用argmax获得id,再经过emdedding layer来获取下一时刻的输入\n # 其参数是:embedding,start_tokens,end_token\n # embedding是指定义的嵌入变量数据,start_tokens是指每个序列起始输入的token_id,也就是起始标识对应的编码。\n # end_token是序列终止的token_id\n\n predicting_helper =Seq.GreedyEmbeddingHelper(decoder_embeddings,start_tokens,\n target_letter_to_int[''])\n \n predicting_decoder = Seq.BasicDecoder(cell,predicting_helper,\n initial_state,output_layer)\n \n predicting_decoder_output,_ ,_ = Seq.dynamic_decode(predicting_decoder,impute_finished=True,\n maximum_iterations=max_target_seq_len)\n\n return training_decoder_output,predicting_decoder_output\n\n#搭建seq2seq框架,将原先创建好的函数输入,得出训练的输出和预测输出\ndef seq2seq_model(input_data,targets,lr,\n target_seq_len,max_target_seq_len,source_seq_len,\n source_vocab_size,target_vocab_size,\n encoding_embedding_size,decoding_embedding_size,\n rnn_size,batch_size,num_layers,keep_prob):\n #获取编码状态,准备传入解码层\n encoder_output,encoder_state = get_encoder_layer(input_data,rnn_size,num_layers,\n source_seq_len,source_vocab_size,\n encoding_embedding_size,keep_prob)\n #获取解码输入,准备传入解码层\n decoder_input = process_decoder_input(targets,target_letter_to_int,batch_size)\n \n training_decoder_output,predicting_decoder_output = decoding_layer(target_letter_to_int,\n decoding_embedding_size,\n num_layers,rnn_size,batch_size,\n target_seq_len,max_target_seq_len,\n encoder_output,encoder_state,\n decoder_input,keep_prob)\n return training_decoder_output,predicting_decoder_output\n\nepochs = 1000\nrnn_size = 64\nnum_layers = 3 \n#编码层嵌入矩阵的大小,也就是将每个字母对应的编码,转成一列几行的数据,就是所谓的word2vec\nencoding_embedding_size = 30\ndecoding_embedding_size = 30\nlearning_rate = 0.001\nbatch_size = 32\nwith open('./source.txt') as f:\n source_data = f.read()\nwith open('./target.txt') as f:\n target_data = f.read()\n \n#需注意的是,输入序列的文字及索引号,与输出序列的文字及索引号,两者并无直接关系。\n#也就是说,输入序列中的任意一个字,其对应的索引号。在输出序列中,相同的字对应的索引号,并不相同。\n#但是进行文本和编码对应时,需将输入序列和输出序列的映射表合并起来\nsource_int_to_letter,source_letter_to_int = extract_character_vocab(source_data + target_data)\ntarget_int_to_letter,target_letter_to_int = extract_character_vocab(source_data + target_data)\n\n#source_int的目的是,获取字典source_letter_to_int中的每行单词的每个字母对应的下标。\n# 如字母不在字典中,则用对应的下标替代\n# 对于target_int的目的也是类似,只是在target集中,还额外增加了尾部识别标记的下标值。\n# 其实就是对数据集的每行单词的每个字母,全部映射成随机的数字。然后将这些数字替换为字母显示。对结果集增加一个尾部结束提示。\nsource_int = [[source_letter_to_int.get(letter,source_letter_to_int['']) for letter in line] \n for line in source_data.split('\\n')]\ntarget_int = [[target_letter_to_int.get(letter,target_letter_to_int['']) for letter in line]\n + [target_letter_to_int['']] for line in target_data.split('\\n')]\n\n#切分训练集和验证集\ntrain_source = source_int[batch_size:]\ntrain_target = target_int[batch_size:]\nvalid_source = source_int[:batch_size]\nvalid_target = target_int[:batch_size]\n\n(valid_targts_batch,valid_sources_batch,valid_targets_lengths,\n valid_sources_lengths) = next(get_batches(valid_target,valid_source,batch_size,\n source_letter_to_int[''],\n target_letter_to_int['']))\n\ntrain_graph = tf.Graph()\nwith train_graph.as_default():\n input_data,targets,lr,target_seq_len,max_target_seq_len,source_seq_len,keep_prob = get_inputs()\n \n training_decoder_output,predicting_decoder_output = seq2seq_model(input_data,targets,lr,target_seq_len,\n max_target_seq_len,source_seq_len,\n len(source_letter_to_int),\n len(target_letter_to_int),\n encoding_embedding_size,\n decoding_embedding_size,\n rnn_size,batch_size,num_layers,keep_prob)\n #tf.identity用于返回一个输入完全相同形状和内容的张量,类似 y= x的操作.\n # 这么做的目的是将操作转成一个op,而不是单纯的赋值。单纯的赋值,无法在tf框架下执行。\n #training_decoder_oupt --> seq2seq_model函数 --> decoding_layer函数 --> Seq.dynamic_decode的输出\n # dynamic_decode动态解码器,返回的内容是(final_outputs,final_state,final_seq_len).\n #其中final_outputs是一个命名的元组,里面包含两项:rnn_outputs和sample_id。\n # rnn_output:【batch_size,decoder_targets_length,vocab_size】保存decode每个时刻每个单词的概率,可以用来计算loss\n # sample_id:【batch_size】,tf.int32, 保存最终的编码结果,可以表示最后的答案。\n training_logits = tf.identity(training_decoder_output.rnn_output,'logits')\n \n predicting_logits = tf.identity(predicting_decoder_output.sample_id,name = 'predictions')\n #张量变换函数,返回一个表示每个单元前N个位置的mask张量。这个N即指定的max_target_seq_len\n #可以这么理解,就是用来判定所有序列中,每个序列不满足指定序列长度(一般是最长序列的长度)的部分\n # 这里返回的是float32型的结果,即1.0和0.0。默认是布尔型结果。\n #基本上就是在进行encode-decode网络中,用于标记无用的填充。\n masks = tf.sequence_mask(target_seq_len,max_target_seq_len,dtype=tf.float32,name = 'masks')\n #个人感觉,这里增加这个name_scope的定义,完全就是为了画图时方便归集到一起。\n with tf.name_scope('optimization'):\n #用于计算seq2seq中的loss,使用sequence_loss函数\n #需要注意的是,当我们输入的是不定长数据时,这个函数中的参数weight经常使用masks张量。\n cost = Seq.sequence_loss(training_logits,targets,masks)\n# cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=targets,logits=training_logits)) \n optimizer = tf.train.AdamOptimizer(lr)\n # 梯度修剪,防止梯度消失和爆炸问题。compute_gradients属于minimize的第一步。\n # compute_gradients返回(gradient,variable)对的列表。\n gradients = optimizer.compute_gradients(cost)\n #tf.clip_by_value使得一个张量中的数值限制在一个范围值之内。也就是类似盖帽法,将超出阈值的数值直接替换为阈值。\n #这个capped_gradients包括的是梯度和更新变量的元组对\n #还个tf.clip_by_norm用于修剪超过L2范数值的梯度,L2范数值是求向量平方和的开方值,有些类似标准差。\n #如果向量的L2范数超过设定的规约数,则将整个向量值替换成:向量 * 规约数 / 向量的L2范数。\n # 如果是tf.clip_by_global_norm则是计算全局的L2范数。。上述的只是计算单次梯度的L2范数。\n # 如果是tf.clip_by_average_norm则是计算向量的L2范数后,再求均值,与设定的规约数比较。\n capped_gradients = [(tf.clip_by_value(grad,-5.,5.),var) for grad,var in gradients if grad is not None]\n #apply_gradients属于minimize的第二步。执行对应变量的更新梯度操作\n train_op = optimizer.apply_gradients(capped_gradients)\n\ncheckpoint = \"./data/trained_model.ckpt\"\nwith tf.Session(graph=train_graph) as sess:\n sess.run(tf.global_variables_initializer()) \n for epoch_i in range(1,epochs + 1):\n # batch_i是指第几个batch\n for batch_i,(targets_batch,sources_batch,\n targets_lengths,sources_lengths) in enumerate(get_batches(train_target,\n train_source,batch_size,\n source_letter_to_int[''],\n target_letter_to_int[''])):\n \n #要注意的是,sess.run时,要传入feed_dict的数据\n # 此时需要与前面定义get_inputs函数所获取的占位变量名对照,确保输入完整的数据集\n _,loss = sess.run([train_op,cost],{input_data: sources_batch,\n targets:targets_batch,\n lr:learning_rate,\n target_seq_len:targets_lengths,\n source_seq_len:sources_lengths,\n keep_prob:0.5})\n if epoch_i % 50 == 0:\n validation_loss = sess.run([cost],{input_data:valid_sources_batch,\n targets:valid_targts_batch,\n lr:learning_rate,\n target_seq_len:valid_targets_lengths,\n source_seq_len:valid_sources_lengths,\n keep_prob:1.0})\n print('Epoch {:>3}/{} Batch {:>4} /{} - Training loss: {:>6.3f} -Validation loss :{:>6.3f}'.format\n (epoch_i,epochs,batch_i,len(train_source) // batch_size,\n loss,validation_loss[0]))\n saver = tf.train.Saver()\n saver.save(sess,checkpoint)\n print('Model Trained and Saved')","sub_path":"seq2seq_text_model/seq2seq_test.py","file_name":"seq2seq_test.py","file_ext":"py","file_size_in_byte":24805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"251428250","text":"\"\"\"\nmulti-layer neural network for classification using Theano.\n\"\"\"\n\nimport os\nimport sys\nimport time\n\nimport numpy\n\nimport theano\nimport theano.tensor as T\n\n#from Optimizers import AdaGrad, AdaDelta, SGDMomentum, GD\nfrom Adams import Adam\n\nclass HiddenLayer(object):\n def __init__(self, rng, input, n_in, n_out, W=None, b=None, activation=T.tanh):\n \"\"\"\n rng: a random number generator used to initialize weights\n\n input: a symbolic tensor of shape (batchSize, n_in)\n n_in: dimensionality of input\n n_out: number of hidden units\n\n activation: Non linearity to be applied in the hidden layer\n \"\"\"\n self.input = input\n self.n_in = n_in\n self.n_out = n_out\n\n if W is None:\n W_values = numpy.asarray( rng.uniform( low = -numpy.sqrt(6./(n_in + n_out)), high = numpy.sqrt(6./(n_in + n_out)), size=(n_in, n_out)), dtype=theano.config.floatX )\n if activation == T.nnet.sigmoid:\n W_values *= 4\n\n W = theano.shared(value=W_values, name='HL_W', borrow=True)\n\n if b is None:\n b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)\n b = theano.shared(value=b_values, name='HL_b', borrow=True)\n\n self.W = W\n self.b = b\n\n lin_output = T.dot(input, self.W) + self.b\n self.output = ( lin_output if activation is None else activation(lin_output) )\n\n # parameters of the model\n self.params = [self.W, self.b]\n self.paramL1 = abs(self.W).sum() + abs(self.b).sum()\n self.paramL2 = (self.W**2).sum() + (self.b**2).sum()\n\n## a simple logistic regression for classification\nclass LogRegLayer(object):\n\n def __init__(self, rng, input, n_in, n_out):\n \"\"\" \n input: symbolic variable that describes the input of the architecture (one minibatch). It has shape (batchSize, n_in)\n n_in: number of input units, the dimension of the space in which the datapoints lie\n n_out: number of output units, the dimension of the space in which the labels lie\n\n \"\"\"\n self.n_in = n_in\n self.n_out = n_out\n\n # initialize with 0 the weights W as a matrix of shape (n_in, n_out)\n value_bound = numpy.sqrt(6. /(n_in + n_out))\n W_values = numpy.asarray(rng.uniform( low = - value_bound, high = value_bound, size=(n_in, n_out) ), dtype=theano.config.floatX)\n self.W = theano.shared (value = W_values, name ='LogReg_W', borrow=True)\n\n # initialize the baises b as a vector of n_out 0s\n self.b = theano.shared( value=numpy.zeros( (n_out,), dtype=theano.config.floatX ), name='LogReg_b', borrow=True)\n\n self.pre_act = T.dot(input, self.W) + self.b\n self.p_y_given_x = T.nnet.softmax(self.pre_act)\n self.y_pred = T.argmax(self.p_y_given_x, axis=1)\n self.output = self.p_y_given_x\n\n # parameters of the model\n self.params = [self.W, self.b]\n self.paramL1 = abs(self.W).sum() + abs(self.b).sum()\n self.paramL2 = (self.W**2).sum() + (self.b**2).sum()\n\n ## this function returns a scalar\n def NLL(self, y, sampleWeight=None):\n ###Return the mean of the negative log-likelihood of the prediction of this model under a given target distribution.\n\n if sampleWeight is not None:\n return -T.sum(T.mul(sampleWeight, T.log(self.p_y_given_x)[T.arange(y.shape[0]), y] ) )/T.sum(sampleWeight)\n else:\n return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y])\n\n def errors(self, y, sampleWeight=None):\n ###Return the 0-1 error rate in a minibatch y: a vector of true labels\n\n # check if y has same dimension of y_pred\n if y.ndim != self.y_pred.ndim:\n raise TypeError(\n 'y should have the same shape as self.y_pred',\n ('y', y.type, 'y_pred', self.y_pred.type)\n )\n # check if y is of the correct datatype\n if y.dtype.startswith('int'):\n # the T.neq operator returns a vector of 0s and 1s, where 1 represents a mistake in prediction\n if sampleWeight is not None:\n return T.sum( T.mul(sampleWeight, T.neq(self.y_pred, y) ) ) * 1./T.sum(sampleWeight)\n else:\n return T.mean(T.neq(self.y_pred, y))\n else:\n raise NotImplementedError()\n\n\n### A neural network Logistic Regression for Classification\nclass NN4LogReg(object):\n\n def __init__(self, rng, input, n_in, n_out, n_hiddens=[], activation=T.nnet.relu):\n \"\"\"Initialize the parameters for the multilayer perceptron\n\n rng: a random number generator used to initialize weights\n\n input has shape (batchSize, n_in)\n n_in is the number of input features\n n_out is the number of classes (or labels)\n\n n_hidden: a tuple defining the number of hidden units at each hidden layer\n activation: the nonlinear function for the hidden layers\n\n \"\"\"\n self.input = input\n self.n_in = n_in\n self.n_hiddens = n_hiddens\n\n self.hlayers = []\n self.layers = []\n\n output_in_last_layer = input\n n_out_in_last_layer = n_in\n\n for i in range(len(n_hiddens)):\n hiddenLayer = HiddenLayer( rng=rng, input=output_in_last_layer, n_in=n_out_in_last_layer, n_out=n_hiddens[i], activation=activation)\n self.hlayers.append(hiddenLayer)\n output_in_last_layer = hiddenLayer.output\n n_out_in_last_layer = n_hiddens[i]\n\n ## add the final logistic regression layer\n linLayer = LogRegLayer(rng, output_in_last_layer, n_out_in_last_layer, n_out)\n self.linLayer = linLayer\n self.layers = self.hlayers + [ self.linLayer ]\n\n self.pre_act = linLayer.pre_act\n self.p_y_given_x = linLayer.p_y_given_x\n\n ## here we make self.y_pred have shape (batchSize, 1) instead of (batchSize, )\n self.y_pred = linLayer.y_pred.dimshuffle(0, 'x')\n\n ## self.output has shape (batchSize, n_out)\n self.output = self.p_y_given_x\n self.n_out = n_out\n\n self.paramL1 =0\n self.paramL2 =0\n self.params = []\n\n for layer in self.layers:\n self.paramL1 += layer.paramL1\n self.paramL2 += layer.paramL2\n self.params += layer.params\n\n ## Both y and sampleWeight shall have shape (batchSize, 1) instead of (batchSize,)\n ## this function returns a scalar\n ## useMeanOnly here shall always be set to False, it is used only for placeholder\n def NLL(self, y, useMeanOnly=False, sampleWeight=None):\n assert (y.ndim == 2)\n ##convert to 1d vector\n y0 = y[:,0]\n if sampleWeight is None:\n return self.linLayer.NLL(y0)\n assert (sampleWeight.ndim == 2)\n w = sampleWeight[:, 0]\n return self.linLayer.NLL(y0, w)\n\n ## sampleWeight shall have shape (batchSize, 1) instead of (batchSize,)\n ## y shall have shape (batchSize, valueDims of this response)\n ## this function returns a tensor with ndim =1, the number of elements in this tensor is valueDims of this response\n def errors(self, y, sampleWeight=None):\n assert (y.ndim == 2)\n err = T.neq(self.y_pred, y)\n if sampleWeight is None:\n return T.mean(err, axis=0)\n assert (sampleWeight.ndim == 2)\n return T.sum( T.mul(err, sampleWeight), axis=0)/T.sum(sampleWeight)\n\n ## this function returns a scalar\n def loss(self, y, useMeanOnly=False, sampleWeight=None):\n return self.NLL(y, useMeanOnly, sampleWeight)\n\n\ndef testNN4LogReg(learning_rate=0.01, L1_reg=0.00, L2_reg=0.0001, n_epochs=2000,\n n_hiddens=[200, 200], trainData=None, testData=None):\n\n ## generate some random train and test data\n batchSize = 200000\n nFeatures = 30\n trainX = numpy.random.uniform(0, 1, (batchSize, nFeatures)).astype(numpy.float32)\n trainXsum = numpy.sum(trainX**2, axis=1, keepdims=True)\n trainY = numpy.zeros((batchSize, 1), dtype=numpy.int32 )\n numpy.putmask(trainY, trainXsum>5, 1)\n numpy.putmask(trainY, trainXsum>10, 2)\n numpy.putmask(trainY, trainXsum>15, 3)\n\n testBatchSize = 50\n testX = numpy.random.uniform(0, 1, (testBatchSize, nFeatures)).astype(numpy.float32)\n testXsum = numpy.sum(testX**2, axis=1, keepdims=True)\n testY = numpy.zeros((testBatchSize, 1), dtype=numpy.int32 )\n numpy.putmask(testY, testXsum>5, 1)\n numpy.putmask(testY, testXsum>10, 2)\n numpy.putmask(testY, testXsum>15, 3)\n\n ######################\n # BUILD ACTUAL MODEL #\n ######################\n print('... building the model')\n\n\n x = T.matrix('x') # the data is presented as rasterized images\n y = T.imatrix('y') # the labels\n\n rng = numpy.random.RandomState()\n\n regressor = NN4LogReg(rng, input=x, n_in=trainX.shape[1], n_hiddens=n_hiddens, n_out=4, activation=T.nnet.relu)\n loss = regressor.loss(y)\n error = regressor.errors(y)\n cost = loss + L1_reg * regressor.paramL1 + L2_reg * regressor.paramL2\n\n gparams = [T.grad(cost, param) for param in regressor.params]\n param_shapes = [ param.shape.eval() for param in regressor.params ]\n updates, others = Adam(regressor.params, gparams)\n\n train = theano.function( inputs=[x,y], outputs=[loss, error, regressor.paramL1, regressor.paramL2], updates=updates)\n test = theano.function( inputs=[x,y], outputs=error)\n calculate = theano.function( inputs=[x], outputs=regressor.output )\n\n step = 200\n numEpochs = 30\n for j in range(0, numEpochs):\n results = []\n for i in range(0, trainX.shape[0], step):\n los, err, l1, l2 = train(trainX[i:i+step, :], trainY[i:i+step, :])\n results.append( los )\n if i%5000 == 0:\n print('i=', i, ' loss=', los, ' error=', err, ' L1norm=', l1, ' L2norm=', l2)\n\n print('j=', j, ' avgLos, avgErr=', numpy.mean(results, axis=0))\n\n\n out = calculate(testX)\n print(numpy.around( numpy.concatenate( (out, testY.reshape(testBatchSize, 1) ), axis=1), 2))\n\n print('err=', test(testX, testY))\n\nif __name__ == '__main__':\n testNN4LogReg()\n","sub_path":"NN4LogReg.py","file_name":"NN4LogReg.py","file_ext":"py","file_size_in_byte":10128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"129204104","text":"#coding:utf-8\nimport time\nimport os\nimport pygame\nimport urllib.request\nimport json\nfrom aip import AipSpeech\nimport speech_recognition as sr\nimport urllib3\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)#忽略百度api连接时的报错信息。\n\n# Baidu Speech API\nAPP_ID = '22895018'\nAPI_KEY = 'zzxWTnPxgKxfv4jMcGij1xFH'\nSECRET_KEY = '1uh14bAwqWvM6aaKxwvawnMdbe9RIScQ'\n\nclient = AipSpeech(APP_ID,API_KEY,SECRET_KEY)\n\n#Turing API\nTURING_KEY = \"cafb7e6da9d64e6292434b569aa9b26b\"\nAPI_URL = \"http://openapi.tuling123.com/openapi/api/v2\"\n\n# 录音\ndef rec(rate=16000):\n r = sr.Recognizer()\n with sr.Microphone(sample_rate=rate) as source:\n print(\"please say something\")\n audio = r.listen(source)\n\n with open(\"recording.wav\", \"wb\") as f:\n f.write(audio.get_wav_data())\n\n# 百度语音转文字\ndef listen():\n with open('recording.wav', 'rb') as f:\n audio_data = f.read()\n\n result = client.asr(audio_data, 'wav', 16000, {\n 'dev_pid': 1536,\n })\n\n text_input = result[\"result\"][0]\n\n print(\"我说: \" + text_input)\n Robot_think(text_input)\n\n\n# 图灵处理\ndef Robot_think(text_input):\n req = {\n \"perception\":\n {\n \"inputText\":\n {\n \"text\": text_input\n },\n\n \"selfInfo\":\n {\n \"location\":\n {\n \"city\": \"福州\",\n \"province\": \"福建\",\n \"street\": \"智恒路\"\n }\n }\n },\n \"userInfo\":\n {\n \"apiKey\": TURING_KEY,\n \"userId\": \"starky\" #\"这里随便填\"\n }\n}\n # print(req)\n # 将字典格式的req编码为utf8\n req = json.dumps(req).encode('utf8')\n # print(req)\n\n http_post = urllib.request.Request(API_URL, data=req, headers={'content-type': 'application/json'})\n response = urllib.request.urlopen(http_post)\n response_str = response.read().decode('utf8')\n # print(response_str)\n response_dic = json.loads(response_str)\n # print(response_dic)\n\n intent_code = response_dic['intent']['code']\n results_text = response_dic['results'][0]['values']['text']\n print(\"AI说: \" + results_text)\n du_say(results_text)\n play_mp3('robot.mp3')\n# 文字转语音\ndef du_say(results_text):\n # per 3是汉子 4是妹子,spd 是语速,vol 是音量\n result = client.synthesis(results_text, 'zh', 1, {\n 'vol': 5, 'per': 4, 'spd': 4\n })\n # 识别正确返回语音二进制 错误则返回dict 参照下面错误码\n if not isinstance(result, dict):\n with open('robot.mp3', 'wb') as f:\n f.write(result)\n\n# 播放Mp3文件\ndef play_mp3(file):\n pygame.mixer.init()\n pygame.mixer.music.load(file)\n pygame.mixer.music.play()\n while pygame.mixer.music.get_busy():\n time.sleep(1)\n pygame.mixer.music.stop()\n pygame.mixer.quit()\n \n \n\nif __name__ == '__main__':\n while True:\n rec()\n listen()\n \n \n \n \n \n","sub_path":"turing/key.py","file_name":"key.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"499439696","text":"# Copyright 2016 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\"\"\"Tests for ../__main__.py\"\"\"\n\nimport argparse\nimport unittest\nimport mock\n\nfrom infra.tools.log import log\nfrom infra.tools.log import __main__ as log_main\n\n\nclass MainTests(unittest.TestCase):\n def test_main_options(self):\n parser = argparse.ArgumentParser()\n l = log_main.Log()\n l.add_argparse_options(parser)\n args = parser.parse_args(['cat', 'bootstrap'])\n self.assertEquals(args.command, 'cat')\n self.assertEquals(args.target, ['bootstrap'])\n\n @mock.patch('infra.tools.log.log.LogQuery', autospec=True)\n def test_main(self, _lq):\n args = mock.MagicMock()\n args.command = 'list'\n log_main.Log().main(args)\n # The class is used.\n self.assertGreaterEqual(len(_lq.mock_calls), 1)\n","sub_path":"infra/tools/log/test/__main___test.py","file_name":"__main___test.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"44243274","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Jason Wang\nimport re\n\ndef add(a,b):\n return a+b\n\ndef minus(a,b):\n return a-b\n\ndef multi(a,b):\n return a*b\ndef divd(a,b):\n return a/b\ndef handle_chenchu(s):\n n_li = []\n count = 0\n flag = True\n while flag:\n for i in s:\n if re.match(r'(\\d+\\.?\\d*[*]\\d+\\.?\\d*)',i):#匹配单个*号 eg: 3.3*4.4\n a,b = i.split('*')\n i = multi(float(a),float(b))\n i = str(i)\n n_li.append(i)\n elif re.match(r'(\\d+\\.?\\d*[/]\\d+\\.?\\d*)',i):#匹配/号 eg:3.3/4.4\n a,b = i.split('/')\n i = divd(float(a),float(b))\n i = str(i)\n n_li.append(i)\n elif re.match(r'([+-]?\\d+\\.?\\d*[*/]+[-+]+\\d+\\.?\\d*)',i):#匹配[*-]和-符号在一块的情况 eg. 3.3*-4.4 或4.4/-3.3\n i = re.split(r'(\\d+\\.?\\d*[*/]{1}[-+]{1}\\d+\\.?\\d*[^+\\-*/])',i)\n for m in i:\n if re.match(r'\\d+\\.?\\d*[*]{1}[-]{1}\\d+\\.?\\d*',m):\n t = 0\n a,b=m.split('*-')\n t -= multi(float(a),float(b))\n t = str(t)\n n_li.append(t)\n elif re.match(r'\\d+\\.?\\d*[/]{1}[-]{1}\\d+\\.?\\d*',m):\n if re.findall('[-]$',m):\n n_li.append(m)\n else:\n t = 0\n a,b=m.split('/-')\n t -= divd(float(a),float(b))\n t = str(t)\n n_li.append(t)\n else:\n n_li.append(m)\n print('去除*和-连接问题')\n else:\n n_li.append(i)\n print(n_li)\n s = ''.join(i for i in n_li)\n print(s)\n return n_li\ndef handlejiajian(s):\n li = re.split(r'[+]',s)\n # print('去掉加号')\n print(li)\n n_li = []\n for i in li:\n if '*' in i:\n a=i.split('*')\n print(a)\n total= 1\n for j in a:\n if '/' not in j:#去括号再次拼接字符串后出现*,需要再次去掉*\n print(j)\n print(total)\n total = float(total)\n total *= float(j)\n # total = str(total)\n else:#去括号再次拼接字符串后出现/,需要再次去掉/\n tt = j.split('/')\n tt_total = float(tt[0])\n for i in tt[1:]:\n tt_total /= float(i)\n total *= tt_total\n total = str(total)\n print(total)\n n_li.append(total)\n if '-' not in i:\n n_li.append(i)\n else:#去掉减号\n # p = re.split(r'([-]?\\d+\\.?\\d*\\d+\\.?\\d*)',i)\n if re.findall(r'^[-]',i):\n n_li.append(i)\n elif re.findall(r'[-]$',i):\n n_li.append(i)\n else:\n if '*' not in i:\n p = re.split(r'-',i)\n temp = float(p[0])\n for k in p[1:]:\n # print(k)\n temp -= float(k)\n print(temp)\n n_li.append(temp)\n print('拆分为单个数字')\n print(n_li)\n total = 0\n for i in n_li:\n if i != '':\n total += float(i)\n print(total)\n total = str(total)\n print(total)\n return total\ndef cal(s):\n # li = re.split(r'(\\d{1}[*/]\\d{1})',s)\n flag = True\n # count = 0\n while flag:\n li = re.split(r'(\\d+\\.?\\d*[*/]\\d+\\.?\\d*)',s)\n print(li)\n n_li = handle_chenchu(li)\n s = ''.join(i for i in n_li)\n # if '*' in s or '-' in s:\n # n_li = handle_chenchu()\n # s = ''.join(i for i in n_li)\n print('去掉乘号和除号')\n print(s)\n if '*' not in s and '/' not in s:\n flag = False\n s = handlejiajian(s)\n return s\n# test1 = '8*12+(6-(5*6-2)/77+2)*(3-7)*2+8+(20*3)++++++---+3+++++2'\n# test1 = '8*12+(6-(5*6-2)/77+2)*(3-7)*(3+5)*(3+5)/2+8'\ndef strip_k(s):\n # p = re.compile(r'\\(\\d[+\\-*/]*(\\d*[^()]\\d*)[+\\-*/]*\\d\\)')\n li = []\n flag = True\n count = 0\n while flag:\n count += 1\n p = re.compile(r'\\(([^()]*)\\)')\n # print(p.split(s))\n # print(p.findall(s))\n num_1 = 0\n num_2 = 0\n for i in s:\n if re.match(r'.*\\(.*',i):#标记(出现的次数\n num_1 += i.count('(')\n elif re.match(r'.*\\).*',i):#标记)出现的次数\n num_2 += i.count(')')\n if num_1 == 0 and num_2 == 0:\n cal(s)\n flag = False\n break\n elif num_1 >0 and num_2 >0:\n ##去除***或///连续出现的情况\n s = re.sub(r'\\*+','*',s)\n s = re.sub(r'\\/+','/',s)\n print(s)\n ##去除加号减号混合出现的情况;eg. 3+++4-+----++++6\n if re.findall(r'([+-]{2,})',s):\n a = re.split(r'([+-]{2,})',s)\n print('here')\n print(a)\n sl = []\n for i in a:#去掉重复的+-号\n m = re.match(r'[+-]{2,}',i)\n print(m)\n if m:\n if m.group().count('-')%2 == 1:\n # print(i)\n sl.append('-')\n else:\n sl.append('+')\n else:\n sl.append(i)\n s = ''.join(i for i in sl)\n li = p.split(s)\n # li = p.split(s)\n print(li)\n n_li = []\n for i in li:\n print(i)\n if re.match(r'.*[()]+.*',i):#匹配到包含括号的不处理\n print(i)\n n_li.append(i)\n elif re.match(r'^[+\\-*/]{1}.*',i):#匹配到运算符开头的不处理\n n_li.append(i)\n elif re.match(r'.*[+\\-*/]{1}$',i):#匹配到运算符结尾的不处理\n n_li.append(i)\n else:#不包含括号的调用计算器函数\n t = cal(i)\n print(t)\n n_li.append(t)\n # for i in n_li:\n # if i == 'None':\n # n_li.remove(i)\n # print(n_li)\n s = ''.join(i for i in n_li)\n print('#拼接成新的字符串')\n print(s)\n\nif __name__ == '__main__':\n ss = input('输入计算的方程式').strip()\n strip_k(ss)\n","sub_path":"day6/calculates.py","file_name":"calculates.py","file_ext":"py","file_size_in_byte":6698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"378082160","text":"import pandas as pd\nimport openpyxl\nfrom itertools import islice\n\n\ndef count_medicine(filename):\n wb_obj = openpyxl.load_workbook(filename, read_only=True)\n result = {}\n for wb in wb_obj.worksheets:\n res = process_one_wb(wb)\n result[wb.title] = pd.DataFrame([[key, res[key]] for key in res.keys()], columns=['name', 'sold'])\n name = filename.split('.')[0]\n result_file_name = f'{name}_result.xlsx'\n with pd.ExcelWriter(result_file_name) as writer:\n for key in result.keys():\n result[key].to_excel(writer, sheet_name=key, index=False)\n return result_file_name\n\n\ndef process_one_wb(wb):\n values = {}\n for row in islice(wb.rows, 3, None):\n if isinstance(row[2].value, str):\n vals = [str(cell.value) for cell in row if cell.value is not None]\n key_v = vals[0]\n data = ' '.join(vals[2:])\n del vals\n data = data.replace('x', '')\n data = data.replace(' ', '')\n c_sold = data.count('JL')\n if key_v in values.keys():\n values[key_v] = values[key_v] + c_sold\n else:\n values[key_v] = c_sold\n return {k: v for k, v in sorted(values.items(), key=lambda item: item[1])}\n","sub_path":"count_server.py","file_name":"count_server.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"463335557","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# =============================================================================\n## @file derivative.py \n# Simple adaptive numerical differentiation (for pyroot/PyRoUts/Ostap)\n# R. De Levie, \"An improved numerical approximation for the first derivative\"\n# @see http://www.ias.ac.in/chemsci/Pdf-Sep2009/935.pdf\n#\n# .. and also very simple wrapper to numerical integation using scipy\n#\n# @author Vanya BELYAEV Ivan.Belyaev@itep.ru\n# @date 2014-06-06\n# \n# =============================================================================\n\"\"\"Simple adaptive numerical differentiation (for pyroot/PyRoUts/Ostap/...)\n\n>>> func = lambda x : x*x\n>>> print derivative ( func , 1 )\n\n... and also very simple wrapper to numerical integation using scipy\n\n>>> func = lambda x : x*x\n>>> print integral ( func , 0 , 1 )\n\nthere are also object form:\n\n>>> func = ...\n>>> deriv = Derivative ( func )\n>>> integ = Integral ( func , 0 )\n>>> print deriv ( 0.1 ) , integ ( 0.1 ) \n\"\"\"\n# =============================================================================\n__version__ = \"$Revision$\"\n__author__ = \"Vanya BELYAEV Ivan.Belyaev@itep.ru\"\n__date__ = \"2014-06-06\"\n__all__ = (\n ##\n \"derivative\" , ## numerical differentiation (as function)\n \"Derivative\" , ## numerical differentiation (as object)\n ## \n \"partial\" , ## numerical partial derivatives (as function)\n \"Partial\" , ## numerical partial derivatives (as object) \n ##\n 'EvalVE' , ## evaluate the function taking argument's unicertainty \n 'Eval2VE' , ## evaluate 2-argument function with argument's unicertainties\n ) \n# =============================================================================\nimport ROOT\n# =============================================================================\n# logging \n# =============================================================================\nfrom ostap.logger.logger import getLogger\nif '__main__' == __name__ : logger = getLogger ( 'ostap.math.deriv' )\nelse : logger = getLogger ( __name__ )\n# =============================================================================\nfrom sys import float_info\n_eps_ = float_info.epsilon\nif not 0.75 < _eps_ * 2**52 < 1.25 :\n import warnings\n warnings.warn ('\"epsilon\" in not in the expected range!Math could be suboptimal')\n# =============================================================================\nfrom ostap.math.base import cpp,iszero,isequal\nfrom ostap.math.ve import VE \n# =============================================================================\n_next_double_ = cpp.Ostap.Math.next_double\n_mULPs_ = 1000 \ndef _delta_ ( x , ulps = _mULPs_ ) :\n n1 = _next_double_ ( x , ulps )\n n2 = _next_double_ ( x , -ulps )\n return max ( abs ( n1 - x ) , abs ( n2 - x ) )\n\n# =============================================================================\n## calculate 1st (and optionally 3rd) derivative with the given step\n# - f' is calculated as O(h**2)\n# - f^(III) is calculated as O(h**2)\ndef _h2_ ( func , x , h , der = False ) :\n \"\"\"Calculate 1st (and optionally 3rd) derivative \n - f' is calculated as O(h**2)\n - f^(III) is calculated as O(h**2)\n \"\"\"\n fm1 = func ( x - 1 * h )\n fp1 = func ( x + 1 * h )\n\n d1 = 1.0 * ( fp1 - fm1 ) / (2 * h )\n if not der : return d1 \n \n fm2 = func ( x - 2 * h ) \n fp2 = func ( x + 2 * h )\n\n d3 = -2.0 * ( fp1 - fm1 ) + ( fm2 - fm2 ) \n d3 /= (2 * h*h*h)\n\n return d1,d3\n\n# =============================================================================\n## calculate 1st (and optionally 5th) derivative with the given step\n# - f' is calculated as O(h**4)\n# - f^(V) is calculated as O(h**2)\ndef _h4_ ( func , x , h , der = False ) :\n \"\"\"Calculate 1st (and optionally 5th) derivative with O(h*h) precision\n - f' is calculated as O(h**4)\n - f^(V) is calculated as O(h**2)\n \"\"\" \n fm2 = func ( x - 2 * h ) \n fm1 = func ( x - 1 * h )\n fp1 = func ( x + 1 * h )\n fp2 = func ( x + 2 * h )\n \n d1 = 8.0 * ( fp1 - fm1 ) - ( fp2 - fm2 )\n d1 /= 12 * h \n \n if not der : return d1 \n \n fm3 = func ( x - 3 * h ) \n fp3 = func ( x + 3 * h )\n \n d5 = 5.0 * ( fp1 - fm1 ) - 4 * ( fp2 - fm2 ) + ( fp3 - fm3 )\n d5 /= 2 * h**5 \n \n return d1,d5\n\n\n# =============================================================================\n## calculate 1st (and optionally 7th) derivative with the given step\n# - f' is calculated as O(h**6)\n# - f^(VII) is calculated as O(h**2)\ndef _h6_ ( func , x , h , der = False ) :\n \"\"\"Calculate 1st (and optionally 7th) derivative\n - f' is calculated as O(h**6)\n - f^(VII) is calculated as O(h**2)\n \"\"\" \n fm3 = func ( x - 3 * h ) \n fm2 = func ( x - 2 * h ) \n fm1 = func ( x - 1 * h )\n fp1 = func ( x + 1 * h )\n fp2 = func ( x + 2 * h )\n fp3 = func ( x + 3 * h )\n \n d1 = 45.0 * ( fp1 - fm1 ) - 9 * ( fp2 - fm2 ) + 1 * ( fp3 - fm3 )\n d1 /= 60*h\n\n if not der : return d1\n \n fm4 = func ( x - 4 * h ) \n fp4 = func ( x + 4 * h )\n \n d7 = -14.0 * ( fp1 - fm1 ) + 14 * ( fp2 - fm2 ) - 6 * ( fp3 - fm3 ) + ( fp4 - fm4 )\n d7 /= 2* h**7\n \n return d1,d7\n\n\n# =============================================================================\n## calculate 1st (and optionally 9th) derivative with the given step\n# - f' is calculated as O(h**8)\n# - f^(IX) is calculated as O(h**2)\ndef _h8_ ( func , x , h , der = False ) :\n \"\"\"Calculate 1st (and optionally 9th) derivative\n - f' is calculated as O(h**8)\n - f^(IX) is calculated as O(h**2)\n \"\"\" \n fm4 = func ( x - 4 * h ) \n fm3 = func ( x - 3 * h ) \n fm2 = func ( x - 2 * h ) \n fm1 = func ( x - 1 * h )\n fp1 = func ( x + 1 * h )\n fp2 = func ( x + 2 * h )\n fp3 = func ( x + 3 * h )\n fp4 = func ( x + 4 * h )\n \n d1 = 672.0 * ( fp1 - fm1 ) - 168 * ( fp2 - fm2 ) + 32 * ( fp3 - fm3 ) - 3 * ( fp4 - fm4 )\n d1 /= 840 * h \n \n if not der : return d1 \n \n fm5 = func ( x - 5 * h ) \n fp5 = func ( x + 5 * h )\n d9 = ( -fm5 +8*fm4 -27*fm3 + 48*fm2 - 42*fm1 + 42*fp1 - 48*fp2 +27*fp3 -8*fp4 + fp5 )/( 2 * h**9)\n\n d9 = 42.0 * ( fp1 - fm1 ) - 48 * ( fp2 - fm2 ) + 27 * ( fp3 - fm3 ) - 8 * ( fp4 - fm4 ) + ( fp5 - fm5 ) \n d9 /= 2 * h**9\n \n return d1,d9\n\n# =============================================================================\n## calculate 1st (and optionally 11th) derivative with the given step\n# - f' is calculated as O(h**10)\n# - f^(XI) is calculated as O(h**2)\ndef _h10_ ( func , x , h , der = False ) :\n \"\"\"Calculate 1st (and optionally 11th) derivative\n - f' is calculated as O(h**10)\n - f^(XI) is calculated as O(h**2)\n \"\"\"\n fm5 = func ( x - 5 * h ) \n fm4 = func ( x - 4 * h ) \n fm3 = func ( x - 3 * h ) \n fm2 = func ( x - 2 * h ) \n fm1 = func ( x - 1 * h )\n fp1 = func ( x + 1 * h )\n fp2 = func ( x + 2 * h )\n fp3 = func ( x + 3 * h )\n fp4 = func ( x + 4 * h )\n fp5 = func ( x + 5 * h )\n \n d1 = 2100.0 * ( fp1 - fm1 ) - 600 * ( fp2 - fm2 ) + 150 * ( fp3 - fm3 ) - 25 * ( fp4 - fm4 ) + 2 * ( fp5 - fm5 )\n d1 /= 2520.0 * h \n \n\n if not der : return d1\n \n fm6 = func ( x - 6 * h ) \n fp6 = func ( x + 6 * h )\n \n d11 = -132.0 * ( fp1 - fm1 ) + 165 * ( fp2 - fm2 ) - 110 * ( fp3 - fm3 ) + 44 * ( fp4 - fm4 ) - 10 * ( fp5 - fm5 ) + ( fp6 - fm6 ) \n d11 /= 2*h**11\n \n return d1,d11\n\n# =============================================================================\n## calculate 1st (and optionally 13th) derivative with the given step\n# - f' is calculated as O(h**12)\n# - f^(XIII) is calculated as O(h**2)\ndef _h12_ ( func , x , h , der = False ) :\n \"\"\"Calculate 1st (and optionally 13th) derivative\n - f' is calculated as O(h**12)\n - f^(XIII) is calculated as O(h**2)\n \"\"\"\n \n fm6 = func ( x - 6 * h ) \n fm5 = func ( x - 5 * h ) \n fm4 = func ( x - 4 * h ) \n fm3 = func ( x - 3 * h ) \n fm2 = func ( x - 2 * h ) \n fm1 = func ( x - 1 * h )\n fp1 = func ( x + 1 * h )\n fp2 = func ( x + 2 * h )\n fp3 = func ( x + 3 * h )\n fp4 = func ( x + 4 * h )\n fp5 = func ( x + 5 * h )\n fp6 = func ( x + 6 * h )\n \n d1 = 23760.0 * ( fp1 - fm1 ) - 7425 * ( fp2 - fm2 ) + 2200 * ( fp3 - fm3 ) - 495 * ( fp4 - fm4 ) + 72 * ( fp5 - fm5 ) - 5 * ( fp6 - fm6 )\n d1 /= 27720.0 * h \n \n if not der : return d1\n \n fm7 = func ( x - 7 * h ) \n fp7 = func ( x + 7 * h )\n\n d13 = 429.0 * ( fp1 - fm1 ) - 572 * ( fp2 - fm2 ) + 429 * ( fp3 - fm3 ) - 208 * ( fp4 - fm4 ) + 65 * ( fp5 - fm5 ) - 12 * ( fp6 - fm6 ) + ( fp7 - fm7 ) \n d13 /= 2*h**13\n \n return d1,d13\n\n# =============================================================================\n## calculate 1st (and optionally 15th) derivative with the given step\n# - f' is calculated as O(h**14)\n# - f^(XV) is calculated as O(h**2)\ndef _h14_ ( func , x , h , der = False ) :\n \"\"\"Calculate 1st (and optionally 15th) derivative\n - f' is calculated as O(h**12)\n - f^(XV) is calculated as O(h**2)\n \"\"\"\n \n fm7 = func ( x - 7 * h ) \n fm6 = func ( x - 6 * h ) \n fm5 = func ( x - 5 * h ) \n fm4 = func ( x - 4 * h ) \n fm3 = func ( x - 3 * h ) \n fm2 = func ( x - 2 * h ) \n fm1 = func ( x - 1 * h )\n fp1 = func ( x + 1 * h )\n fp2 = func ( x + 2 * h )\n fp3 = func ( x + 3 * h )\n fp4 = func ( x + 4 * h )\n fp5 = func ( x + 5 * h )\n fp6 = func ( x + 6 * h )\n fp7 = func ( x + 7 * h )\n \n d1 = 315315.0 * ( fp1 - fm1 ) - 105105 * ( fp2 - fm2 ) + 35035 * ( fp3 - fm3 ) - 9555 * ( fp4 - fm4 ) + 1911 * ( fp5 - fm5 ) - 245 * ( fp6 - fm6 ) + 15 * ( fp7 - fm7 ) \n d1 /= 360360.0 * h \n \n if not der : return d1\n \n fm8 = func ( x - 8 * h ) \n fp8 = func ( x + 8 * h )\n\n d15 = -1430.0 * ( fp1 - fm1 ) + 2002 * ( fp2 - fm2 ) - 1638 * ( fp3 - fm3 ) + 910 * ( fp4 - fm4 ) - 350 * ( fp5 - fm5 ) + 90 * ( fp6 - fm6 ) - 14 * ( fp7 - fm7 ) + ( fp8 - fm8 ) \n d15 /= 2*h**15\n \n return d1,d15\n\n# =============================================================================\n## calculate 1st (and optionally 17th) derivative with the given step\n# - f' is calculated as O(h**16)\n# - f^(XVII) is calculated as O(h**2)\ndef _h16_ ( func , x , h , der = False ) :\n \"\"\"Calculate 1st (and optionally 17th) derivative\n - f' is calculated as O(h**16)\n - f^(XVII) is calculated as O(h**2)\n \"\"\"\n \n fm8 = func ( x - 8 * h ) \n fm7 = func ( x - 7 * h ) \n fm6 = func ( x - 6 * h ) \n fm5 = func ( x - 5 * h ) \n fm4 = func ( x - 4 * h ) \n fm3 = func ( x - 3 * h ) \n fm2 = func ( x - 2 * h ) \n fm1 = func ( x - 1 * h )\n fp1 = func ( x + 1 * h )\n fp2 = func ( x + 2 * h )\n fp3 = func ( x + 3 * h )\n fp4 = func ( x + 4 * h )\n fp5 = func ( x + 5 * h )\n fp6 = func ( x + 6 * h )\n fp7 = func ( x + 7 * h )\n fp8 = func ( x + 8 * h )\n \n d1 = 640640.0 * ( fp1 - fm1 ) - 224224 * ( fp2 - fm2 ) + 81536 * ( fp3 - fm3 ) - 25480 * ( fp4 - fm4 ) + 6272 * ( fp5 - fm5 ) - 1120 * ( fp6 - fm6 ) + 128 * ( fp7 - fm7 ) - 7 * ( fp8 - fm8 ) \n d1 /= 720720.0 * h \n \n if not der : return d1\n \n fm9 = func ( x - 9 * h ) \n fp9 = func ( x + 9 * h )\n\n d17 = 4862.0 * ( fp1 - fm1 ) - 7072 * ( fp2 - fm2 ) + 6188 * ( fp3 - fm3 ) - 3808 * ( fp4 - fm4 ) + 1700 * ( fp5 - fm5 ) - 544 * ( fp6 - fm6 ) + 119 * ( fp7 - fm7 ) - 16 * ( fp8 - fm8 ) + ( fp9 - fm9 ) \n d17 /= 2*h**17\n \n return d1,d17\n\n# =============================================================================\n# The actual setup for\n# =============================================================================\n_funcs_ = (\n _h2_ , ## 0 == 1 \n _h2_ , ## 1 \n _h4_ , ## 2 \n _h6_ , ## 3\n _h8_ , ## 4 \n _h10_ , ## 5 \n _h12_ , ## 6\n _h14_ , ## 7\n _h16_ ## 8\n )\n_numbers_ = (\n ( 0.5*10**(-10./ 3) ,\n 0.5*10**(-10./ 3) ,\n 0.5*10**(-10./ 5) ,\n 0.5*10**(-10./ 7) ,\n 0.5*10**(-10./ 9) ,\n 0.5*10**(-10./11) , \n 0.5*10**(-10./13) , \n 0.5*10**(-10./15) , \n 0.5*10**(-10./17) ) , \n ( 6 , 4.5324e-17 , 5.1422e-6 , 6.0554e-6 ) , ## I=1, J= 3 3-point rule \n ( 30 , 6.0903e-17 , 8.5495e-4 , 7.4009e-4 ) , ## I=2, J= 5 5-point rule \n ( 140 , 6.9349e-17 , 7.7091e-3 , 5.8046e-4 ) , ## I=3, J= 7 7-point rule \n ( 630 , 7.4832e-17 , 2.6237e-2 , 1.8227e-2 ) , ## I=4, J= 9 9-point rule \n ( 2772 , 7.8754e-17 , 5.7292e-2 , 3.7753e-2 ) , ## I=5, J=11 11-point rule \n ( 12012 , 8.1738e-17 , 9.8468e-2 , 6.2500e-2 ) , ## I=6, J=13 13-point rule \n ( 51480 , 8.4108e-17 , 1.4656e-1 , 9.0454e-1 ) , ## I=7, J=15 15-point rule \n ( 218790 , 8.6047e-17 , 1.9873e-1 , 1.2000e-1 ) , ## I=8, J=17 17-point rule \n )\n\n# =============================================================================\n## Calculate the first derivative for the function\n# R. De Levie, \"An improved numerical approximation for the first derivative\"\n# @see http://www.ias.ac.in/chemsci/Pdf-Sep2009/935.pdf\n# @code\n# >>> fun = lambda x : x*x\n# >>> print derivative ( fun , x = 1 ) \n# @endcode\n# @param fun (INPUT) the function itself\n# @param x (INPUT) the argument\n# @param h (INPUT) the guess for the step used in numeric differentiation\n# @param I (INPUT) the rule to be used (\"N-point rule\" = 2*I+1)\n# @param err (INPUT) calcualte the uncertainty?\n# @author Vanya BELYAEV Ivan.Belyaev@itep.ru\n# @date 2014-06-06\ndef derivative ( fun , x , h = 0 , I = 2 , err = False ) : \n \"\"\"Calculate the first derivative for the function\n # @code\n # >>> fun = lambda x : x*x\n # >>> print derivative ( fun , x = 1 ) \n \"\"\"\n\n func = lambda x : float ( fun ( x ) )\n \n ## get the function value at the given point \n f0 = func(x)\n\n ## adjust the rule \n I = min ( max ( I , 1 ) , 8 )\n J = 2 * I + 1\n \n _dfun_ = _funcs_[I]\n delta = _delta_ ( x )\n \n ## if the intial step is too small, choose another one \n if abs ( h ) < _numbers_[I][3] or abs ( h ) < delta : \n if iszero( x ) : h = _numbers_[0][I]\n else : h = abs ( x ) * _numbers_[I][3] \n \n ## 1) find the estimate for first and \"J\"th the derivative with the given step \n d1,dJ = _dfun_( func , x , h , True )\n \n ## find the optimal step \n if iszero ( dJ ) or ( iszero ( f0 ) and iszero ( x * d1 ) ) :\n if iszero ( x ) : hopt = _numbers_[0][I] \n else : hopt = abs ( x ) * _numbers_[I][3]\n else : \n hopt = _numbers_[I][2]*( ( abs ( f0 ) + abs ( x * d1 ) ) / abs ( dJ ) )**( 1.0 / J )\n\n ## finally get the derivative \n if not err : return _dfun_ ( func , x , hopt , False )\n\n ## estimate the uncrtainty, if needed \n d1,dJ = _dfun_ ( func , x , hopt , True )\n e = _numbers_[I][1]/(J-1)/_numbers_[I][2]\n e2 = e * e * ( J * _eps_ + abs ( f0 ) + abs( x * d1 ) )**(2-2./J) * abs( dJ )**(2./J)\n return VE ( d1 , 4 * e2 )\n\n# =============================================================================\n## @class Derivative\n# Calculate the first derivative for the function\n# R. De Levie, \"An improved numerical approximation for the first derivative\"\n# @see http://www.ias.ac.in/chemsci/Pdf-Sep2009/935.pdf\n# @code\n# func = math.sin\n# deriv = Derivative ( func ) \n# @endcode \n# @author Vanya BELYAEV Ivan.Belyaev@itep.ru\n# @date 2014-06-06\nclass Derivative(object) :\n \"\"\"Calculate the first derivative for the function\n R. De Levie, ``An improved numerical approximation for the first derivative''\n see http://www.ias.ac.in/chemsci/Pdf-Sep2009/935.pdf\n >>> func = math.sin\n >>> deri = Derivative ( func ) \n \"\"\"\n # =========================================================================\n ## constructor \n # @param func the function\n # @param step proposed initial step for evaluation of derivatives\n # @param order derivative is calcualated using 2*I(+1) point\n # @param err evaluate numerical uncertainties?\n def __init__ ( self , func , step = 0 , order = 2 , err = False ) :\n \"\"\"Calculate the first derivative for the function\n R. De Levie, ``An improved numerical approximation for the first derivative''\n see http://www.ias.ac.in/chemsci/Pdf-Sep2009/935.pdf\n - func: the function\n - step: proposed initial step for evaluation of derivatives\n - order derivative is calcuakted using 2*I+1 point\n - err evaluate numerical uncertainties?\n >>> func = math.sin\n >>> deri = Derivative ( func ) \n \"\"\"\n self._func = func\n self._step = float( step ) \n self._order = int ( order )\n self._err = True if err else False \n if self._order < 0 :\n raise AttributeError(\"Invalid ``order''-parameter!\")\n\n # =========================================================================\n ## evaluate the derivative\n # @code \n # func = math.sin\n # deriv = Derivative ( func )\n # print deriv(0.1)\n # @endcode \n def __call__ ( self , x ) :\n \"\"\"Calculate the first derivative for the function\n R. De Levie, ``An improved numerical approximation for the first derivative''\n see http://www.ias.ac.in/chemsci/Pdf-Sep2009/935.pdf\n \n >>> func = math.sin\n >>> deriv = Derivative ( func )\n \n >>> print deriv(0.1) \n \"\"\"\n return derivative ( self._func ,\n x ,\n self._step ,\n self._order ,\n self._err )\n\n# =============================================================================\n## Calculate the partial derivative for the function\n# @see derivative\n# R. De Levie, \"An improved numerical approximation for the first derivative\"\n# @see http://www.ias.ac.in/chemsci/Pdf-Sep2009/935.pdf\n# @code\n# >>> fun2 = lambda x,y : x*x+y*y\n# >>> print partial ( 0 , fun , (1.0,2.0) ) ) \n# @endcode\n# @param index (INPUT) indx of the variable \n# @param func (INPUT) the function itself\n# @param x (INPUT) the argument\n# @param h (INPUT) the guess for the step used in numeric differentiation\n# @param I (INPUT) the rule to be used (\"N-point rule\" = 2*I+1)\n# @param err (INPUT) calcualte the uncertainty?\n# @author Vanya BELYAEV Ivan.Belyaev@itep.ru\n# @date 2014-06-06\ndef partial ( index , func , x , h = 0 , I = 2 , err = False ) : \n \"\"\"Calculate the partial derivative for the function\n - index (INPUT) indx of the variable \n - func (INPUT) the function itself\n - x (INPUT) the argument\n - h (INPUT) the guess for the step used in numeric differentiation\n - I (INPUT) the rule to be used (\"N-point rule\" = 2*I+1)\n - err (INPUT) calcualte the uncertainty?\n \n Algorithm used:\n R. De Levie, ``An improved numerical approximation for the first derivative''\n - see http://www.ias.ac.in/chemsci/Pdf-Sep2009/935.pdf\n >>> fun2 = lambda x,y : x*x+y*y\n >>> print partial ( 0 , fun , (1.0,2.0) ) ) \n - see derivative\n \"\"\"\n \n if len(x) <= index :\n raise AttributeError(\"Invalid argument length/index %d/%d\" % ( len(x) , index ) )\n \n _x = [ float(a) for a in x ]\n \n ## create wrapper function \n def _wrap ( z ) :\n _z = _x[index] \n _x[index] = z\n _r = func ( *_x )\n _x[index] = _z\n return _r\n \n xi = _x[ index ]\n return derivative ( _wrap , xi , h , I , err )\n\n# =============================================================================\n## calcuate the partial derivative for the function\n# @code\n# func = lambda x, y: x * x + y * y \n# dFdX = Partial ( 0 , func )\n# dFdY = Partial ( 1 , func )\n# x = 1\n# y = 2\n# print ' f(%f,%f)=%f ' % ( x , y , func( x, y ) ) \n# print ' dFdX=%f dFdY=%f' % ( dFdX(x,y), dFdY ( x, y ) ) \n# @endcode \n# @see Derivative\n# @see partial \n# @author Vanya BELYAEV Ivan.Belyaev@itep.ru\n# @date 2017-01-25\nclass Partial(Derivative) :\n \"\"\"Calcuate the partial derivative for the function\n >>> func = lambda x, y: x * x + y * y \n >>> dFdX = Partial( 0 , func )\n >>> dFdY = Partial( 1 , func )\n >>> x = 1\n >>> y = 2\n >>> print ' f(%f,%f)=%f ' % ( x , y , func( x, y ) ) \n >>> print ' dFdX=%f dFdY=%f' % ( dFdX(x,y), dFdY ( x, y ) ) \n \"\"\"\n # =========================================================================\n ## constructor\n # @param index index of the variable (>=0)\n # @param func the function\n # @param step proposed initial step for derivatives \n # @param order derivative is evaluated using 2*I(+1) point (>=0) \n # @param err estimate the numerical uncertainty?\n def __init__ ( self ,\n index , ## index of the variabale \n func , ## the function \n step = 0 , ## proposed initial step for derivatives\n order = 2 , ## J=2*I(+1) is a number of points used for evaluation of derivative\n err = False ) : ## estimate the uncertainty?\n \"\"\"Calculate the partial derivative for the function\n - index (INPUT) indx of the variable \n - func (INPUT) the function itself\n - step (INPUT) the guess for the step used in numeric differentiation\n - order (INPUT) the rule to be used (\"N-point rule\" = 2*I+1)\n - err (INPUT) calcualte the uncertainty?\n >>> func = lambda x, y: x * x + y * y \n >>> dFdX = Partial( 0 , func )\n >>> dFdY = Partial( 1 , func )\n >>> x = 1\n >>> y = 2\n >>> print ' f(%f,%f)=%f ' % ( x , y , func( x, y ) ) \n >>> print ' dFdX=%f dFdY=%f' % ( dFdX(x,y), dFdY ( x, y ) ) \n \"\"\"\n if isinstance ( index , (int,long) ) and 0 <= index :\n self._index = index\n else :\n raise AttributeError(\"Invalid variable index %s\" % index)\n\n ## keep the function \n self._func2 = func\n \n ## initialize the base \n Derivative.__init__ ( self , func , step , order , err )\n \n # =========================================================================\n ## evaluate the derivative\n # @code \n # func = math.sin\n # deriv = Derivative ( func )\n # print deriv(0.1)\n # @endcode \n def __call__ ( self , *x ) :\n \"\"\"Calcuate the partial derivative for the function\n >>> func = lambda x, y: x * x + y * y \n >>> dFdX = Partial( 0 , func )\n >>> dFdY = Partial( 1 , func )\n >>> x = 1\n >>> y = 2\n >>> print ' f(%f,%f)=%f ' % ( x , y , func( x, y ) ) \n >>> print ' dFdX=%f dFdY=%f' % ( dFdX(x,y), dFdY ( x, y ) )\n \"\"\"\n return partial ( self._index ,\n self._func2 ,\n x ,\n self._step ,\n self._order ,\n self._err )\n \n# =============================================================================\n## @class EvalVE\n# Evaluate the function taking into account the uncertainty in the argument\n# @code\n# import math \n# x = VE(1,0.1**2)\n# sin = EvalVE( math.sin , lambda s : math.cos(s) )\n# print 'sin(x) = %s ' % sin(x) \n# @endcode\n# @see ostap.math.math_ve \n# @author Vanya BELYAEV Ivan.Belyaev@itep.ru\n# @date 2016-02-23\nclass EvalVE(object) :\n \"\"\"Evaluate the function taking into account uncertainty in the argument\n \n >>> import math \n >>> x = VE(1,0.1**2)\n >>> sin1 = EvalVE( math.sin , lambda s : math.cos(s) )\n >>> print 'sin1(x) = %s ' % sin1(x) \n >>> sin2 = EvalVE( math.sin )\n >>> print 'sin2(x) = %s ' % sin2(x) \n see also ostap.math.math_ve\n \"\"\"\n ## constructor\n def __init__ ( self , func , deriv = None , name = '' ) :\n \"\"\" Constructor from the function, derivative and name\n >>> sin1 = EvalVE( math.sin , lambda s : math.cos(s) )\n >>> sin2 = EvalVE( math.sin ) ## numerical derivative will be used \n \"\"\"\n self._func = func\n if deriv : self._deriv = deriv\n elif hasattr ( func , 'derivative' ) :\n try :\n self._deriv = func.derivative() ## derivative as object?\n except:\n self._deriv = func.derivative ## derivative as function \n elif hasattr ( func , 'Derivative' ) :\n try :\n self._deriv = func.Derivative() ## derivative as object?\n except:\n self._deriv = func.Derivative ## derivative as function \n else :\n ## use numerical differentiation\n self._deriv = Derivative(func)\n \n if name : self.__name__ = name \n elif hasattr ( func , '__name__' ) and '' != func.__name__ :\n self.__name__ = func.__name__\n else : self.__name__ = 'Eval2VE'\n\n ## printout \n def __str__ ( self ) : return str ( self.__name__ )\n __repr__ = __str__\n \n ## get a value \n def _value_ ( self , x , *args ) :\n \"\"\"Evaluate a function\"\"\"\n return self._func( float( x ) , *args )\n\n # =========================================================================\n ## Evaluate the function taking into account uncertainty in the argument\n # @code\n # import math \n # x = VE(1,0.1**2)\n # sin1 = EvalVE( math.sin , lambda s : math.cos(s) )\n # print 'sin1(x) = %s ' % sin1(x) \n # sin2 = EvalVE( math.sin )\n # print 'sin2(x) = %s ' % sin2(x)\n # @endcode\n def __call__ ( self , x , *args ) :\n \"\"\"Evaluate the function taking into account uncertainty in the argument \n >>> import math \n >>> x = VE(1,0.1**2)\n >>> sin1 = EvalVE( math.sin , lambda s : math.cos(s) )\n >>> print 'sin1(x) = %s ' % sin1(x) \n >>> sin2 = EvalVE( math.sin )\n >>> print 'sin2(x) = %s ' % sin2(x)\n \"\"\"\n #\n ## evaluate the function \n val = self._value_ ( x , *args )\n #\n ## no uncertainties? \n if isinstance ( x , ( float , int , long ) ) : return VE ( val , 0 )\n # ignore small or invalid uncertanties \n elif 0 >= x.cov2() or iszero ( x.cov2() ) : return VE ( val , 0 )\n # evaluate the derivative \n d = self._deriv ( float ( x ) , *args )\n ## calculate the variance \n cov2 = d * d * x.cov2()\n ## get a final result \n return VE ( val , cov2 )\n \n# ===================================================================================\n## @class Eval2VE\n# Evaluate the 2-argument function taking into account the uncertaintines\n# @code\n# func2 = lambda x,y : x*x + y*y\n# eval2 = Eval2VE ( func2 )\n# x = VE(1,0.1**2)\n# y = VE(2,0.1**2)\n# print eval2(x,y) ## treat x,y as uncorrelated \n# print eval2(x,y, 0) ## ditto \n# print eval2(x,y,+1) ## treat x,y as 100% correlated \n# print eval2(x,y,-1) ## treat x,y as 100% anti-correlated\n# @endcode\n# Partial derivatives can be provided explictely:\n# @code\n# func2 = lambda x,y : x*x + y*y\n# eval2 = Eval2VE ( func2 , dFdX = lambda x,y : 2*x , dFdY = lambda x,y : 2*y ) \n# @endcode\n# If derivatves are not provided, numerical differentiation will be used \n# @see EvalVE\n# @author Vanya BELYAEV Ivan.Belyaev@itep.ru\n# @date 2016-02-23\nclass Eval2VE(object) :\n \"\"\" Evaluate the 2-argument function taking into account the uncertaintines\n >>> func2 = lambda x,y : x*x + y*y\n >>> eval2 = Eval2VE ( func2 )\n >>> x = VE(1,0.1**2)\n >>> y = VE(2,0.1**2)\n >>> print eval2(x,y) ## treat x,y as uncorrelated \n >>> print eval2(x,y, 0) ## ditto \n >>> print eval2(x,y,+1) ## treat x,y as 100% correlated \n >>> print eval2(x,y,-1) ## treat x,y as 100% anti-correlated\n Partial derivatives can be provided explictely:\n >>> func2 = lambda x,y : x*x + y*y\n >>> eval2 = Eval2VE ( func2 , dFdX = lambda x,y : 2*x , dFdY = lambda x,y : 2*y )\n If derivatves are not provided, numerical differentiation will be used \n \"\"\"\n ## constructor\n # @param func the 2-argument function\n # @param dFdX (optional) the partial derivative d(dunc)/dX\n # @param dFdY (optional) the partial derivative d(dunc)/dY\n # @param name (optional) the function name \n def __init__ ( self , func , dFdX = None , dFdY = None , name = '' ) :\n \"\"\" Constructor from the function, optional partial derivative and name\n >>> func2 = lambda x,y : x*x + y*y\n >>> eval2 = Eval2VE ( func2 )\n >>> x = VE(1,0.1**2)\n >>> y = VE(2,0.1**2)\n >>> print eval2(x,y) ## treat x,y as uncorrelated \n >>> print eval2(x,y, 0) ## ditto \n >>> print eval2(x,y,+1) ## treat x,y as 100% correlated \n >>> print eval2(x,y,-1) ## treat x,y as 100% anti-correlated\n Partial derivatives can be provided explictely:\n >>> func2 = lambda x,y : x*x + y*y\n >>> eval2 = Eval2VE ( func2 , dFdX = lambda x,y : 2*x , dFdY = lambda x,y : 2*y )\n If derivatves are not provided, numerical differentiation will be used \n \"\"\"\n self._func = func\n \n self._dFdX = dFdX if dFdX else Partial ( 0 , func )\n self._dFdY = dFdY if dFdY else Partial ( 1 , func )\n\n if not hasattr ( self._dFdX , '_step' ) : self._dFdX._step = 0 \n if not hasattr ( self._dFdY , '_step' ) : self._dFdY._step = 0 \n \n if name : self.__name__ = name \n elif hasattr ( func , '__name__' ) and '' != func.__name__ :\n self.__name__ = func.__name__\n else : self.__name__ = 'Eval2VE'\n\n ## printout \n def __str__ ( self ) : return str ( self.__name__ )\n __repr__ = __str__\n \n # =========================================================================\n ## get a value \n def _value_ ( self , x , y ) :\n \"\"\"Evaluate a function\"\"\"\n return self._func( float ( x ) , float(y) )\n \n # =========================================================================\n ## get a partial derivatives,\n # adjust the step for numerical differentiation: use the initial value of 0.1*error\n def _partial_ ( self , f , x , y , step2 ) :\n \"\"\" get a partial derivatives,\n adjust the step for numerical differentiation:\n - use the initial value of 0.1*error\n \"\"\"\n \n old_step = f._step\n ## magic number choice: 1.e-8 <= ( step ~ 0.1 * error ) \n if 1.e-14 <= step2 :\n from math import sqrt as _sqrt_ \n f._step = 0.1 * _sqrt_( step2 ) \n _r = f ( x , y )\n f._step = old_step\n return _r \n \n ## get a partial derivatives d(func)/d(x)\n def dFdX ( self , x , y ) :\n \"\"\"Get a partial derivatives d(func)/d(X)\"\"\"\n x = VE ( x )\n return self._partial_ ( self._dFdX , x.value() , y , x.cov2() )\n \n ## get a partial derivatives d(func)/d(y)\n def dFdY ( self , x , y ) :\n \"\"\"Get a partial derivatives d(func)/d(Y)\"\"\"\n y = VE ( y )\n return self._partial_ ( self._dFdY , x , y.value() , y.cov2() )\n\n # =========================================================================\n ## evaluate the function \n # @code\n # func2 = lambda x,y : x*x + y*y\n # eval2 = Eval2VE ( func2 )\n # x = VE(1,0.1**2)\n # y = VE(2,0.1**2)\n # print eval2(x,y) ## treat x,y as uncorrelated \n # print eval2(x,y, 0) ## ditto \n # print eval2(x,y,+1) ## treat x,y as 100% correlated \n # print eval2(x,y,-1) ## treat x,y as 100% anti-correlated\n # @endcode\n def __call__ ( self , x , y , cxy = 0 ) :\n \"\"\"Evaluate the function \n >>> func2 = lambda x,y : x*x + y*y\n >>> eval2 = Eval2VE ( func2 )\n >>> x = VE(1,0.1**2)\n >>> y = VE(2,0.1**2)\n >>> print eval2(x,y) ## treat x,y as uncorrelated \n >>> print eval2(x,y, 0) ## ditto \n >>> print eval2(x,y,+1) ## treat x,y as 100% correlated \n >>> print eval2(x,y,-1) ## treat x,y as 100% anti-correlated\n \"\"\"\n ## evaluate the function \n val = self._value_ ( x , y )\n #\n x = VE ( x )\n y = VE ( y )\n #\n x_plain = x.cov2() <= 0 or iszero ( x.cov2() )\n y_plain = y.cov2() <= 0 or iszero ( y.cov2() ) \n #\n if x_plain and y_plain : return VE ( val , 0 )\n #\n ## here we need to calculate the uncertainties\n # \n cov2 = 0.0\n #\n fx = self.dFdX ( x , y.value() ) if not x_plain else 0 \n fy = self.dFdY ( x.value() , y ) if not y_plain else 0 \n #\n if not x_plain : cov2 += fx * fx * x.cov2() \n if not y_plain : cov2 += fy * fy * y.cov2()\n # \n if not x_plain and not y_plain : \n ## adjust the correlation coefficient:\n cxy = min ( max ( -1 , cxy ) , 1 )\n if not iszero ( cxy ) :\n cov2 += 2 * cxy * fx * fy * x.error() * y.error() \n\n return VE ( val , cov2 )\n \n\n# =============================================================================\nif '__main__' == __name__ :\n \n from ostap.utils.docme import docme\n docme ( __name__ , logger = logger )\n\n import math\n\n functions = [\n ( lambda x : math.cos(100.*x) , lambda x : -100*math.sin(100.*x) , 0 ) , \n ( lambda x : x**3 , lambda x : 3.0*x*x , 1 ) , \n ( lambda x : math.exp(x) , lambda x : math.exp(x) , 5 ) ,\n ( lambda x : x**8 , lambda x : 8.0*x**7 , 2.2 ) ,\n ( lambda x : math.tanh(10.*x) , lambda x : 10*(1.-math.tanh(10.*x)**2) , 0.1 ) ,\n ( lambda x : math.tan (10.*x) , lambda x : 10*(1.+math.tan (10.*x)**2) , 2.1 ) ,\n ( lambda x : 1./math.sin(2.*x) , lambda x : -2./math.sin(2.*x)**2*math.cos(2.*x) , 0.2 ) , \n ( lambda x : 1.11*x , lambda x : 1.11 , 0.4 ) , \n ( lambda x : 1000./x**2 , lambda x : -2000./x**3 , 0.8 ) , \n ( lambda x : 1.11111 , lambda x : 0.0 , 0.6 ) , \n ( lambda x : x**50 , lambda x : 50.*x**49 , 1.3 ) , \n ]\n\n\n for o in functions :\n\n fun = o[0] ## function \n der = o[1] ## derivative \n x = o[2] ## argument \n \n logger.info ( 80*'*' ) \n \n for i in range(1,6 ) :\n \n res = derivative ( fun , x , 1.e-20 , i , err = True )\n f1 = res \n d = der(x) ## the exact value for derivative \n if iszero ( d ) : \n logger.info ( 'Rule=%2d %s %s %s' % ( 2*i+1 , f1 , d , (f1.value()-d) ) ) \n else :\n logger.info ( 'Rule=%2d %s %s %s' % ( 2*i+1 , f1 , d , (f1.value()-d)/d ) ) \n \n logger.info ( 80*'*' ) \n\n ## the function \n func = math.sin\n ## analysitical derivative \n deriv_a = math.cos\n ## numerical first derivative \n deriv_1 = Derivative ( func , order = 5 ) \n ## numerical second derivative \n deriv_2 = Derivative ( deriv_1 , order = 5 ) \n\n import random\n\n for i in range ( 0 , 20 ) : \n\n x = random.uniform( 0 , 0.5*math.pi )\n \n fmt = \"x=%10.5g f=%10.5g delta(f')= %+10.4g delta(f\\\")= %+10.4g \"\n logger.info ( fmt % ( x ,\n func(x) ,\n 1-deriv_1(x)/deriv_a(x) ,\n 1+deriv_2(x)/func (x) ) ) \n \n logger.info ( 80*'*' ) \n\n ## the function\n func2 = lambda x,y : x*x + y*y\n \n ## use explicit partial derivatives \n eval2_1 = Eval2VE( func2 , dFdX = lambda x,y : 2*x , dFdY = lambda x,y : 2*y )\n \n ## use numerical partial derivatives \n eval2_2 = Eval2VE( func2 )\n\n for x,y in [ (0,0) , (1,1) , (1,2) , (2,2) ] :\n\n x = VE(x,0.1**2)\n y = VE(x,0.1**2)\n \n logger.info ( 'x=%-17s, y=%-17s' % ( x , y ) )\n \n logger.info ( ' eval2_1(x,y)= %-17s eval2_3(x,y)= %-17s ' % ( eval2_1 ( x, y ) ,\n eval2_2 ( x, y ) ) )\n ## use correlation coefficient:\n for c in (0,-1,1) :\n logger.info ( ' eval2_1(x,y,%+2d)=%-17s eval2_3(x,y,%+2d)=%-17s ' % ( c , eval2_1 ( x, y ) ,\n c , eval2_2 ( x, y ) ) ) \n logger.info ( 80*'*' ) \n \n# =============================================================================\n# The END \n# =============================================================================\n","sub_path":"ostap/math/derivative.py","file_name":"derivative.py","file_ext":"py","file_size_in_byte":37434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"497112296","text":"import argparse\nimport os\n\nfrom calamari_ocr import __version__\nfrom calamari_ocr.utils import glob_all, split_all_ext, keep_files_with_same_file_name\nfrom calamari_ocr.ocr.datasets import create_dataset, DataSetType, DataSetMode\nfrom calamari_ocr.ocr.augmentation.data_augmenter import SimpleDataAugmenter\nfrom calamari_ocr.ocr import Trainer\nfrom calamari_ocr.ocr.text_processing import \\\n default_text_normalizer_params, default_text_regularizer_params\n\nfrom calamari_ocr.proto import CheckpointParams, DataPreprocessorParams, TextProcessorParams, \\\n network_params_from_definition_string, NetworkParams, TextGeneratorParameters, LineGeneratorParameters\n\nfrom google.protobuf import json_format\n\nfrom calamari_ocr.proto.config import get_cfg\nfrom yacs.config import CfgNode\nfrom typing import List, Union\nfrom calamari_ocr.ocr.datasets import RawDataSet\nfrom calamari_ocr.ocr.datasets import FileDataSet\nfrom calamari_ocr.ocr.datasets import AbbyyDataSet\nfrom calamari_ocr.ocr.datasets import PageXMLDataset\nfrom calamari_ocr.ocr.datasets.hdf5_dataset import Hdf5DataSet\nfrom calamari_ocr.ocr.datasets.extended_prediction_dataset import ExtendedPredictionDataSet\nfrom calamari_ocr.ocr.datasets.generated_line_dataset import GeneratedLineDataset\nfrom calamari_ocr.utils import dataregistry\n\n\ndef create_train_dataset(cfg: CfgNode, dataset_args=None):\n gt_extension = cfg.DATASET.TRAIN.GT_EXTENSION if cfg.DATASET.TRAIN.GT_EXTENSION is not False else DataSetType.gt_extension(cfg.DATASET.TRAIN.TYPE)\n\n # Training dataset\n print(\"Resolving input files\")\n input_image_files = sorted(glob_all(cfg.DATASET.TRAIN.PATH))\n if not cfg.DATASET.TRAIN.TEXT_FILES:\n if gt_extension:\n gt_txt_files = [split_all_ext(f)[0] + gt_extension for f in input_image_files]\n else:\n gt_txt_files = [None] * len(input_image_files)\n else:\n gt_txt_files = sorted(glob_all(cfg.DATASET.TRAIN.TEXT_FILES))\n input_image_files, gt_txt_files = keep_files_with_same_file_name(input_image_files, gt_txt_files)\n for img, gt in zip(input_image_files, gt_txt_files):\n if split_all_ext(os.path.basename(img))[0] != split_all_ext(os.path.basename(gt))[0]:\n raise Exception(\"Expected identical basenames of file: {} and {}\".format(img, gt))\n\n if len(set(gt_txt_files)) != len(gt_txt_files):\n raise Exception(\"Some image are occurring more than once in the data set.\")\n\n dataset = create_dataset(\n cfg.DATASET.TRAIN.TYPE,\n DataSetMode.TRAIN,\n images=input_image_files,\n texts=gt_txt_files,\n skip_invalid=not cfg.DATALOADER.NO_SKIP_INVALID_GT,\n args=dataset_args if dataset_args else {},\n )\n print(\"Found {} files in the dataset\".format(len(dataset)))\n return dataset\n\n\ndef create_test_dataset(cfg: CfgNode,\n dataset_args=None) -> Union[List[\n Union[RawDataSet, FileDataSet,\n AbbyyDataSet, PageXMLDataset,\n Hdf5DataSet, ExtendedPredictionDataSet,\n GeneratedLineDataset]], None]:\n if cfg.DATASET.VALID.TEXT_FILES:\n assert len(cfg.DATASET.VALID.PATH) == len(cfg.DATASET.VALID.TEXT_FILES)\n\n if cfg.DATASET.VALID.PATH:\n validation_dataset_list = []\n print(\"Resolving validation files\")\n for i, valid_path in enumerate(cfg.DATASET.VALID.PATH):\n validation_image_files = glob_all(valid_path)\n dataregistry.register(i,\n os.path.basename(os.path.dirname(valid_path)),\n len(validation_image_files))\n\n if not cfg.DATASET.VALID.TEXT_FILES:\n val_txt_files = [split_all_ext(f)[0] + cfg.DATASET.VALID.GT_EXTENSION for f in validation_image_files]\n else:\n val_txt_files = sorted(glob_all(cfg.DATASET.VALID.TEXT_FILES[i]))\n validation_image_files, val_txt_files = keep_files_with_same_file_name(validation_image_files, val_txt_files)\n for img, gt in zip(validation_image_files, val_txt_files):\n if split_all_ext(os.path.basename(img))[0] != split_all_ext(os.path.basename(gt))[0]:\n raise Exception(\"Expected identical basenames of validation file: {} and {}\".format(img, gt))\n\n if len(set(val_txt_files)) != len(val_txt_files):\n raise Exception(\"Some validation images are occurring more than once in the data set.\")\n\n validation_dataset = create_dataset(\n cfg.DATASET.VALID.TYPE,\n DataSetMode.TRAIN,\n images=validation_image_files,\n texts=val_txt_files,\n skip_invalid=not cfg.DATALOADER.NO_SKIP_INVALID_GT,\n args=dataset_args,\n )\n print(\"Found {} files in the validation dataset\".format(len(validation_dataset)))\n validation_dataset_list.append(validation_dataset)\n else:\n validation_dataset_list = None\n\n return validation_dataset_list\n\ndef run(cfg: CfgNode):\n\n # check if loading a json file\n if len(cfg.DATASET.TRAIN.PATH) == 1 and cfg.DATASET.TRAIN.PATH[0].endswith(\"json\"):\n import json\n with open(cfg.DATASET.TRAIN.PATH[0], 'r') as f:\n json_args = json.load(f)\n for key, value in json_args.items():\n if key == 'dataset' or key == 'validation_dataset':\n setattr(cfg, key, DataSetType.from_string(value))\n else:\n setattr(cfg, key, value)\n\n # parse whitelist\n whitelist = cfg.MODEL.CODEX.WHITELIST\n if len(whitelist) == 1:\n whitelist = list(whitelist[0])\n\n whitelist_files = glob_all(cfg.MODEL.CODEX.WHITELIST_FILES)\n for f in whitelist_files:\n with open(f) as txt:\n whitelist += list(txt.read())\n\n if cfg.DATASET.TRAIN.GT_EXTENSION is False:\n cfg.DATASET.TRAIN.GT_EXTENSION = DataSetType.gt_extension(cfg.DATASET.TRAIN.TYPE)\n\n if cfg.DATASET.VALID.GT_EXTENSION is False:\n cfg.DATASET.VALID.GT_EXTENSION = DataSetType.gt_extension(cfg.DATASET.VALID.TYPE)\n\n\n text_generator_params = TextGeneratorParameters()\n\n line_generator_params = LineGeneratorParameters()\n\n dataset_args = {\n 'line_generator_params': line_generator_params,\n 'text_generator_params': text_generator_params,\n 'pad': None,\n 'text_index': 0,\n }\n\n # Training dataset\n dataset = create_train_dataset(cfg, dataset_args)\n\n # Validation dataset\n validation_dataset_list = create_test_dataset(cfg, dataset_args)\n\n params = CheckpointParams()\n\n params.max_iters = cfg.SOLVER.MAX_ITER\n params.stats_size = cfg.STATS_SIZE\n params.batch_size = cfg.SOLVER.BATCH_SIZE\n params.checkpoint_frequency = cfg.SOLVER.CHECKPOINT_FREQ if cfg.SOLVER.CHECKPOINT_FREQ >= 0 else cfg.SOLVER.EARLY_STOPPING_FREQ\n params.output_dir = cfg.OUTPUT_DIR\n params.output_model_prefix = cfg.OUTPUT_MODEL_PREFIX\n params.display = cfg.DISPLAY\n params.skip_invalid_gt = not cfg.DATALOADER.NO_SKIP_INVALID_GT\n params.processes = cfg.NUM_THREADS\n params.data_aug_retrain_on_original = not cfg.DATALOADER.ONLY_TRAIN_ON_AUGMENTED\n\n params.early_stopping_at_acc = cfg.SOLVER.EARLY_STOPPING_AT_ACC\n params.early_stopping_frequency = cfg.SOLVER.EARLY_STOPPING_FREQ\n params.early_stopping_nbest = cfg.SOLVER.EARLY_STOPPING_NBEST\n params.early_stopping_best_model_prefix = cfg.EARLY_STOPPING_BEST_MODEL_PREFIX\n params.early_stopping_best_model_output_dir = \\\n cfg.EARLY_STOPPING_BEST_MODEL_OUTPUT_DIR if cfg.EARLY_STOPPING_BEST_MODEL_OUTPUT_DIR else cfg.OUTPUT_DIR\n\n if cfg.INPUT.DATA_PREPROCESSING is False or len(cfg.INPUT.DATA_PREPROCESSING) == 0:\n cfg.INPUT.DATA_PREPROCESSING = [DataPreprocessorParams.DEFAULT_NORMALIZER]\n\n params.model.data_preprocessor.type = DataPreprocessorParams.MULTI_NORMALIZER\n for preproc in cfg.INPUT.DATA_PREPROCESSING:\n pp = params.model.data_preprocessor.children.add()\n pp.type = DataPreprocessorParams.Type.Value(preproc) if isinstance(preproc, str) else preproc\n pp.line_height = cfg.INPUT.LINE_HEIGHT\n pp.pad = cfg.INPUT.PAD\n\n # Text pre processing (reading)\n params.model.text_preprocessor.type = TextProcessorParams.MULTI_NORMALIZER\n default_text_normalizer_params(params.model.text_preprocessor.children.add(), default=cfg.INPUT.TEXT_NORMALIZATION)\n default_text_regularizer_params(params.model.text_preprocessor.children.add(), groups=cfg.INPUT.TEXT_REGULARIZATION)\n strip_processor_params = params.model.text_preprocessor.children.add()\n strip_processor_params.type = TextProcessorParams.STRIP_NORMALIZER\n\n # Text post processing (prediction)\n params.model.text_postprocessor.type = TextProcessorParams.MULTI_NORMALIZER\n default_text_normalizer_params(params.model.text_postprocessor.children.add(), default=cfg.INPUT.TEXT_NORMALIZATION)\n default_text_regularizer_params(params.model.text_postprocessor.children.add(), groups=cfg.INPUT.TEXT_REGULARIZATION)\n strip_processor_params = params.model.text_postprocessor.children.add()\n strip_processor_params.type = TextProcessorParams.STRIP_NORMALIZER\n\n if cfg.SEED > 0:\n params.model.network.backend.random_seed = cfg.SEED\n\n if cfg.INPUT.BIDI_DIR:\n # change bidirectional text direction if desired\n bidi_dir_to_enum = {\"rtl\": TextProcessorParams.BIDI_RTL, \"ltr\": TextProcessorParams.BIDI_LTR,\n \"auto\": TextProcessorParams.BIDI_AUTO}\n\n bidi_processor_params = params.model.text_preprocessor.children.add()\n bidi_processor_params.type = TextProcessorParams.BIDI_NORMALIZER\n bidi_processor_params.bidi_direction = bidi_dir_to_enum[cfg.INPUT.BIDI_DIR]\n\n bidi_processor_params = params.model.text_postprocessor.children.add()\n bidi_processor_params.type = TextProcessorParams.BIDI_NORMALIZER\n bidi_processor_params.bidi_direction = TextProcessorParams.BIDI_AUTO\n\n params.model.line_height = cfg.INPUT.LINE_HEIGHT\n params.model.network.learning_rate = cfg.SOLVER.LR\n params.model.network.lr_decay = cfg.SOLVER.LR_DECAY\n params.model.network.lr_decay_freq = cfg.SOLVER.LR_DECAY_FREQ\n params.model.network.train_last_n_layer = cfg.SOLVER.TRAIN_LAST_N_LAYER\n network_params_from_definition_string(cfg.MODEL.NETWORK, params.model.network)\n params.model.network.clipping_norm = cfg.SOLVER.GRADIENT_CLIPPING_NORM\n params.model.network.backend.num_inter_threads = 0\n params.model.network.backend.num_intra_threads = 0\n params.model.network.backend.shuffle_buffer_size = cfg.DATALOADER.SHUFFLE_BUFFER_SIZE\n\n if cfg.MODEL.WEIGHTS == \"\":\n weights = None\n else:\n weights = cfg.MODEL.WEIGHTS\n\n # create the actual trainer\n trainer = Trainer(params,\n dataset,\n validation_dataset=validation_dataset_list,\n data_augmenter=SimpleDataAugmenter(),\n n_augmentations=cfg.INPUT.N_AUGMENT,\n weights=weights,\n codec_whitelist=whitelist,\n keep_loaded_codec=cfg.MODEL.CODEX.KEEP_LOADED_CODEC,\n preload_training=not cfg.DATALOADER.TRAIN_ON_THE_FLY,\n preload_validation=not cfg.DATALOADER.VALID_ON_THE_FLY,\n )\n trainer.train(\n auto_compute_codec=not cfg.MODEL.CODEX.SEE_WHITELIST,\n progress_bar=not cfg.NO_PROGRESS_BAR\n )\n\n\nif __name__ == \"__main__\":\n import sys\n cfg_path = sys.argv[1]\n cfg = get_cfg()\n cfg.merge_from_file(cfg_path)\n run(cfg)\n","sub_path":"calamari_ocr/scripts/train_cfg.py","file_name":"train_cfg.py","file_ext":"py","file_size_in_byte":11840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"581800010","text":"from hpbandster.core.worker import Worker\nfrom ConfigSpace.read_and_write import pcs_new\nimport grpc\nimport json\nimport math\nimport os, sys, inspect\nimport PCSBasedComponentParameter_pb2\nimport PCSBasedComponentParameter_pb2_grpc\n\n\nclass MyWorker(Worker):\n component = ''\n\n def __init__(self, *args, sleep_interval=0, gRPC_port, **kwargs):\n super().__init__(*args, **kwargs)\n self.gRPC_port = gRPC_port\n\n def compute(self, config, budget, **kwargs):\n \"\"\"\n Simple example for a compute function\n The loss is just a the config + some noise (that decreases with the budget)\n\n For dramatization, the function can sleep for a given interval to emphasizes\n the speed ups achievable with parallel workers.\n\n Args:\n config: dictionary containing the sampled configurations by the optimizer\n budget: (float) amount of time/epochs/etc. the model can use to train\n\n Returns:\n dictionary with mandatory fields:\n 'loss' (scalar)\n 'info' (dict)\n \"\"\"\n \n with open(\"worker.log\", \"a\") as file:\n file.write(\"Budget \" + str(budget)+\"\\n\")\n\n params = []\n for k, v in config.items():\n params.append(PCSBasedComponentParameter_pb2.PCSBasedParameterProto(key=k, value=str(v)))\n cmp = PCSBasedComponentParameter_pb2.PCSBasedComponentProto(name=str(math.ceil(budget/1000)), parameters=params)\n\n channel = grpc.insecure_channel(\"localhost:\" + str(self.gRPC_port))\n stub = PCSBasedComponentParameter_pb2_grpc.PCSBasedOptimizerServiceStub(channel)\n\n\n response = stub.Evaluate(cmp)\n channel.close()\n\n if(response.result < 0):\n return( {'loss': float(10000), 'info': 'crashed'})\n else:\n return ({'loss': float(response.result), 'info': 'succeeded'})\n\n @staticmethod\n def get_configspace():\n with open('searchspace.pcs', 'r') as fh:\n cs = pcs_new.read(fh)\n return cs\n","sub_path":"resources/hb/evalworker.py","file_name":"evalworker.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"100624414","text":"# 2665 Экспедиция\nq=[int(i) for i in input().split()]\nmass=[]\nfor i in range(q[0]):\n n=[int(j) for j in input().split()]\n mass.append(n)\nc=int(input())\nmemb=[int(i) for i in input().split()]\nour_mass=[]\nfor i in range(q[0]):\n our_mass+=mass[i]\nour_mass.sort()\nmemb.sort()\nk=0\nc=0\nfor j in range(len(our_mass)):\n while c=memb[j]:\n k+=1\n c+=1\n break\n c+=1\n\nprint(k)\n","sub_path":"2000-2999/2665.py","file_name":"2665.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"460142142","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author:owefsad\n# software: PyCharm\n# project: lingzhi-webapi\nfrom dongtai.models.hook_type import HookType\nfrom dongtai.models.hook_strategy import HookStrategy\nfrom dongtai.utils import const\n\nfrom dongtai.endpoint import R\nfrom dongtai.endpoint import TalentAdminEndPoint\nfrom django.utils.translation import gettext_lazy as _\nfrom iast.utils import extend_schema_with_envcheck, get_response_serializer\n\n_ResponseSerializer = get_response_serializer(status_msg_keypair=(\n ((201, _('Strategy is disabled, total {} hook rules')), ''),\n ((202, _('Strategy does not exist')), ''),\n))\n\n\nclass StrategyDisableEndpoint(TalentAdminEndPoint):\n @extend_schema_with_envcheck(\n tags=[_('Strategy')],\n summary=_('Strategy Disable'),\n description=_(\n \"Disable the corresponding strategy according to id\"\n ),\n response_schema=_ResponseSerializer,\n )\n def get(self, request, id):\n strategy_model = HookType.objects.filter(id=id).first()\n if strategy_model:\n counts = strategy_model.strategies.filter(enable=const.HOOK_TYPE_ENABLE).update(\n enable=const.HOOK_TYPE_DISABLE)\n strategy_model.enable = const.HOOK_TYPE_DISABLE\n strategy_model.save(update_fields=['enable'])\n\n return R.success(msg=_('Strategy is disabled, total {} hook rules').format(counts))\n else:\n return R.failure(status=202, msg=_('Strategy does not exist'))\n\n\nif __name__ == '__main__':\n \n HookStrategy.objects.values(\"id\").count()\n","sub_path":"iast/views/strategy_disable.py","file_name":"strategy_disable.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"406333477","text":"\"\"\"Sample scoring script.\"\"\"\n\nimport argparse\nimport json\n\n\ndef get_args():\n \"\"\"Suggested command-line arguments.\n\n You may add additional ones if they are needed.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-g\", \"--goldstandard\", required=True,\n help=\"Goldstandard for scoring\")\n parser.add_argument(\"-s\", \"--submission_file\", required=True,\n help=\"Submission file\")\n parser.add_argument(\"-r\", \"--results\", required=True,\n help=\"Scores output file\")\n\n return parser.parse_args()\n\n\ndef main():\n \"\"\"Main function.\"\"\"\n args = get_args()\n\n with open(args.submission_file, \"r\") as sub_file, \\\n open(args.goldstandard, \"r\") as gold_file:\n pred = sub_file.read()\n gold = gold_file.read()\n\n ## Sample scoring ##\n score1 = 0.8\n score2 = 0.2\n prediction_file_status = \"SCORED\"\n\n # secondary_metric and secondary_metric_value are optional\n result = {'primary_metric': \"auc\",\n 'primary_metric_value': score1,\n 'secondary_metric': \"aupr\",\n 'secondary_metric_value': score2,\n 'submission_status': prediction_file_status}\n with open(args.results, \"w\") as o:\n o.write(json.dumps(result))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"31109586","text":"\"\"\"website 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.conf.urls import url\nfrom django.contrib import admin\nfrom django.urls import path, include, re_path\nfrom django.views.static import serve\n\nfrom rest_framework_jwt.views import obtain_jwt_token\n\nfrom apps.user.views import test, captcha_refresh, yan, login_view, UserGetInfo, UserGetAllInfo, UserDisbale, \\\n PersonOthers, Register, active_user\nfrom django.views.generic import TemplateView\n\nfrom website import settings\nfrom apps.article import views\nfrom apps.user.views import logout_view,Person,PersonApi\nfrom rest_framework import routers\n\nrouter = routers.DefaultRouter()\nrouter.register('article_list', views.ArticleListView)\nrouter.register('follow_list', views.FollowListView)\nrouter.register('category', views.CategoryView)\nrouter.register('article_Comment', views.ArticleCommintView)\nrouter.register('comment_reply', views.ArticleCommentReplyView)\nrouter.register('PersonApi', PersonApi)\nrouter.register('info', UserGetInfo)\nrouter.register('all_info', UserGetAllInfo)\nrouter.register('user_disbale', UserDisbale)\nrouter.register('PersonOthers', PersonOthers)\n\n\n\nurlpatterns = [\n\n path('admin/', admin.site.urls),\n #path('',test), # 这是生成验证码的图片\n url(r'^captcha/', include('captcha.urls')),\n path('refresh/',captcha_refresh), # 这是生成验证码的图片\n path('yan/',yan), # 这是生成验证码的图片\n path('',views.Article_list,name='home'),\n path('login/',login_view,name='index'),\n path('person/',include('apps.user.urls')),\n path('logou/',logout_view,name='logou'),\n path('register/',Register.as_view(),name='register'),\n path('article/',include('apps.article.urls')),\n path('course/',include('apps.course.urls')),\n path('support/',include('apps.support.urls')),\n url(r'^activate/(?P\\w+.[-_\\w]*\\w+.[-_\\w]*\\w+)/$',active_user,name='active_user'),\n url(r'^search/', include('haystack.urls'),name='haystack_search'),\n\n\n re_path(r'^upload/(?P.*)$', serve, {'document_root': settings.MEDIA_ROOT}),\n url(r'api/', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n re_path(r'api/login/$', obtain_jwt_token),#jwt认证\n #re_path(r'^static/(?P.*)$', serve, {'document_root': settings.STATI_ROOT}) # 配置文件上传html显示\n]\n","sub_path":"website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"188892966","text":"# Search Matrix Helper for Math 300 Project\r\n# Rachel J. Morris, January 2013\r\n# zlib license\r\n#\r\n# Reads in the file of words.\r\n# Enter your search terms, it will tell you how to change your search array.\r\n\r\nimport sys\r\n\r\nfileWords = open( 'words.txt', 'r' )\r\nlstWords = []\r\n\t\r\nfor line in fileWords:\r\n\tsanitizedLine = line.replace( \"\\n\", \"\" )\r\n\tsanitizedLine = sanitizedLine.replace( \"\\t\", \"\" )\r\n\tsanitizedLine = sanitizedLine.replace( \"'\", \"\" )\r\n\tsanitizedLine = sanitizedLine.replace( \"&\", \"\" )\r\n\t\r\n\tif ( sanitizedLine != '' and sanitizedLine != ' ' ):\r\n\t\tlstWords.append( sanitizedLine.lower() )\r\n\t\r\nfileWords.close()\r\n\r\ndone = False\r\n\r\nwhile ( not done ):\r\n\tsearch = raw_input( \"Enter your search term(s), or \\\"QUIT\\\" to stop: \" )\r\n\t\r\n\tif ( search.lower().find( \"quit\" ) != -1 ):\r\n\t\tdone = True\r\n\telse:\r\n\t\t\r\n\t\tsearch = search.lower()\r\n\t\tterms = search.split( \" \" )\r\n\r\n\t\tindices = []\r\n\t\tfor term in terms:\r\n\t\t\tfor word in lstWords:\r\n\t\t\t\tif ( term.find( word ) != -1 ):\r\n\t\t\t\t\t# We have to account for indices starting at \"1\" and not \"0\"\r\n\t\t\t\t\t# when moved over to MatLab!\r\n\t\t\t\t\tindices.append( lstWords.index( word ) + 1 )\r\n\t\t\r\n\t\tprint( \"\" )\r\n\t\tprint( \"------------------\" )\r\n\t\tprint( \" RESULT\" )\r\n\t\tprint( \"------------------\" )\r\n\t\tprint( \"Here are the commands to run on the search matrix: \" )\r\n\t\t\r\n\t\tfor i in indices:\r\n\t\t\tprint( \"X(\" + str( i ) + \",1)=1;\" )\r\n\t\t\t\r\n\t\tprint( \"\" )\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n","sub_path":"UMKC_Math300_LinearAlgebra/Search Data Helper/search matrix helper.py","file_name":"search matrix helper.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"347775887","text":" \r\n'''\r\nGiven an array, rotate the array to the right by k steps, k is non-negative.\r\nTry to optimize the time complexity.\r\ninput: [1,2,3,4,5], k=2\r\noutput: [4,5,1,2,3]\r\ninput: [0,1,2,3,4], k=1\r\noutput: [4,0,1,2,3]\r\n'''\r\n\r\ndef rotation(k):\r\n arr = [int(x) for x in input().split(',')]\r\n result = [0] * len(arr)\r\n for i in range(len(arr)):\r\n if i+k < len(arr):\r\n result[i+k] = arr[i]\r\n else:\r\n new_index = (i+k) % len(arr)\r\n result[new_index] = arr[i]\r\n return result\r\n\r\nk = int(input())\r\nprint(rotation(k))","sub_path":"19_array_rotation.py","file_name":"19_array_rotation.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"351086246","text":"\n# for 2-label model\n# read bounding box details from txt files and extract CMP details \n\n\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt\nimport os \nimport glob\nimport tkinter as tk\nfrom tkinter import filedialog\nimport datetime\nfrom scipy import signal\nimport statistics \nfrom statistics import mode\nfrom matplotlib import ticker, cm\nfrom matplotlib.widgets import Slider, Button, RadioButtons\nimport peakutils # for background estimation\nimport math\nfrom sklearn import preprocessing\n\nimport csv\nimport seaborn as sns; sns.set(style=\"white\", color_codes=True)\nimport statistics\n\n\ndef events_stats(stats_dir):\n \n # set working dir where plots will be saved\n DataPath = stats_dir\n \n length_of_image = 10 # at the moment each image is 10 minutes long \n files = sorted(glob.glob(DataPath))\n \n dict_results = {}\n \n plt.ion()\n counter = 0\n for file in files: \n \n counter +=1\n print('\\n')\n print(f'Processing file number %s' % counter)\n #print(counter)\n print(f'Counter %s ' % counter)\n \n # read in each txt file\n txt0 = pd.read_csv(file, header=None, delimiter=\"\\s+\") \n txt1 = txt0.rename(columns={0: 'class', 1: 'confidence', 2: 'x', 3: 'y', 4: 'width', 5: 'height'}) # rename the columns\n class_names = ['HAPC', 'cyclic'] # class assignements - colab doc\n txt1['class'] = txt1['class'].replace([0, 1], class_names) # update class col with class names\n \n \n class0 = txt1['class'] # the list of classes - 1st column of txt file\n set_class = set(class0) # list of unique classes \n \n \n \n # create a dictionary for the results\n results = {}\n \n # get stats on each class separtately \n for object_class in set_class:\n \n \n # dictionary of results per class\n class_results = {} \n \n \n print(f'class: %s' % object_class)\n \n txt2 = txt1[txt1['class'].isin([object_class])] # new df with only current class\n \n # total number of events\n num_events = len(txt2) # total number of events of current class\n print(f'There are %s %s events ' %(num_events, object_class))\n \n # raw freq\n raw_freq = num_events/length_of_image\n print(f'Uncorrected frequency: %.2f per minute ' %(raw_freq))\n \n\n \n \n # duration of events (s) \n ave_dur = txt2['width'].mean()*length_of_image*60 # average duration of an event in seconds\n min_dur = txt2['width'].min()*length_of_image*60 # min duration of an event in seconds\n max_dur = txt2['width'].max()*length_of_image*60 # max duration of an event in seconds \n print(f'Average duration is %.2f s (max = %.2f s and min = %.2f s)' %(ave_dur, min_dur, max_dur)) \n \n # extent of events (cm)\n ave_extent = txt2['height'].mean()*100 # average duration of an event in seconds\n min_extent = txt2['height'].min()*100 # min duration of an event in seconds\n max_extent = txt2['height'].max()*100 # max duration of an event in seconds\n print(f'Average length of colon affected is %.2f cm (max = %.2f cm and min = %.2f cm)' %(ave_extent, min_extent, max_extent)) \n \n # speed of propagation = extent / duration (cm/s)\n speeds = (txt2['height']*100)/(txt2['width']*length_of_image*60) \n ave_speed = speeds.mean()\n min_speed = speeds.min()\n max_speed = speeds.max() \n print(f'Average propagation speed is %.2f cm per second (max = %.2f cm and min = %.2f cm)' %(ave_speed, min_speed, max_speed)) \n \n \n # corrected frequency, calculate frequency of events taking into account:\n # 1. only periods over which events are seen\n # 2. when there are gaps between events i.e. model doesn't find consecutive events\n # Will calculate deltas (times between events) and then take median\n event_starts = (txt2['x']-(txt2['width']/2)) * length_of_image # left-hand side of bounding box is the start of the event\n sorted_event_starts = sorted(event_starts, reverse=False) # order start times from smallest to largest \n \n num_deltas = num_events - 1\n delta = [0]*num_deltas\n \n \n # calculate delta values, the times between start times of successive events\n for counter_del in range(num_deltas):\n delta[counter_del] = sorted_event_starts[counter_del+1] - sorted_event_starts[counter_del] \n \n \n med_delta = 0\n if len(delta) > 2:\n med_delta = statistics.median(delta)\n \n corr_freq = 0\n if med_delta > 0:\n corr_freq = 1/med_delta\n \n \n # plots to show distribution of events\n #fig = plt.figure(figsize=(16,8)) \n #plt.plot(delta) \n #sns.swarmplot(y=delta)\n #plt.hist(delta, bins = 3)\n #plt.show()\n #plt.close()\n \n \n \n print(f'Corrected frequency: %.2f %s per minute ' %(corr_freq, object_class))\n\n \n class_results['num_events'] = num_events\n class_results['raw_freq'] = format(raw_freq, '.2f')\n class_results['corr_freq'] = format(corr_freq, '.2f')\n class_results['ave_dur'] = format(ave_dur, '.2f')\n class_results['max_dur'] = format(max_dur, '.2f')\n class_results['min_dur'] = format(min_dur, '.2f')\n class_results['ave_extent'] = format(ave_extent, '.2f')\n class_results['max_extent'] = format(max_extent, '.2f')\n class_results['min_extent'] = format(min_extent, '.2f')\n class_results['ave_speed'] = format(ave_speed, '.2f')\n class_results['max_speed'] = format(max_speed, '.2f')\n class_results['min_speed'] = format(min_speed, '.2f')\n\n \n \n \n results[object_class] = class_results\n \n print(\"These are all the results: {}\".format(results))\n \n dict_filename = os.path.basename(file)\n \n dict_results[dict_filename] = results\n print(\"These are ALL the results: {}\".format(dict_results)) \n \n\n return(dict_results)\n\n# how to use\n# temp =events_stats(r'PATH\\*.txt')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"events_2labels.py","file_name":"events_2labels.py","file_ext":"py","file_size_in_byte":7132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"287467173","text":"import json\n\nclass Node:\n def __init__(self, val, pos):\n self.val = val\n # Position info is stored here and ALSO as index in graph -\n # this is a form of data duplication, which is evil!\n self.pos = pos\n self.visited = False\n def __repr__(self):\n # nice repr for pprint\n return repr(self.pos)\n\ndef bfs(graph, start):\n fringe = [[start]]\n # Special case: start == goal\n if start.val == 'g':\n return [start]\n start.visited = True\n # Calculate width and height dynamically. We assume that \"graph\" is dense.\n width = len(graph[0])\n height = len(graph)\n # List of possible moves: up, down, left, right.\n # You can even add chess horse move here!\n moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n while fringe:\n # # Print fringe at each step\n # print fringe\n # print('')\n # Get first path from fringe and extend it by possible moves.\n path = fringe.pop(0)\n node = path[-1]\n pos = node.pos\n # Using moves list (without all those if's with +1, -1 etc.) has huge benefit:\n # moving logic is not duplicated. It will save you from many silly errors.\n # The example of such silly error in your code:\n # graph[pos[0-1]][pos[1]].visited = True\n # ^^^\n # Also, having one piece of code instead of four copypasted pieces\n # will make algorithm much easier to change (e.g. if you want to move diagonally).\n for move in moves:\n # Check out of bounds. Note that it's the ONLY place where we check it. Simple and reliable!\n if not (0 <= pos[0] + move[0] < height and 0 <= pos[1] + move[1] < width):\n continue\n neighbor = graph[pos[0] + move[0]][pos[1] + move[1]]\n if neighbor.val == 'g':\n return path + [neighbor]\n elif neighbor.val == 'o' and not neighbor.visited:\n neighbor.visited = True\n fringe.append(path + [neighbor]) # creates copy of list\n raise Exception('Path not found!')\n\ndef buildMatrix(data):\n info = json.loads(data)\n print(info['snakes']['coords'])\n # width = data['width']\n # height = data[\"height\"]\n # tempRow = []\n # rows = []\n # # init graph with all 0s\n # for index in range(height):\n # for index in range(width):\n # tempRow.append(0)\n # rows.append(tempRow)\n # tempRow = []\n # # add obstacles\n # snakes = data[\"snakes\"]\n # for snake in snakes:\n # # print snake\n # coords = snake.get(\"coords\")\n # # coords = snake[\"coords\"]\n # for coord in coords:\n # rowList = rows[coord[1]]\n # rowList[coord[0]] = 1;\n # # 1 = obstacle\n\n # walls = data[\"walls\"]\n # for wall in walls:\n # coords = wall.get(\"coords\")\n # rowList = rows[coord[1]]\n # rowList[coord[0]] = 1;\n # # 1 = obstacle\n\n # print rows\n pass\n\nif __name__ == '__main__':\n # Graph in convenient form: 0 is empty, 1 is wall, 2 is goal.\n # Note that you can have multiple goals.\n # data = { }\n # snake = { }\n # data[\"height\"] = 15\n # data[\"width\"] = 15\n\n # snake[\"coords\"] = [[1,1],[1,2],[2,2],[3,2]]\n\n # wall1 = {}\n # wall2 = {}\n # wall1[\"coords\"] = [4,4]\n # wall2[\"coords\"] = [12,4]\n\n # walls = [wall1,wall2]\n\n # data[\"snakes\"] = snake\n # data[\"walls\"] = walls\n predata = {\n \"width\":15,\n \"height\":15,\n \"snakes\":\n {\n \"coords\": [[1,1],[1,2],[2,2],[3,2]]\n },\n \"walls\": \n {\n \"coords\": [[4,4],[11,2]]\n }\n }\n data = json.dumps(predata)\n graph = buildMatrix(data)\n # Transform int matrix to Node matrix.\n # TRANSLATE = {0: 'o', 1: 'x', 2: 'g'}\n # graph = [[Node(TRANSLATE[x], (i, j)) for j, x in enumerate(row)] for i, row in enumerate(graph)]\n # Find path\n try:\n path = bfs(graph, graph[0][0])\n print(\"Path found: {!r}\".format(path))\n except Exception as ex:\n # Learn to use exceptions. In your original code, \"no path\" situation\n # is not handled at all!\n print(ex)","sub_path":"app/testBFS.py","file_name":"testBFS.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"19045098","text":"import apiai\nimport json\nimport telebot\nfrom config import TOKEN, DFKEY\n\n\nbot = telebot.TeleBot(TOKEN)\nkeyboard1 = telebot.types.ReplyKeyboardMarkup()\n\n\n@bot.message_handler(commands=['start'])\ndef start_message(message):\n bot.send_message(message.chat.id, 'Привет, зачем ты позвал меня?', reply_markup=keyboard1)\n\n\n@bot.message_handler(content_types=['text'])\ndef text_message(message):\n request = apiai.ApiAI(DFKEY).text_request()\n request.lang = 'ru'\n request.session_id = 'BatlabAIBot'\n request.query = message.text\n responseJson = json.loads(request.getresponse().read().decode('utf-8'))\n response = responseJson['result']['fulfillment']['speech']\n if response:\n bot.send_message(chat_id=message.chat.id, text=response)\n else:\n bot.send_message(chat_id=message.chat.id, text='Ничего не понимаю!')\n\n\nif __name__ == '__main__':\n bot.polling(none_stop=True)\n","sub_path":"bot_nn.py","file_name":"bot_nn.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"223186433","text":"\"\"\"FValidation - Main module.\n\nBefore changing the code, please consult the Developer's Guide available at\n.\n\nThe list of implemented FValidation rules is kept at\n.\nPlease keep it in sync with the code.\n\n\nThis is the main FValidation module that defines three Front Arena hook\nfunctions: validate_transaction, four_eyes_needed, and validate_entity. Front\nArena will pass data to these functions before the data are written to the\nunderlying database.\n\nYou should not normally need to edit this module. FValidation rules are\ndefined in other modules (e.g. FValidation_General). This main module\nimplements functionality that loads those rules and then calls them at the\nright time.\n\n\nEmergency recovery\n==================\n\nIt may happen that there is a bug, say a syntax error, in an FValidation\nmodule; and that bug prevents you from saving the module itself, i.e. fixing\nit. In that case, follow these steps:\n\n (1) Set constant ENABLE_VALIDATION to False (module FValidation_settings)\n and reload module FValidation_settings.\n (2) Reload the main module FValidation.\n (3) Fix the broken module, save it and reload it.\n (4) Set ENABLE_VALIDATION back to True and reload module\n FValidation_settings.\n (5) Reload the main module FValidation.\n\n\nHistory\n=======\n\n2014-08-31 Vojtech Sidorin CHNG0002210109 Initial implementation.\n2014-10-21 Andrei Conicov CHNG0002365110 Have removed the FValidation_Trade_Amend module.\n2014-11-20 Vojtech Sidorin CHNG0002443195 Add module FValidation_FixedIncome.\n2014-11-12 Nada Jasikova CHNG0002443195 Added FValidation_enrich_SecLending.\n2015-06-09 Vojtech Sidorin ABITFA-3501 Replace FValidation_depr_YC_Vol_Access with FValidation_YC_Vol_Access.\n2015-09-17 Willie van der Bank Adaptiv: Added FValidation_Adaptiv_Conf_Stlm.\n2015-11-06 Vojtech Sidorin ABITFA-3910 Add module FValidation_DatesAndTimes.\n2016-03-16 Vojtech Sidorin ABITFA-4064: Add module FValidation_Volcker.\n2016-05-09 Vojtech Sidorin ABITFA-3286: Move constants to module FValidation_settings.\n2016-06-22 Vojtech Sidroin DEMAT: Merge module FValidation_Adaptiv_Conf_Stlm to FValidation_SettleConf.\n2017-01-06 Vojtech Sidorin ABITFA-3288: Move helper functions to the FValidation_core module.\n2018-07-05 Cuen Edwards FAOPS-127: Changed bypass validation of simulated trades to exclude confirmation owner trades.\n2019-10-15 Stuart Wilson FAOPS-607: Added ability to force super user to validate against particular validations.\n\"\"\"\n\nimport sys\nimport ael\n\n# NOTE: For security reasons, the imports are done as \"from module import\n# something\" to create local copies of the objects. This means any change in\n# an external module will be reflected in FValidation only after the main\n# FValidation module is reloaded. Since the FValidation module is a \"safe\"\n# module, \"...any local changes (reloads) will only be used by the system if\n# the user has write access to the module\". See FCA3724 (AEF Basic Extensions)\n# for more information about safe modules.\nfrom FValidation_settings import (\n ENABLE_VALIDATION,\n SUPERUSERS,\n ENRICHMENT_MODULES,\n VALIDATION_MODULES,\n SUPERUSER_VALIDATIONS\n )\nfrom FValidation_core import (\n load_rules,\n debug_msg,\n handle_current_exception,\n )\n\n# Old FValidation (deprecated module) with not-yet-refactored rules.\nimport FValidation_depr\n\n# Information about the last FValidation exception that occured after\n# (re)loading this module: a tuple with values (type, value, traceback).\n# This global variable can be used by external code to retrieve the info.\n# See also the docstring of the handle_current_exception function.\nlast_exc_info = sys.exc_info()\n\n\n# Load validation rules when (re)loading the module.\ntry:\n modules = ENRICHMENT_MODULES + VALIDATION_MODULES\n rules = load_rules(modules)\nexcept:\n last_exc_info = handle_current_exception()\n raise\nelse:\n debug_msg(\"Registered {0} transaction validation rule(s) and {1} entity \"\n \"validation rule(s).\"\n .format(len(rules[\"transaction\"]), len(rules[\"entity\"])))\n\n\ndef validate_transaction(transaction_list):\n \"\"\"Front Arena hook function.\"\"\"\n global last_exc_info\n try:\n return _validate_transaction(transaction_list)\n except:\n last_exc_info = handle_current_exception()\n raise\n\n\ndef four_eyes_needed(transaction_list):\n \"\"\"Front Arena hook function.\"\"\"\n # Return:\n # 0 = Disable four-eyes checks for the transaction.\n # 1 = Perform standard four-eyes checks for the transaction.\n return 1\n\n\ndef validate_entity(entity, operation):\n \"\"\"Front Arena hook function.\"\"\"\n global last_exc_info\n try:\n return _validate_entity(entity, operation)\n except:\n last_exc_info = handle_current_exception()\n raise\n\n\ndef _validate_transaction(transaction_list):\n \"\"\"\n Implementation of FValidation.validate_transaction hook.\n \"\"\"\n if _should_bypass_all_validation():\n # Bypass transaction validation all together.\n return transaction_list\n # Apply deprecated FValidation validate_transaction.\n transaction_list = _apply_deprecated_validate_transaction(transaction_list)\n # Hook (1): Validate the entire transaction.\n transaction_list = _apply_transaction_validation_rules(transaction_list)\n # Hook (2): Validate individual entities within the transaction.\n for entity, operation in transaction_list:\n # Bypass validation of simulated trades unless they are\n # confirmation owner trades.\n if (_is_simulated_trade(entity) and\n not _is_modification_of_confirmation_owner_trade(entity, operation)):\n continue\n for entity_rule in _get_entity_validation_rules(entity, operation, \"validate_transaction\"):\n _apply_entity_validation_rule(entity_rule, entity, operation)\n return transaction_list\n\n\ndef _validate_entity(entity, operation):\n \"\"\"\n Implementation of FValidation.validate_entity hook.\n \"\"\"\n if _should_bypass_all_validation():\n # Bypass entity validation all together.\n return\n if _is_simulated_trade(entity):\n # Bypass entity validation all together.\n return\n # Apply deprecated FValidation validate_entity.\n _apply_deprecated_validate_entity(entity, operation)\n # Hook (3): Validate entities in validate_entity.\n for entity_rule in _get_entity_validation_rules(entity, operation, \"validate_entity\"):\n _apply_entity_validation_rule(entity_rule, entity, operation)\n\n\ndef _should_bypass_all_validation():\n \"\"\"\n Determine whether or not to bypass all FValidation.\n\n This function will return True if validation is disabled in\n FValidation_settings or if the current user is defined as a\n super user in FValidation_settings and has no enforced super\n user validations.\n \"\"\"\n # Check if validation is disabled.\n if not ENABLE_VALIDATION:\n debug_msg(\"FValidation has been disabled in FValidation_settings\")\n return True\n # Check if current user is a superuser without any superuser validations.\n userid = ael.user().userid\n _super_user_validation_debug_message(userid)\n if userid in SUPERUSERS and userid not in list(SUPERUSER_VALIDATIONS.keys()):\n debug_msg(\"Super User: {userid} is bypassing all FValidations\".format(userid=userid))\n return True\n # Otherwise validation should not be bypassed.\n return False\n\n\ndef _apply_deprecated_validate_transaction(transaction_list):\n \"\"\"\n Applies deprecated legacy transaction validations defined in\n FValidation_depr.\n\n Please note that super user validations are not supported for\n deprecated validations.\n \"\"\"\n if ael.user().userid in SUPERUSERS:\n return transaction_list\n debug_msg(\"validate_transaction: Validating transaction by \"\n \"FValidation_depr.validate_transaction.\")\n return FValidation_depr.validate_transaction(transaction_list)\n\n\ndef _apply_deprecated_validate_entity(entity, operation):\n \"\"\"\n Applies deprecated legacy entity validations defined in\n FValidation_depr.\n\n Please note that super user validations are not supported for\n deprecated validations.\n \"\"\"\n if ael.user().userid in SUPERUSERS:\n return\n debug_msg(\"validate_entity: Validating {entity_type}@{operation} by \"\n \"FValidation_depr.validate_entity.\"\n .format(entity_type=entity.record_type, operation=operation))\n FValidation_depr.validate_entity(entity, operation)\n\n\ndef _apply_transaction_validation_rules(transaction_list):\n \"\"\"\n Applies transaction validation rules.\n \"\"\"\n for transaction_rule in _get_transaction_validation_rules():\n debug_msg(\"validate_transaction: Validating transaction by \"\n \"{module}.{function}.\"\n .format(module=transaction_rule.__module__,\n function=transaction_rule.__name__))\n transaction_list = transaction_rule(transaction_list)\n return transaction_list\n\n\ndef _apply_entity_validation_rule(entity_rule, entity, operation):\n \"\"\"\n Applies the specified entity validation rule.\n \"\"\"\n debug_msg(\"validate_entity: Validating {entity_type}@{operation} by \"\n \"{module}.{function}.\"\n .format(entity_type=entity.record_type,\n operation=operation,\n module=entity_rule.__module__,\n function=entity_rule.__name__))\n entity_rule(entity, operation)\n\n\ndef _get_transaction_validation_rules():\n \"\"\"\n Gets all transaction validation rules to be enforced for the\n current user.\n \"\"\"\n transaction_rules = []\n userid = ael.user().userid\n for transaction_rule in rules[\"transaction\"]:\n if userid in SUPERUSERS and transaction_rule.__name__ not in SUPERUSER_VALIDATIONS[userid]:\n continue\n transaction_rules.append(transaction_rule)\n return transaction_rules\n\n\ndef _get_entity_validation_rules(entity, operation, caller):\n \"\"\"\n Gets all entity validation rules to be enforced for the\n current user.\n \"\"\"\n entity_rules = []\n userid = ael.user().userid\n for entity_rule, entity_type, rule_operation, rule_caller in rules[\"entity\"]:\n if userid in SUPERUSERS and entity_rule.__name__ not in SUPERUSER_VALIDATIONS[userid]:\n continue\n if entity_type != entity.record_type:\n continue\n if rule_operation != operation:\n continue\n if rule_caller != caller:\n continue\n entity_rules.append(entity_rule)\n return entity_rules\n\n\ndef _is_simulated_trade(entity):\n \"\"\"\n Determine whether or not an entity is a simulated trade.\n \"\"\"\n return entity.record_type == \"Trade\" and entity.status == \"Simulated\"\n\n\ndef _is_modification_of_confirmation_owner_trade(entity, operation):\n \"\"\"\n Determine whether or not an operation being performed is the\n modification of a confirmation owner trade.\n\n Confirmation owner trades are created to own confirmations that are\n related to multiple trades (e.g. term statements, loan notices, etc.).\n\n Such trades are identified by being in simulated status and having\n the trader ATS_CONFO.\n \"\"\"\n if entity.record_type != 'Trade':\n return False\n if operation != 'Update':\n return False\n if entity.original().status != 'Simulated':\n return False\n trader = entity.original().trader_usrnbr\n if trader is None or trader.userid != 'ATS_CONFO':\n return False\n return True\n\n\ndef _super_user_validation_debug_message(userid):\n \"\"\"debug message for super user validation only to be called when\n debug mode is enabled\"\"\"\n\n if userid in list(SUPERUSER_VALIDATIONS.keys()):\n functions = SUPERUSER_VALIDATIONS[userid]\n debug_message = \"Super User: {userid} will validate against: {functions}\".format(\n userid=userid,\n functions=functions)\n debug_msg(debug_message)\n\n","sub_path":"Python modules/FValidation.py","file_name":"FValidation.py","file_ext":"py","file_size_in_byte":12311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"304214994","text":"#This module check whether the records is consecutive. For debug purpose.\nimport pandas as pd\n\n\ndef check_bike(record, operation, car_num):\n mcount = 0\n def _is_good_operation(oper_df):\n count = 0\n for ix, row in oper_df.iterrows():\n oper_type = int(row['oper_type'])\n count += 1\n if count%2 != oper_type%2:\n return False\n return True\n\n is_undefine = True\n for ix, row in record.iterrows():\n if is_undefine:\n rent_station = row['rent_netid']\n return_station = row['return_netid']\n rent_time = row['normal_rent']\n return_time = row['normal_return']\n is_undefine = False\n continue\n new_rent_station = row['rent_netid']\n new_return_station = row['return_netid']\n new_rent_time = row['normal_rent']\n new_return_time = row['normal_return']\n if new_rent_station == return_station:\n rent_station = new_rent_station\n return_station = new_return_station\n rent_time = new_rent_time\n return_time = new_return_time\n continue\n car_df = operation[operation['normal_time'] >= return_time]\n car_df = car_df[car_df['normal_time'] <= new_rent_time]\n if len(car_df) != 0:\n if len(car_df)%2 == 0:\n if _is_good_operation(car_df):\n head_row = car_df.head(1)\n head_station = (head_row['net_id']).iloc[0]\n tail_row = car_df.tail(1)\n tail_station = (tail_row['net_id']).iloc[0]\n if (int(head_station) == int(return_station)) and (int(tail_station) == int(new_rent_station)):\n rent_station, rent_time, return_station, return_time = \\\n new_rent_station, new_rent_time, new_return_station, new_return_time\n continue\n mcount += 1\n #print(car_num)\n #print(rent_station, rent_time, return_station, return_time)\n #print(new_rent_station, new_rent_time, new_return_station, new_return_time)\n #input('Pause...')\n rent_station, rent_time, return_station, return_time = \\\n new_rent_station, new_rent_time, new_return_station, new_return_time\n return mcount\n\nall_record = pd.read_csv('clean_record.csv')\nall_operation = pd.read_csv('essential_sjx.csv')\nallbike = all_record['car_num']\nallbike = allbike.drop_duplicates()\nacount = 0\ncount = 0\nfor i, car_num in allbike.iteritems():\n sub_record = all_record[all_record['car_num'] == car_num]\n sub_record = sub_record.sort_values(by='normal_rent')\n sub_record = sub_record.reset_index()\n sub_operation = all_operation[all_operation['car_num']==car_num]\n sub_operation = sub_operation.sort_values(by='normal_time')\n sub_operation = sub_operation.reset_index()\n acount = acount + check_bike(sub_record, sub_operation,car_num)\n count += 1\n if count%1000 == 0:\n print(count)\nprint(acount)","sub_path":"preprocess/colse_loop.py","file_name":"colse_loop.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"114391496","text":"def partition(a,start,end):\n\tpivot = a[end]\n\tpindex=start\n\t \n\n\tfor i in range(start, end):\n\t\tif a[i] <= pivot:\n\t\t\tt=a[pindex]\n\t\t\ta[pindex] = a[i]\n\t\t\ta[i]=t\n\t\t\tpindex = pindex+1\n\t\n\tt = a[pindex]\n\ta[pindex] = pivot\n\n\ta[end] = t\n\tprint(a)\n\n\tprint(\"pivot\")\n\tprint(pivot)\n\tprint(\"pindex\")\t\n\tprint(pindex)\n\treturn pindex\n\n\ndef quicksort(a):\n\tlast = len(a) - 1\n\tfirst = 0 \n\t\n\n\tqsorting(a,first,last)\n\ndef qsorting(a,first,last):\n\t\n\tif first (Mapping.Base, NearestNeighborsQuery.Base):\n if algorithm == \"exact\":\n if metric == 'l1':\n return (Mapping.DenseFloat(dims), NearestNeighborsQuery.Exact(field, dummy, Similarity.L1))\n elif metric == 'l2':\n return (Mapping.DenseFloat(dims), NearestNeighborsQuery.Exact(field, dummy, Similarity.L2))\n elif metric == 'angular':\n return (Mapping.DenseFloat(dims), NearestNeighborsQuery.Exact(field, dummy, Similarity.L2))\n elif metric == 'jaccard':\n return (Mapping.SparseBool(dims), NearestNeighborsQuery.Exact(field, dummy, Similarity.Jaccard))\n elif metric == 'hamming':\n return (Mapping.SparseBool(dims), NearestNeighborsQuery.Exact(field, dummy, Similarity.Hamming))\n elif algorithm == 'sparse_indexed':\n if metric == 'jaccard':\n return (Mapping.SparseIndexed(dims), NearestNeighborsQuery.SparseIndexed(field, dummy, Similarity.Jaccard))\n elif metric == 'hamming':\n return (Mapping.SparseIndexed(dims), NearestNeighborsQuery.SparseIndexed(field, dummy, Similarity.Hamming))\n elif algorithm == 'lsh':\n if metric == 'jaccard':\n return (Mapping.JaccardLsh(dims, **mapping_params), NearestNeighborsQuery.JaccardLsh(field, dummy, **query_params))\n raise NameError\n\n self._mk_mapping_query = lambda dims: _mk_mapping_query(dims)\n self._mapping = None\n self._query = None\n self._eknn = ElastiKnnClient(es)\n\n def fit(self, X: Union[np.ndarray, csr_matrix, List[Vec.SparseBool], List[Vec.DenseFloat]], shards: int = 1):\n vecs = list(canonical_vectors_to_elastiknn(X))\n dims = len(vecs[0])\n (self._mapping, self._query) = self._mk_mapping_query(dims)\n\n if self._index is None:\n self._index = f\"{ELASTIKNN_NAME}-{int(time())}\"\n self._logger.warning(f\"index was not given, using {self._index} instead\")\n\n self._eknn.es.indices.delete(self._index, ignore=[400, 404])\n body = dict(settings=dict(number_of_shards=shards, number_of_replicas=0))\n self._eknn.es.indices.create(self._index, body=json.dumps(body))\n self._eknn.es.indices.refresh(self._index)\n self._eknn.put_mapping(self._index, self._field, mapping=self._mapping)\n self._eknn.es.indices.refresh(self._index)\n\n self._logger.info(f\"indexing {len(vecs)} vectors into index {self._index}\")\n ids = [str(i + 1) for i in range(len(vecs))] # Add one because 0 is an invalid id in ES.\n self._eknn.index(self._index, self._field, vecs, ids, refresh=True)\n\n def kneighbors(self, X: Union[np.ndarray, csr_matrix, List[Vec.SparseBool], List[Vec.DenseFloat], List[Vec.Base]],\n n_neighbors: int, return_similarity: bool = False, allow_missing: bool = False):\n futures = []\n for vec in canonical_vectors_to_elastiknn(X):\n args = (self._index, self._query.with_vec(vec), n_neighbors, False)\n futures.append(self._tpex.submit(self._eknn.nearest_neighbors, *args))\n inds = np.ones((len(X), n_neighbors), dtype=np.int32) * -1\n sims = np.zeros((len(X), n_neighbors), dtype=np.float) * np.nan\n wait(futures) # Ensures same order as calls.\n for i, future in enumerate(futures):\n res = future.result()\n hits = res['hits']['hits']\n assert allow_missing or len(hits) == n_neighbors, f\"Expected {n_neighbors} hits for vector {i} but got {len(hits)}\"\n for j, hit in enumerate(hits):\n inds[i][j] = int(hit['_id']) - 1 # Subtract one because 0 is an invalid id in ES.\n sims[i][j] = float(hit['_score'])\n\n if return_similarity:\n return inds, sims\n else:\n return inds\n","sub_path":"client-python/elastiknn/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"441676755","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 11 15:21:18 2018\n\n@author: ChristianKazuyoshi\n\"\"\"\n\n# https://www.kaggle.com/archaeocharlie/a-beginner-s-approach-to-classification\n\nimport pandas as pd\nimport matplotlib.pyplot as plt, matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\n\n\n#%%\n\nlabeled_images = pd.read_csv('data/train.csv')\nimages = labeled_images.iloc[0:5000,1:]\nlabels = labeled_images.iloc[0:5000,:1]\ntrain_images, test_images,train_labels, test_labels = train_test_split(images, labels, train_size=0.8, random_state=0)\n\n\n#%%\n\ni=1\nimg=train_images.iloc[i].as_matrix()\nimg=img.reshape((28,28))\nplt.imshow(img,cmap='gray')\nplt.title(train_labels.iloc[i,0])\n\n#%%\n\nplt.hist(train_images.iloc[i])\n#%%\n\nclf = svm.SVC()\nclf.fit(train_images, train_labels.values.ravel())\nclf.score(test_images,test_labels)\n\n\n#%%\ntest_images[test_images>0]=1\ntrain_images[train_images>0]=1\n\nimg=train_images.iloc[i].as_matrix().reshape((28,28))\nplt.imshow(img,cmap='binary')\nplt.title(train_labels.iloc[i])\nplt.hist(train_images.iloc[i])\n\n#%%\n\nclf = svm.SVC()\nclf.fit(train_images, train_labels.values.ravel())\nclf.score(test_images,test_labels)\n\n#%%\n\ntest_data=pd.read_csv('data/test.csv')\ntest_data[test_data>0]=1\nresults=clf.predict(test_data)\nresults\n\n\n#%%\ndf = pd.DataFrame(results)\n\n#df = df.reindex(df.index.rename(['ImageId']))\ndf.index+=1\ndf.index.names=['ImageId'] # depois de df.index+=1\ndf.columns=['Label']\n#df.to_csv('results.csv', index = True, index_label = ['ImageId'])\ndf.to_csv('results.csv', header = True)","sub_path":"Tutorial1.py","file_name":"Tutorial1.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"299127683","text":"\nfrom two_test import Authentication_helper\n\nauth = Authentication_helper('https://id.test.cognita.ru/api/')\n\nfirst_headers = {\n \"Accept\": \"application/json, text/plain, */*\",\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Accept-Language\": \"en-us,en;q=0.8\",\n \"Content-Type\": \"application/json;charset=UTF-8\",\n \"Cookie\": \"_gat=1; _ga=GA1.2.1994786266.1453794507\",\n}\naut_body = {\n \"login\": \"golubenkov_test@mail.ru\",\n \"password\": \"igor-igor\"\n }\n\nresp = auth.req_sessionid(aut_body, first_headers)\n\nif resp.status_code != 200:\n raise ConnectionError('Status error: {}'.format(resp.status_code))\nprint('Get Session ID: {}'.format(resp.json()[\"sessionId\"]), \",\", 'Response JSON: {}'.format(resp.json()))\n\nses_id = resp.json()['sessionId']\n\nheaders_X_Session_Id = {\n \"Accept\": \"application/json, text/plain, */*\",\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Accept-Language\": \"en-us,en;q=0.8\",\n \"Content-Type\": \"application/json;charset=UTF-8\",\n \"Cookie\": \"_gat=1; _ga=GA1.2.1994786266.1453794507\",\n \"X-Session-Id\": ses_id,\n }\n\noauth_body = {\n \"clientId\": 0,\n \"credentials\": {\n \"id\": [\"main\",\"accounts\",\"groups\"]\n }\n }\n\nresp = auth.req_code(oauth_body, headers_X_Session_Id)\n\nses_code = resp.json()['code']\n\nif resp.status_code != 200:\n raise ConnectionError('Status error: {}'.format(resp.status_code))\nprint('Get Code: {}'.format(ses_code), \",\", 'Response JSON: {}'.format(resp.json()))\n\noauth_token_body = {\n \"clientId\": \"0\",\n \"clientSecret\": \"@Mqb8Xh7m5N5~eW\",\n \"grantType\": \"code\",\n \"code\": ses_code,\n \"refreshToken\": \"null\"\n }\n\nresp = auth.req_oauth_token(oauth_token_body, headers_X_Session_Id)\n\nses_token = resp.json()[\"token\"]\n\nif resp.status_code != 200:\n raise ConnectionError('Status error: {}'.format(resp.status_code))\nprint('Get oauth Token: {}'.format(ses_token), \",\", 'Response JSON: {}'.format(resp.json()))\n\n\n","sub_path":"test_authentication.py","file_name":"test_authentication.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"125506972","text":"import socket, time\nimport argparse\nfrom multiprocessing import Process\nimport procman\nimport logging\n\ndef get_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n # doesn't even have to be reachable\n s.connect(('10.255.255.255', 0))\n IP = s.getsockname()[0]\n except:\n IP = '127.0.0.1'\n finally:\n s.close()\n return IP\n \ndef runMaster(lport, loglevel):\n\ttime.sleep(.5) # so clients get there first and have to retry\n\tminst = masterinst(lport, loglevel)\n\tminst.runforever()\n\tprint (\"Master has terminated\")\n\nclass masterinst(procman.ProcClient):\n\tdef __init__(self,listport,loglevel):\n\t\tsuper().__init__(\"master\")\n\t\tif loglevel == 1:\n\t\t\tself.setLogLevels(logging.DEBUG, logging.DEBUG)\n\t\tprint(\"master listener instantiated\")\n\t\tself.clientset=[]\n\t\tself.clientctr=None\n\t\tself.listener = procman.ProcAccepter(self,False,listenport,self.newclient, aname=\"masterListener\")\n\t\t\n\tdef newclient(self, clientsock):\n\t\tprint(\"new client requested access\")\n\t\tif self.clientctr is None:\n\t\t\tself.clientctr = 1\n\t\telse:\n\t\t\tself.clientctr += 1\n\t\tself.clientset.append(masterresponder(clientsock, self, self.clientctr))\n\n\tdef deadclient(self,client):\n\t\tif client in self.clientset:\n\t\t\tself.clientset.remove(client)\n\t\t\tself.clientctr -= 1\n\t\tprint(\"client gone %d left \" % self.clientctr)\n\t\tif self.clientctr == 0:\n\t\t\tself.close()\n\nclass masterresponder(procman.ProcServerConnection):\n\tdef __init__(self, sock, parent,instctr):\n\t\tsuper().__init__(parent, sock, self.obin, \"master responder %d\" % instctr)\n\t\tself.mctr = 1\n\n\tdef close(self):\n\t\tself.parent.deadclient(self)\n\t\tsuper().close()\n\n\tdef obin(self, anob):\n\t\tself.lgr.debug(\"I have message %s, count %d\" % (anob['msg'],anob['ctr']))\n\t\tself.mctr += 1\n\t\tif 'byeee' in anob:\n\t\t\tprint(\"cycle done - client should close\")\n\t\telse:\n\t\t\tanob['msg'] = 'PONG'\n\t\t\tanob['ctr'] = self.mctr\n\t\t\tself.sendOb(anob)\n\ndef runClient(instno,targip,targport, loglevel):\n\tcinst = clientinst(instno,targip,targport, loglevel)\n\tcinst.runforever()\n\tprint (\"Client %d has terminated\" % instno)\n\nclass clientinst(procman.ProcClient):\n\tdef __init__(self,instno,tip,tport, loglevel):\n\t\tself.cstr = \"client %d\" % instno\n\t\tsuper().__init__(self.cstr)\n\t\tprint(\"%s instantiated\" % self.cstr)\n\t\tif loglevel == 1:\n\t\t\tself.setLogLevels(logging.DEBUG, logging.DEBUG)\n\t\tself.mconn = procman.ProcHostConnection(self, (tip,tport), self.obreceived, self.cstr)\n\t\tif loglevel == 1:\n\t\t\tself.mconn.setLogLevel(logging.DEBUG)\n\t\tself.ticker = procman.ProcCallback(time.time()+0.5, 2-instno*.2, self)\n\t\tself.sendctr = 0\n\t\tself.callmeback(self.ticker,True)\n\t\tself.mconn.sendOb({'ctr':self.sendctr, 'msg': 'fred'})\n\t\tself.pendcount = 0\n\t\tself.closetime = None\n\t\n\tdef obreceived(self,obin):\n\t\trcount = int(obin['ctr'])\n#\t\tif rcount % 10 == 0:\n\t\tprint(\"ob received by %s >%s< %d\" % (self.cstr, obin['msg'], obin['ctr']))\n\t\tif rcount > 200:\n\t\t\tself.mconn.sendOb({'ctr':self.sendctr, 'msg': 'fred', 'byeee':1})\n\t\t\trunning = False\n\t\t\tself.closetime = time.time() + 5\n\t\telse:\n\t\t\tself.pendcount += 1\n\t\t\tif rcount % 10 == 0:\n\t\t\t\tself.sendctr += 1\n\t\t\t\tself.mconn.sendOb({'ctr':self.sendctr, 'msg': 'fred'})\n\t\t\t\tprint(\"add extra %d\" % self.sendctr)\n \t\t\n\tdef pollme(self, p1):\n\t\tprint(\"pollme called with %d pending\" % self.pendcount)\n\t\twhile self.pendcount > 0:\n\t\t\tself.sendctr += 1\n\t\t\tself.pendcount -= 1\n\t\t\tself.mconn.sendOb({'ctr':self.sendctr, 'msg': 'fred'})\n\t\tif not self.closetime is None:\n\t\t\tif time.time() > self.closetime or not self.mconn.hasWriteData():\n\t\t\t\tprint(\"%s all sent / timeout: closing down\" % self.cstr)\n\t\t\t\tself.callmeback(self.ticker,False)\n\t\t\t\tself.mconn.close()\n\t\t\t\tself.close()\n\t\t\t\t\n\nLISTPORT=34242\nAGENTCOUNT=3\nif __name__==\"__main__\":\n\tprint(\"simple test harness for procman, run on multiple machines for full test\")\n\tmyip = get_ip()\n\t\n\tparser = argparse.ArgumentParser(description=\"test app for procman\")\n\n\tparser.add_argument( \"-m\", \"--masteraddress\"\n\t\t, help=\"ip address of PC running as master, default: this instance is the master\")\n\tparser.add_argument( \"-p\", \"--listenport\", type=int\n\t\t, help=\"port used for listener, default %d\" % LISTPORT)\n\tparser.add_argument(\"-a\", \"--agentcount\",type=int\n\t\t, help=\"number of agent subprocesses to start\")\n\tparser.add_argument(\"-v\", \"--verbose\"\n\t\t, help=\"set debug level to DEBUG rather than INFO\")\n\targs = parser.parse_args()\n\t\n\tlistenport = args.listenport if args.listenport else LISTPORT\n\tloglevel = 1 if args.verbose else 0\n\tif not args.masteraddress:\n\t\tprint(\"running master listener on %s:%d\" % (myip,listenport))\n\t\tmastproc = Process(target=runMaster, name = \"master\"\n\t\t\t\t, args= (listenport, loglevel))\n\t\tmastproc.start()\n\t\tmasterip = '127.0.0.1'\n\t\tprint(\"master listener running\")\n\telse:\n\t\tprint(\"running as client, connecting to %s:%d\" %(args.masteraddress,listenport))\n\t\tmasterip = args.masteraddress\n\t\tmast=None\n\t\n\tagents = args.agentcount if args.agentcount else 1\n\n\tclients = []\n\tfor i in range(1,agents+1):\n\t\tcproc = Process(target=runClient, name=\"client\" + str(i)\n\t\t\t\t, args=(i,masterip,listenport,loglevel))\n\t\tcproc.start()\n\t\tclients.append(cproc)\n\t\ttime.sleep(0.5)\n\ttry:\n\t\ttime.sleep(10)\n\t\tclientactive = True\n\t\twhile clientactive:\n\t\t\tclientactive = False\n\t\t\tfor proc in clients:\n\t\t\t\tif proc.is_alive():\n\t\t\t\t\tclientactive = True\n\t\t\t\t\tprint(\"%s is alive\" % proc.name)\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tprint(\"%s is finished\" % proc.name)\n\t\t\ttime.sleep(3)\n\t\tprint(\"all clients are closed - exiting\")\n\t\tfor proc in clients:\n\t\t\tproc.join()\n\t\tif not args.masteraddress:\n\t\t\tprint(\"just the master process left...\")\n\t\t\tmastproc.join()\n\t\t\n\texcept KeyboardInterrupt:\n\t\tpass\n\t ","sub_path":"procmantest.py","file_name":"procmantest.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"553170974","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten,LeakyReLU\nfrom keras.layers import Convolution2D, MaxPooling2D, BatchNormalization,Reshape,UpSampling2D\nfrom keras.utils import np_utils\nfrom sklearn.utils import shuffle\n\ndef discriminator():\n model = Sequential()\n #1->(32,32,128)\n model.add(Convolution2D(64, (3, 3), strides=(2, 2), input_shape=(32, 32, 3), padding='same'))\n # model.add(BatchNormalization())\n model.add(LeakyReLU(0.2))\n model.add(Dropout(0.2))\n #2->(16,16,256)\n model.add(Convolution2D(128, (3, 3), strides=(2, 2), padding='same'))\n # model.add(BatchNormalization())\n model.add(LeakyReLU(0.2))\n model.add(Dropout(0.2))\n #3->(8,8,512),one filter:5*5*256, 512 filters in total\n model.add(Convolution2D(256, (3, 3), strides=(2, 2), padding='same'))\n # model.add(BatchNormalization())\n model.add(LeakyReLU(0.2))\n model.add(Dropout(0.2))\n #4->(4,4,1024)\n model.add(Convolution2D(512, (3, 3), strides=(2, 2), padding='same'))\n # model.add(BatchNormalization())\n model.add(LeakyReLU(0.2))\n model.add(Dropout(0.2))\n #final\n model.add(Flatten())\n model.add(Dense(units=1))\n model.add(Activation('sigmoid'))\n return model\n\ndef generator(inputdim=120, xdim=4, ydim=4):\n model = Sequential()\n #pre, 100->1024*4*4\n model.add(Dense(input_dim=inputdim, units=512 * xdim * ydim))\n #1)4*4*1024->8*8*512\n # model.add(BatchNormalization())#batch norm in G can cause strong intra-class correlation\n model.add(Activation('relu'))\n model.add(Reshape((xdim, ydim,512), input_shape=(inputdim,)))\n model.add(UpSampling2D(size=(2, 2)))\n model.add(Convolution2D(256, (3, 3), padding='same'))\n #2)->16*16*256\n # model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(UpSampling2D(size=(2, 2)))\n model.add(Convolution2D(128, (3, 3), padding='same'))\n #3->32*32*128\n # model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(UpSampling2D(size=(2, 2)))\n model.add(Convolution2D(3, (3, 3), padding='same'))\n\n #final\n # model.add(Activation('tanh'))\n model.add(Activation('sigmoid'))\n return model\n\n # # 8. Compile model\n # model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])\n # # 9. Fit model on training data\n # model.fit(X_train, Y_train,batch_size=32, nb_epoch=10, verbose=1)\n #\n # # 10. Evaluate model on test data\n # score = model.evaluate(X_test, Y_test, verbose=0)\n\ndef generator_containing_discriminator(generator, discriminator):\n model = Sequential()\n model.add(generator)\n discriminator.trainable = False\n model.add(discriminator)\n return model\n\ndef main():\n D = discriminator()\n G = generator()\n model = generator_containing_discriminator(G,D)\n G.summary()\n D.summary()\n model.summary()\n\nif __name__==\"__main__\":\n main()\n","sub_path":"GAN_models_32BN.py","file_name":"GAN_models_32BN.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"169449885","text":"import xml.etree.ElementTree as ET\nimport os\nimport json\n\ndef is_tempdb(root):\n table_type = root.find('.//TableType')\n if (table_type is not None):\n if (table_type.text == 'TempDB' or table_type.text == 'InMemory'):\n return True\n else:\n return False\n else:\n return False\n\ndef get_tables(directory):\n output = []\n for root, subdirs, files in os.walk(os.curdir):\n for filename in files:\n file_path = os.path.join(root, filename)\n if ('AxTable' in file_path):\n if ('.xml' in filename):\n output.append([file_path, filename])\n print('\\t- file %s (full path: %s)' % (filename, file_path), end='')\n return output\n\ndef get_fields(root):\n output = []\n field_nodes = root.findall('.//Fields/AxTableField/Name')\n for x in field_nodes:\n output.append(x.text)\n return output\n\n\n\nif __name__ == '__main__':\n target_directory = ''\n\n #os.chdir(target_directory)\n output = []\n\n tables = get_tables(target_directory)\n\n for i in tables:\n tree = ET.parse(i[0])\n root = tree.getroot()\n output.append([i[1], get_fields(root)])\n \n\n with open('output.json', 'w') as fi:\n fi.write(json.dumps(output))","sub_path":"metadata-parser-poc/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"121912766","text":"\"\"\"\nThis script is used for detecting lane line in images\nand videos.\n\"\"\"\nimport cv2\nimport os\nimport numpy as np\nimport matplotlib.image as mpimg\nfrom moviepy.editor import VideoFileClip\nfrom tqdm import tqdm\n\n# ###### Constants ############\nLANE_HEIGHT_METERS = 30\nLANE_WIDTH_METERS = 3.7\n\n# The distance in pixels between lanes\nLANE_WIDTH_PIXELS = 700\n\n\nclass Line:\n \"\"\"\n This class contains line info\n \"\"\"\n\n __slots__ = ['detected', 'recent_fitted_x', 'best_x', 'best_fit',\n 'current_fit', 'radius_of_curvature', 'line_base_pos',\n 'diffs', 'all_x', 'all_y']\n\n def __init__(self):\n # Was the line detected in the last iteration?\n self.detected = False\n # Average x values of the fitted line over the last n iterations\n self.best_x = 0\n # Polynomial coefficients averaged over the last n iterations\n self.best_fit = None\n # Polynomial coefficients for the most recent fit\n self.current_fit = [np.array([False])]\n # Radius of curvature of the line in some units\n self.radius_of_curvature = None\n # Distance in meters of vehicle center from the line\n self.line_base_pos = None\n # Difference in fit coefficients between last and new fits\n self.diffs = np.array([0, 0, 0], dtype='float')\n # x values for detected line pixels\n self.all_x = None\n # y values for detected line pixels\n self.all_y = None\n\n def get_points(self):\n \"\"\"\n Returns a Tuple with `all_y` and `all_x`\n \"\"\"\n return self.all_y, self.all_x\n\n\nclass Camera:\n \"\"\"\n This class handles all camera related functionality.\n \"\"\"\n\n __slots__ = ['_camera_mtx', '_camera_dist', '_wrap_mat', '_wrap_mat_inv']\n\n def __init__(self):\n self._camera_mtx = None\n self._camera_dist = None\n\n # Bird-eye wrap preparation\n # Source points(formatted like the actual rectangle)\n src_points = np.float32([[594, 450], [688, 450],\n [200, 720], [1100, 720]])\n # Create the destination points array\n dst_points = np.float32([[300, 0], [1000, 0],\n [300, 720], [1000, 720]])\n # Create wrap matrix\n self._wrap_mat = cv2.getPerspectiveTransform(src_points, dst_points)\n self._wrap_mat_inv = cv2.getPerspectiveTransform(dst_points, src_points)\n\n def calibrate_camera(self, cal_images_path, chessboard_size):\n \"\"\"\n Calibrates the camera using chessboard pattern calibration.\n :param cal_images_path: The path for a folder containing\n camera calibration images.\n :param chessboard_size: The 2D dimensions of the chessboard\n \"\"\"\n obj_points, img_points = [], []\n img_shape = None\n\n # Object points for all the images is the same.\n # The object points are only in the xy plane thous z axes is zero.\n img_obj_points = np.zeros((chessboard_size[0] * chessboard_size[1], 3), dtype=np.float32)\n img_obj_points[:, :2] = np.mgrid[0:chessboard_size[0], 0:chessboard_size[1]].T.reshape(-1, 2)\n\n print('Calibrating camera')\n\n # Run on all images in the calibration folder.\n pbar = tqdm(os.listdir(cal_images_path))\n for img_path in pbar:\n pbar.set_description('Processing {}'.format(img_path))\n img = mpimg.imread(os.path.join(cal_images_path, img_path))\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n found, corners = cv2.findChessboardCorners(gray, chessboard_size, None)\n\n if found:\n img_points.append(corners)\n obj_points.append(img_obj_points)\n\n if img_shape is None:\n img_shape = gray.shape\n\n pbar.close()\n\n if len(img_points) == 0:\n # If we got here we got a problem.\n raise ValueError(\"Didn't find chessboard pattern in any of the images in '{}'.\".format(cal_images_path))\n\n print('Calculating calibration matrix and distortion coefficients.')\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, img_shape[::-1], None, None)\n self._camera_mtx = mtx\n self._camera_dist = dist\n print('Camera calibration done')\n\n def _create_bit_mask(self, src, low_tresh, high_tresh):\n \"\"\"\n Creates a bit mask from `src` image when the bits are `1`\n only when `src` is between the thresholds.\n :param src: Source image\n :param low_tresh: Low threshold for mask\n :param high_tresh: High threshold for mask\n :return: A bit mask with the image shape.\n \"\"\"\n bit_mask = np.zeros_like(src, dtype=np.bool)\n bit_mask[(low_tresh <= src) & (src <= high_tresh)] = 1\n return bit_mask\n\n def _get_edges(self, image, s_thresh, sobel_thresh, red_thresh):\n \"\"\"\n Detects lane edges in an image via converting\n the image to HLS.\n The final result is created from the image S-channel and the\n xy derivative of the image L-channel.\n\n :param image: An image or a list of images\n :param s_thresh: A tuple or list representing the lower and upper\n thresholds that will be used on the image S-channel\n :param sobel_thresh: A tuple or list representing the lower and upper\n thresholds that will be being used on the xy\n derivative of the image L-channel\n :return: A binary image or a list of binary images that\n contains only the edges of the `images`\n \"\"\"\n\n r_channel = image[:, :, 0]\n r_mask = self._create_bit_mask(r_channel, *red_thresh)\n\n hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n l_channel = hls[:, :, 1]\n s_channel = hls[:, :, 2]\n\n# l_channel = cv2.equalizeHist(l_channel)\n # Take the derivative of the l channel in both x and y directions\n sobel_x = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0)\n sobel_y = cv2.Sobel(l_channel, cv2.CV_64F, 0, 1)\n # Calculate the magnitude using complex numbers math.\n sobel_mag = np.abs(sobel_x + 1j * sobel_y)\n # Scale the magnitude to the size of one byte.\n sobel_scaled = np.uint8(255 * sobel_mag / np.max(sobel_mag))\n # Create bit mask\n sobel_mask = self._create_bit_mask(sobel_scaled, *sobel_thresh)\n\n s_mask = self._create_bit_mask(s_channel, *s_thresh)\n # Combine both masks using bitwise or\n combined_mask = s_mask | sobel_mask | r_mask\n return combined_mask\n\n def get_lane_view(self, image, s_thresh=(110, 255), sobel_thresh=(60, 120), red_thresh=(230, 254)):\n \"\"\"\n Takes an image and process it using the following steps:\n * Fix camera distortions\n * Find edges in images\n * Warp to bird-eye view\n :param image: The image to be processed.\n :param s_thresh: Lower & Upper HLS S-Channel thresholds for edge detection.\n :param sobel_thresh: Lower & Upper Sobel derivative thresholds for edge detection.\n :param red_thresh: Lower & Upper RGB R-Channel thresholds for edge detection\n :return: A binary that contains the image lanes in bird-eye view and the undistorted image.\n \"\"\"\n assert self._camera_mtx is not None, 'Camera must be calibrated first!'\n undistorted = cv2.undistort(image, self._camera_mtx, self._camera_dist)\n edges = self._get_edges(undistorted, s_thresh, sobel_thresh, red_thresh)\n warped = cv2.warpPerspective(np.float32(edges), self._wrap_mat, edges.shape[::-1], flags=cv2.INTER_LINEAR)\n return warped, undistorted\n\n def _draw_lane(self, image, lane_color,\n left_line_color, left_line_points, left_line_poly_coeffs,\n right_line_color, right_line_points, right_line_poly_coeffs):\n \"\"\"\n Draws a lanes on an image\n :param image: An undistorted image\n :param lane_color: The lane color in RBG format\n :param left_line_color: The left line color in RBG format\n :param left_line_points: A tuple with y,x point of the lane for this specific image\n :param left_line_poly_coeffs: A list with the line polynomial coefficients.\n :param right_line_color: The left line color in RBG format\n :param right_line_points: A tuple with y,x point of the lane for this specific image\n :param right_line_poly_coeffs: A list with the line polynomial coefficients.\n :return:\n \"\"\"\n # Create an image to draw the lines on\n binary_zero = np.zeros(image.shape[0:2]).astype(np.uint8)\n warped_overlay = np.dstack((binary_zero, binary_zero, binary_zero))\n\n # Draw the lane area on the overlay\n # Calculate lines\n plot_y = np.linspace(0, image.shape[0] - 1, image.shape[0])\n left_fit_x = np.polyval(left_line_poly_coeffs, plot_y)\n right_fit_x = np.polyval(right_line_poly_coeffs, plot_y)\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fit_x, plot_y]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fit_x, plot_y])))])\n pts = np.hstack((pts_left, pts_right))\n # Draw the lane onto the warped blank image\n cv2.fillPoly(warped_overlay, np.int_([pts]), lane_color)\n # Draw the lines on the overlay\n warped_overlay[left_line_points[0], left_line_points[1]] = left_line_color\n warped_overlay[right_line_points[0], right_line_points[1]] = right_line_color\n\n # Warp the overlay back to the image perspective\n overlay = cv2.warpPerspective(warped_overlay, self._wrap_mat_inv, (image.shape[1], image.shape[0]),\n flags=cv2.INTER_LINEAR)\n result = cv2.addWeighted(image, 1, overlay, 0.6, 0)\n return result\n\n def _add_info(self, image, curvature, left_line_pos, right_line_pos):\n \"\"\"\n Adds additional text info to the picture\n :param image: The image\n :param curvature: The curvature of the lane\n :param left_line_pos: The distance in meters of left line from center\n :param right_line_pos: The distance in meters of right line from center\n :return: The image with text\n \"\"\"\n cv2.putText(image, 'Radius of Curvature = {}(m)'.format(np.int(curvature)), (50, 70),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255))\n\n # Find the shift from center\n arg_max = np.argmax((left_line_pos, right_line_pos))\n lane_width = left_line_pos + right_line_pos\n\n shift_text = 'Vehicle is {}m {} of center'\n if arg_max == 0:\n # The shift is to the left\n shift = np.round(left_line_pos - lane_width/2, 2)\n shift_text = shift_text.format(shift, 'left')\n else:\n # The shift is to the right\n shift = np.round(right_line_pos - lane_width/2, 2)\n shift_text = shift_text.format(shift, 'right')\n\n cv2.putText(image, shift_text.format(np.int(curvature)), (50, 140),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255))\n\n return image\n\n def draw_on_image(self, image, left_lane_line: Line, right_lane_line: Line):\n \"\"\"\n Draws lane on `image` and add additional info at the top left of the image\n :param image: An undistorted image\n :param left_lane_line: The left lane line\n :param right_lane_line: The right lane line\n :return: An image with lane highlighted and lane data written on it\n \"\"\"\n processed = self._draw_lane(image, (0, 255, 0),\n (255, 0, 0), left_lane_line.get_points(), left_lane_line.best_fit,\n (0, 0, 255), right_lane_line.get_points(), right_lane_line.best_fit)\n\n curvature = np.min((left_line.radius_of_curvature, right_line.radius_of_curvature))\n processed = self._add_info(processed, curvature, left_line.line_base_pos, right_line.line_base_pos)\n\n return processed\n\n\ndef detect_lane(binary, lines, movie_mode=True, max_skip=0):\n \"\"\"\n Detects a line in a binary, this method detects one\n line only and searches for it only in the predefined\n `detection_zone`.\n This method will try tracking the line first when possible\n and on failure will try finding it by scanning the `detection_zone`.\n :param max_skip: The maximum number of frames the algorithm will avoid\n finding the line if tracking is failed\n :param movie_mode: If this flag is `True` line tracking and skipping will\n be enabled.\n :param lines: A tuple with both the lane lines\n :param binary: A binary.\n \"\"\"\n\n # ########### Helper methods ####################################\n def validate_lane_lines(binary, left_fit, right_fit, error_margin=200):\n \"\"\"\n Checks if the detected lines are valid.\n :param right_fit: The polynomial coefficients of the right line\n :param left_fit: The polynomial coefficients of the left line\n :param binary: A binary\n :param error_margin: The margin of error of the mean distance\n between the lines\n :return: `True` if the lines are valid and `False` otherwise.\n \"\"\"\n y_points = np.linspace(0, binary.shape[0] - 1, binary.shape[0])\n x_left = np.polyval(left_fit, y_points)\n x_right = np.polyval(right_fit, y_points)\n\n # Check lines distance and that they don't meet\n distances = x_right - x_left\n if any(distances <= 0):\n print('validation failed, error: Crossing lines')\n return False\n normed_distances = np.abs(distances - np.mean(distances))\n if any(normed_distances >= error_margin):\n print('validation failed, error: {} is above error margin'.format(np.max(normed_distances)))\n return False\n\n return True\n\n def find_lane(binary, lines, n_windows=19, recenter_thresh=50, win_margin=100):\n \"\"\"\n Looks for a line in a binary image.\n Scans the `detection_zone` in order to find\n the line using the following steps:\n * Calculate bottom half histogram in order\n to find the initial searching point\n * Use sliding windows in order to follow the\n line from the initial point and collect the points\n that make up the line along the way\n * Use the collected points in order to interpolate\n the line using numpy.polyfit with degree of 2.\n\n :param lines: A tuple containing the lane lines\n :param binary: A binary image.\n :param n_windows: The number of windows to use.\n :param recenter_thresh: The minimum number of pixels that need\n to be found in order to justify recalculation\n of window center.\n :param win_margin: The margin of the window in the x axes.\n \"\"\"\n # Extract the lane lines\n left_line, right_line = lines\n\n midpoint = binary.shape[1]//2\n # Calculate the histogram of the bottom half of the image\n histogram = np.sum(binary[binary.shape[0] // 2:, :], axis=0)\n # Find the peak location\n curr_pos_left = np.argmax(histogram[:midpoint])\n curr_pos_right = np.argmax(histogram[midpoint:]) + midpoint\n # Use sliding windows in order to find the line\n window_height = np.int(binary.shape[0] / n_windows)\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = binary.nonzero()\n nonzero_y = np.array(nonzero[0])\n nonzero_x = np.array(nonzero[1])\n # Create list for the line pixel indices\n left_line_idx = []\n right_line_idx = []\n\n for window in range(n_windows):\n # Identify window boundaries in x and y\n win_y_high = binary.shape[0] - window * window_height\n win_y_low = win_y_high - window_height\n win_x_left_low = curr_pos_left - win_margin\n win_x_left_high = curr_pos_left + win_margin\n win_x_right_low = curr_pos_right - win_margin\n win_x_right_high = curr_pos_right + win_margin\n # Identify the nonzero pixels in x and y within the window\n nonzero_win_left_idx = ((nonzero_y >= win_y_low) &\n (nonzero_y <= win_y_high) &\n (nonzero_x >= win_x_left_low) &\n (nonzero_x <= win_x_left_high)).nonzero()[0]\n nonzero_win_right_idx = ((nonzero_y >= win_y_low) &\n (nonzero_y <= win_y_high) &\n (nonzero_x >= win_x_right_low) &\n (nonzero_x <= win_x_right_high)).nonzero()[0]\n # Add points indices to their corresponding list\n left_line_idx.append(nonzero_win_left_idx)\n right_line_idx.append(nonzero_win_right_idx)\n # Recenter the window if needed\n if len(nonzero_win_left_idx) > recenter_thresh:\n # Recenter to the indices mean position\n curr_pos_left = np.mean(nonzero_x[nonzero_win_left_idx], dtype=np.int)\n if len(nonzero_win_right_idx) > recenter_thresh:\n # Recenter to the indices mean position\n curr_pos_right = np.mean(nonzero_x[nonzero_win_right_idx], dtype=np.int)\n\n left_line_idx = np.concatenate(left_line_idx)\n right_line_idx = np.concatenate(right_line_idx)\n\n # If we didn't find both of the lines then the detection failed.\n if not any(left_line_idx) or not any(right_line_idx):\n left_line.detected = right_line.detected = False\n return\n\n left_line_x = nonzero_x[left_line_idx]\n left_line_y = nonzero_y[left_line_idx]\n left_line_fit = np.polyfit(left_line_y, left_line_x, 2)\n\n right_line_x = nonzero_x[right_line_idx]\n right_line_y = nonzero_y[right_line_idx]\n right_line_fit = np.polyfit(right_line_y, right_line_x, 2)\n\n if not validate_lane_lines(binary, left_line_fit, right_line_fit):\n return\n\n if left_line.current_fit is not None:\n left_line.diffs = left_line.current_fit - left_line_fit\n right_line.diffs = right_line.current_fit - right_line_fit\n\n left_line.current_fit = left_line_fit\n right_line.current_fit = right_line_fit\n\n left_line.all_x, left_line.all_y = left_line_x, left_line_y\n right_line.all_x, right_line.all_y = right_line_x, right_line_y\n\n left_line.detected = right_line.detected = True\n\n def track_lane(binary, lines, margin=20):\n \"\"\"\n Tracks the lines based on latest fit found\n :param margin: The margin in which to track the lines in.\n :param lines: A tuple containing the lane lines\n :param binary: A binary\n :return: `True` if the lines were found, and `False` otherwise.\n \"\"\"\n # Extract lane lines\n left_line, right_line = lines\n # If the line was not detected last frame then there is nothing to track\n if (not left_line.detected) or (not left_line.detected):\n return False\n\n nonzero = binary.nonzero()\n nonzero_y = np.array(nonzero[0])\n nonzero_x = np.array(nonzero[1])\n\n left_fit_val_x = np.polyval(left_line.current_fit, nonzero_y)\n right_fit_val_x = np.polyval(right_line.current_fit, nonzero_y)\n\n left_line_idx = ((nonzero_x > (left_fit_val_x - margin)) & (nonzero_x < (left_fit_val_x + margin)))\n right_line_idx = ((nonzero_x > (right_fit_val_x - margin)) & (nonzero_x < (right_fit_val_x + margin)))\n\n # If we didn't find both of the lines then the detection failed.\n if not any(left_line_idx) or not any(right_line_idx):\n left_line.detected = right_line.detected = False\n return False\n\n left_line_x = nonzero_x[left_line_idx]\n left_line_y = nonzero_y[left_line_idx]\n left_line_fit = np.polyfit(left_line_y, left_line_x, 2)\n\n right_line_x = nonzero_x[right_line_idx]\n right_line_y = nonzero_y[right_line_idx]\n right_line_fit = np.polyfit(right_line_y, right_line_x, 2)\n\n if not validate_lane_lines(binary, left_line_fit, right_line_fit):\n return False\n\n left_line.diffs = left_line.current_fit - left_line_fit\n right_line.diffs = right_line.current_fit - right_line_fit\n\n left_line.current_fit = left_line_fit\n right_line.current_fit = right_line_fit\n\n left_line.all_x, left_line.all_y = left_line_x, left_line_y\n right_line.all_x, right_line.all_y = right_line_x, right_line_y\n\n return True\n\n # ###############################################################\n\n # Crop the binary to the `detection_zone`\n left_line, right_line = lines\n global skip_count\n\n # Try to track the lanes first (only in movie mode) and if tracking fails,\n # decide if to use previous fit info or to find the lane again.\n if not movie_mode or not track_lane(binary, lines):\n if movie_mode and left_line.best_fit is not None and skip_count < max_skip:\n skip_count += 1\n else:\n find_lane(binary, lines)\n\n if left_line.detected:\n skip_count = 0\n\n\ndef average_lines(binary, lines, alpha=0.8):\n \"\"\"\n Calculate the best fit of the lines via averaging the fitted_x points via\n weighted mean, by the following formula, best_x=(1-alpha)*best_x + alpha*current_fit_x\n :param binary: The binary\n :param lines: A tuple with both left & right lane lines\n :param alpha: The alpha number of the weighted mean\n :return:\n \"\"\"\n left_line, right_line = lines\n\n # Calculate the x point for each of the lines\n y_points = np.linspace(0, binary.shape[0] - 1, binary.shape[0])\n x_left = np.polyval(left_line.current_fit, y_points)\n x_right = np.polyval(right_line.current_fit, y_points)\n\n left_line.best_x = left_line.best_x*(1-alpha) + x_left*alpha\n right_line.best_x = right_line.best_x*(1-alpha) + x_right*alpha\n\n # Calculate the best fit\n left_line.best_fit = np.polyfit(y_points, left_line.best_x, 2)\n right_line.best_fit = np.polyfit(y_points, right_line.best_x, 2)\n\n\ndef update_curvature_and_pos(binary, lines):\n \"\"\"\n Updates curvature and position from center\n \"\"\"\n # Extract lane lines\n left_line, right_line = lines\n # Calculate meter per pixel (mpp) in both axis\n mpp_y = LANE_HEIGHT_METERS / binary.shape[0]\n mpp_x = LANE_WIDTH_METERS / LANE_WIDTH_PIXELS\n\n y_eval = binary.shape[0] * mpp_y\n\n # Fit new polynomials to x,y in world space\n left_line_y, left_line_x = left_line.all_y, left_line.all_x\n left_line_fit = np.polyfit(left_line_y * mpp_y, left_line_x * mpp_x, 2)\n\n right_line_y, right_line_x = right_line.all_y, right_line.all_x\n right_line_fit = np.polyfit(right_line_y * mpp_y, right_line_x * mpp_x, 2)\n\n # Calculate curvature at the bottom of the image\n # For left line\n first_der = [2*left_line_fit[0], left_line_fit[1]]\n second_der = 2*left_line_fit[0]\n\n numerator = (1 + np.polyval(first_der, y_eval)**2)**1.5\n denominator = np.abs(second_der)\n left_line.radius_of_curvature = numerator / denominator\n\n # For right line\n first_der = [2*right_line_fit[0], right_line_fit[1]]\n second_der = 2*right_line_fit[0]\n\n numerator = (1 + np.polyval(first_der, y_eval)**2)**1.5\n denominator = np.abs(second_der)\n right_line.radius_of_curvature = numerator / denominator\n\n # Calculate position\n center_pos = (binary.shape[1] / 2) * mpp_x\n left_lane_pos = np.polyval(left_line_fit, y_eval)\n right_lane_pos = np.polyval(right_line_fit, y_eval)\n\n left_line.line_base_pos = np.abs(left_lane_pos - center_pos)\n right_line.line_base_pos = np.abs(right_lane_pos - center_pos)\n\n\ndef process_image(image, movie_mode=True):\n \"\"\"\n Advanced lane line processor, assumes that\n :param movie_mode: Enables/Disables the following:\n * lane tracking (use previous fit to find the current fit).\n * skip detection when tracking fails (use the same fit as the last one\n for `max_skip` number of times).\n * calculate the best fit by weighted average.\n :param image: input image\n :return: processed image\n \"\"\"\n lanes, undist = camera.get_lane_view(image)\n lines = (left_line, right_line)\n\n detect_lane(lanes, lines, movie_mode=movie_mode, max_skip=4)\n\n if left_line.detected and right_line.detected:\n if movie_mode:\n average_lines(lanes, lines)\n else:\n left_line.best_fit = left_line.current_fit\n right_line.best_fit = right_line.current_fit\n\n update_curvature_and_pos(lanes, lines)\n\n # If there is no fit to use - leave the image as is.\n if left_line.best_fit is not None:\n return camera.draw_on_image(undist, left_line, right_line)\n\n return undist\n\n\nif __name__ == '__main__':\n output_folder = 'output_images'\n input_path = 'test_images'\n input_path = 'project_video.mp4'\n\n print(\"Starting lane detection pipeline. input={} output={}\".format(input_path, output_folder))\n\n camera = Camera()\n # Calibrate the camera\n camera.calibrate_camera('camera_cal', (9, 6))\n\n # Global parameters\n left_line = Line()\n right_line = Line()\n # set `skip_count` to np.inf to make sure that on movie mode\n # the first frame won't be skipped.\n skip_count = np.inf\n\n print('Processing...')\n # Create files list\n if os.path.isdir(input_path):\n files = os.listdir(input_path)\n else:\n files = [input_path]\n\n for file in files:\n if os.path.isdir(input_path):\n file_path = os.path.join(input_path, file)\n else:\n file_path = input_path\n\n if not os.path.isfile(file_path):\n continue\n\n suffix = file.split('.')[1]\n if suffix == 'jpg':\n # Image processing pipeline\n img = mpimg.imread(file_path)\n dst = process_image(img, movie_mode=False)\n print(file)\n mpimg.imsave(os.path.join(output_folder, file), dst)\n elif suffix == 'mp4':\n # Video processing pipeline\n clip = VideoFileClip(file_path)\n dst = clip.fl_image(process_image)\n dst.write_videofile(os.path.join(output_folder, file), audio=False)\n\n print('Done')\n","sub_path":"detect_lanes.py","file_name":"detect_lanes.py","file_ext":"py","file_size_in_byte":26801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"559817975","text":"# Copyright (C) 2017 Daniel Watkins \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.\nimport configparser\n\nimport pytest\n\nfrom jenkins_job_linter.config import (\n _filter_config,\n _get_default_linter_configs,\n)\nfrom jenkins_job_linter.linters import Linter\n\nfrom .mocks import create_mock_for_class\n\n\nclass TestGetDefaultLinterConfigs:\n\n def test_no_linters_returns_empty_dict(self, mocker):\n mocker.patch('jenkins_job_linter.config.LINTERS', {})\n assert {} == _get_default_linter_configs()\n\n def test_with_linters(self, mocker):\n default_config = {'key': 'value', 'other_key': ['some', 'values']}\n linter_with_config = create_mock_for_class(\n Linter, default_config=default_config)\n mocker.patch('jenkins_job_linter.config.LINTERS', {\n 'no_config': create_mock_for_class(Linter),\n 'some_config': linter_with_config,\n })\n assert {\n 'job_linter:no_config': {},\n 'job_linter:some_config': default_config,\n } == _get_default_linter_configs()\n\n\nclass TestFilterConfig:\n\n def test_filter_by_prefix(self, mocker):\n mocker.patch('jenkins_job_linter.config.GLOBAL_CONFIG_DEFAULTS', {})\n mocker.patch('jenkins_job_linter.config.LINTERS', {})\n config = configparser.ConfigParser()\n wont_filter = ['job_linter', 'job_linter:linter', 'job_linter-thing']\n will_filter = ['jenkins', 'jenkins_jobs', 'whatever-else']\n config.read_dict({k: {} for k in wont_filter + will_filter})\n filtered_config = _filter_config(config)\n assert set(wont_filter) == set(filtered_config.sections())\n\n @pytest.mark.parametrize('expected,option_content', (\n ([], ''),\n (['eggs'], 'eggs'),\n (['eggs', 'spam'], 'eggs,spam'),\n (['eggs', 'spam'], 'eggs, spam'),\n (['eggs', 'spam'], ' eggs, spam '),\n (['eggs', 'spam'], ' eggs,\\nspam '),\n ))\n def test_returned_configparser_getlist(\n self, expected, mocker, option_content):\n mocker.patch('jenkins_job_linter.config.GLOBAL_CONFIG_DEFAULTS', {})\n mocker.patch('jenkins_job_linter.config.LINTERS', {})\n config = configparser.ConfigParser()\n config.read_dict({'job_linter': {'opt': option_content}})\n filtered_config = _filter_config(config)\n assert expected == filtered_config.getlist('job_linter', 'opt')\n\n def test_sectionproxy_getlist(self, mocker):\n mocker.patch('jenkins_job_linter.config.GLOBAL_CONFIG_DEFAULTS', {})\n mocker.patch('jenkins_job_linter.config.LINTERS', {})\n config = configparser.ConfigParser()\n config.read_dict({'job_linter': {'opt': 'content'}})\n filtered_config = _filter_config(config)\n assert ['content'] == filtered_config['job_linter'].getlist('opt')\n","sub_path":"tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"5005307","text":"import tkinter\nimport tkinter.font as tkf\nroot = tkinter.Tk()\nroot.config(bg=\"red\")\nroot.geometry(\"400x400\")\nroot.minsize(400,400)\nroot.maxsize(500,500)\n# l1 = tkinter.Label(text=\"Welcome to python\",font=\"Arial 22 bold\")\nf = tkf.Font(weight=\"bold\")\nl1 = tkinter.Label(text=\"Welcome \\nto \\npython\",font=f,width=20,height=4)\n# l1.config(font=(\"times new roman\", \"30\" ,\"bold\"))\nl1.config(borderwidth=2,anchor=\"se\",relief=\"solid\")\nl1.pack()\nroot.mainloop()","sub_path":"Projects/Music Player/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"558876873","text":"#import all of the things we will be using\r\nfrom django.db import models\r\nfrom tagging.fields import TagField\r\n# to help with translation of field names\r\nfrom django.utils.translation import ugettext_lazy as _\r\n# to have a generic foreign key for any model\r\nfrom django.contrib.contenttypes import generic\r\n# stores model info so this can be applied to any model\r\nfrom django.contrib.contenttypes.models import ContentType\r\n\r\nclass Book(models.Model):\r\n \"\"\"\r\n The details of a Book\r\n \"\"\"\r\n # fields that describe this book\r\n name = models.CharField(_('name'), max_length=48)\r\n isbn = models.CharField(_('isbn'), max_length=16)\r\n url = models.URLField(_('url'), verify_exists=False, blank=True)\r\n description = models.TextField(_('description'))\r\n \r\n # to add to any model\r\n content_type = models.ForeignKey(ContentType)\r\n object_id = models.PositiveIntegerField()\r\n content_object = generic.GenericForeignKey('content_type',\r\n 'object_id')\r\n \r\n # for the list of tags for this book\r\n tags = TagField()\r\n \r\n # misc fields\r\n deleted = models.BooleanField(default=0)\r\n created = models.DateTimeField(auto_now_add=True)\r\n # so that {{book.get_absolute_url}} outputs the whole url\r\n @models.permalink\r\n def get_absolute_url(self):\r\n return (\"book_details\", [self.pk])\r\n # outputs name when printing this object as a string\r\n def __unicode__(self):\r\n return self.name\r\n\r\n\r\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"38006537","text":"\n\n#calss header\nclass _NURSERY():\n\tdef __init__(self,): \n\t\tself.name = \"NURSERY\"\n\t\tself.definitions = [u'a place where young children and babies are taken care of while their parents are at work: ', u'a room in a house where small children sleep and play', u'a place where plants and trees are grown, especially for sale']\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/_nursery.py","file_name":"_nursery.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"524815969","text":"from django.urls import path\nfrom .views import home, user_profile, team, events, event_registration\n\nurlpatterns = [\n path('', home, name='home'),\n path('user-profile/', user_profile, name='user-profile'),\n path('team/', team, name='team'),\n path('events/', events, name='events'),\n path('event-registration/', event_registration, name='event-registration')\n]","sub_path":"webpage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"262203046","text":"'''\n给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。\n\nnums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。\n\n示例 1:\n\n输入: nums1 = [4,1,2], nums2 = [1,3,4,2].\n输出: [-1,3,-1]\n解释:\n 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。\n 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。\n 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。\n示例 2:\n\n输入: nums1 = [2,4], nums2 = [1,2,3,4].\n输出: [3,-1]\n解释:\n 对于num1中的数字2,第二个数组中的下一个较大数字是3。\n 对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。\n注意:\n\nnums1和nums2中所有元素是唯一的。\nnums1和nums2 的数组大小都不超过1000。\n'''\n\n\nclass Solution:\n def nextGreaterElement(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n out=[]\n for n in range(len(nums1)):\n start=nums2.index(nums1[n])\n for i in range(start,len(nums2)):\n if nums1[n]= 0:\n if res > 0:\n flash('Patient successfully added')\n # here it is possible that patient was already in database (checked by pesel), so must check first and last name\n res = register_patient(db, request.form['fname'], request.form['lname'], request.form['pesel'])\n if res > 0:\n flash('Patient signed in')\n return redirect(url_for('main_screen'))\n elif res == -1:\n error = 'Patient with this PESEL exist, but personal information does not match'\n form_data['pesel'] = request.form['pesel']\n elif res == -2:\n error = \"Patient already signed in\"\n else:\n flash('Error signing in patient')\n else:\n error = \"Error adding patient\"\n return redirect(url_for('main_screen'))\n return render_template('sign_in_new_patient.html', data=form_data, error=error)\n\n@app.route('/show_patients', methods=['GET'])\ndef show_patients():\n error = None\n db = get_db()\n position = get_position(db, session['username'])\n if 'logged_in' not in session or not session['logged_in'] or position not in ['Admin', 'Head physician', 'Doctor', 'Nurse']:\n flash('You do not have rights to access this part of website')\n return redirect(url_for('main_screen')) \n\n if position in ['Admin', 'Head physician']:\n cur = db.execute('select p.fname, p.lname, p.pesel, f.admission_d from files f join patients p on f.patient_pesel = p.pesel where f.discharge_d is null')\n patients = cur.fetchall()\n else: \n patients = get_patients_allowed(db, session['username'])\n \n discharge = None\n if position in ['Admin', 'Head physician', 'Doctor']:\n discharge = True\n \n return render_template('show_patients.html', patients=patients, allow_discharge=discharge)\n \n@app.route('/patient_details', methods=['GET', 'POST'])\ndef patient_details():\n error = None\n db = get_db()\n position = get_position(db, session['username'])\n if 'logged_in' not in session or not session['logged_in'] or position not in ['Admin', 'Head physician', 'Doctor', 'Nurse']:\n flash('You do not have rights to access this part of website')\n return redirect(url_for('main_screen')) \n \n if 'patient' not in request.args:\n flash('No patient specified!');\n return redirect(url_for('main_screen')) \n pesel = request.args['patient'] \n \n medical_records = None \n \n if request.method == \"POST\":\n if request.form['ftype'] == 'assign_personel':\n if add_assignment(db, pesel, request.form['new_personel_id']):\n flash('Added new assignment')\n else:\n flash('Assignment already exist')\n elif request.form['ftype'] == 'deassign_yourself':\n remove_assignment(db, pesel, session['username'])\n flash('Assignment removed')\n if position not in ['Admin', 'Head physician']:\n return redirect(url_for('main_screen'))\n elif request.form['ftype'] == 'presc_drug':\n quantity = float(request.form['quantity'])\n if quantity <= 0:\n error = 'Cannot prescribe this quantity'\n else:\n num = prescribe_drug(db, session['username'], pesel, request.form['presc_drug'], quantity)\n if num < 0:\n flash('Error in prescribing drug (%d)' % (num))\n return redirect(url_for('main_screen')) \n if num != quantity:\n error = 'Not enough drug in storage. Canceling. Contact your supervisor.'\n else:\n flash('Drug prescribed')\n elif request.form['ftype'] == 'order_proc':\n num = order_procedure(db, session['username'], pesel, request.form['ordered_proc'])\n if num < 0:\n flash('Error in prescribing drug (%d)' % (num))\n return redirect(url_for('main_screen'))\n else:\n flash('Procedure ordered')\n elif request.form['ftype'] == 'view_history':\n medical_records = get_all_medical_records(db, pesel)\n \n if position in ['Admin', 'Head physician']:\n details = get_patient_details(db, pesel)\n else:\n details = get_patient_details_if_allowed(db, session['username'], pesel)\n if not details:\n flash('You cannot view this record')\n return redirect(url_for('main_screen')) \n \n personel = get_assigned_personel_for_patient(db, pesel)\n employees = get_all_medical_personel(db) \n \n deassign = None\n if (is_assigned(db, pesel, session['username'])):\n deassign = True\n \n discharge = None\n if position in ['Admin', 'Head physician', 'Doctor']:\n discharge = True\n \n curr_history = get_current_history(db, pesel)\n avail_drugs = get_all_allowed_drugs(db, session['username']) \n avail_procedures = get_all_allowed_procedures(db, session['username']) \n \n return render_template('patient_details.html', details=details, personel=personel, employees=employees, error=error, deassign=deassign, allowed_discharge=discharge, curr_history=curr_history, avail_drugs=avail_drugs, avail_procedures=avail_procedures, medical_records=medical_records)\n\n@app.route('/discharge', methods=['GET', 'POST'])\ndef discharge():\n db = get_db()\n position = get_position(db, session['username'])\n if 'logged_in' not in session or not session['logged_in'] or position not in ['Head physician', 'Doctor', 'Admin']:\n flash('You do not have rights to access this part of website')\n return redirect(url_for('main_screen')) \n \n if 'patient' not in request.args:\n flash('No patient specified!');\n return redirect(url_for('main_screen')) \n pesel = request.args['patient'] \n \n if position in ['Admin', 'Head physician']:\n details = get_patient_details(db, pesel)\n else:\n details = get_patient_details_if_allowed(db, session['username'], pesel)\n if not details:\n flash('You cannot view this record')\n return redirect(url_for('main_screen')) \n \n if request.method == 'POST':\n if request.form['confirmation'] == 'yes' and discharge_patient(db, pesel):\n flash('Patient discharged')\n else:\n flash('Error while discharging. Contact system administrator.')\n return redirect(url_for('show_patients'))\n \n return render_template('discharge.html', details=details)\n\n@app.route('/view_supplies', methods=['GET'])\ndef view_supplies():\n db = get_db()\n position = get_position(db, session['username'])\n if 'logged_in' not in session or not session['logged_in'] or position not in ['Admin', 'Warehouseman', 'Head physician']:\n flash('You do not have rights to access this part of website')\n return redirect(url_for('main_screen')) \n \n supplies = get_all_active_drugs(db)\n return render_template('view_supplies.html', supplies=supplies)\n \n@app.route('/drug_details', methods=['GET', 'POST']) \ndef drug_details():\n db = get_db()\n error = None\n position = get_position(db, session['username'])\n if 'logged_in' not in session or not session['logged_in'] or position not in ['Admin', 'Warehouseman', 'Head physician']:\n flash('You do not have rights to access this part of website')\n return redirect(url_for('main_screen')) \n \n if 'drug' not in request.args:\n flash('No drug specified!');\n return redirect(url_for('main_screen')) \n id = int(request.args['drug']) \n \n allow_orders = (position in ['Admin', 'Warehouseman'])\n allow_change_price = (position in ['Admin', 'Head physician'])\n allow_delete = allow_change_price\n \n if request.method == 'POST':\n if request.form['ftype'] == 'order_more':\n if not allow_orders:\n error = 'You are not allowed to place orders'\n else:\n quantity = float(request.form['quantity'])\n if not order_drug(db, id, quantity, session['username']):\n error = \"Cannot proceed with order\"\n else:\n flash(\"Order requested\")\n elif request.form['ftype'] == 'change_price':\n if not allow_change_price:\n error = 'You are not allowed to change price'\n else:\n price = float(request.form['price'])\n if price < 0:\n error = \"Price cannot be less than zero\"\n else:\n change_drug_price(db, id, price)\n flash('Price changed')\n elif request.form['ftype'] == 'delete_drug':\n if not allow_delete:\n error = 'You are not allowed to delete the drug'\n else:\n inactivate_drug(db, id)\n flash('Drug deleted')\n return redirect(url_for('view_supplies'))\n else:\n flash('Not supported')\n return redirect(url_for('main_screen')) \n \n details = get_active_drug_details(db, id)\n if not details:\n flash('Inactive drug')\n return redirect(url_for('main_screen')) \n orders = get_drug_orders(db, id, 10)\n return render_template('drug_details.html', details=details, error=error, orders=orders, allow_orders=allow_orders, allow_change_price=allow_change_price, allow_delete=allow_delete)\n \n@app.route('/cost_summary', methods=['GET', 'POST'])\ndef cost_summary(): \n db = get_db()\n error = None\n position = get_position(db, session['username'])\n if 'logged_in' not in session or not session['logged_in'] or position not in ['Admin', 'Accountant']:\n flash('You do not have rights to access this part of website')\n return redirect(url_for('main_screen')) \n \n form = None \n total = None\n subtotals = None\n details = None\n if request.method == 'POST':\n form = request.form\n if form['d_from'] != \"\" and form['d_to'] != \"\" and form['d_from'] <= form['d_to']:\n (total, subtotals, details) = get_cost_report(db, form['d_from'], form['d_to'], form.getlist('category'), form.getlist('options'), form['sorting'])\n else:\n error = \"Date format incorrect\"\n\n return render_template('cost_summary.html', form=form, error=error, total=total, subtotals=subtotals, details=details)\n \nif __name__ == '__main__':\n app.run()","sub_path":"hospital/flaskr/flaskr.py","file_name":"flaskr.py","file_ext":"py","file_size_in_byte":17473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"354682205","text":"import sys\nsys.path.append(\"../\")\nfrom Domain.student import *\nfrom dataStruct.DataStruct import *\nimport datetime\nimport unittest\n\nclass StudentRepo:\n \"\"\"\n This is the repository for students. They are stored in a list.\n The groups list is for validation purposes when adding an assignment.\n \"\"\"\n def __init__(self):\n self._studentList = DataStruct()\n self._groups = []\n self._IDs = []\n def store(self, student):\n self._studentList.append(student)\n if(not student._group in self._groups):\n self._groups.append(student._group)\n self._IDs.append(student._sID)\n def get_student_list(self):\n return self._studentList.getList()\n def get_groups_list(self):\n return self._groups\n def get_ID_list(self):\n return self._IDs\n def get_assignments(self, sID):\n lst = self._studentList.getList()\n for i in range(0, len(lst)):\n if(lst[i]._sID == sID):\n return self._studentList[i].getAssignmentList()\n def remove_student(self, ID):\n lst = self._studentList.getList()\n for i in range(0, len(lst)):\n if(lst[i].getID() == ID):\n del self._studentList[i]\n del self._IDs[i]\n break\n def assign_for_student(self, sID, aID):\n lst = self._studentList.getList()\n for i in range(0, len(lst)):\n if(lst[i].getID() == sID and lst[i].has_assignment(aID) == False):\n self._studentList[i].addAssignment(aID)\n break\n def assign_for_group(self, group, aID):\n lst = self._studentList.getList()\n for i in range(0, len(lst)):\n if(lst[i]._group == group and lst[i].has_assignment(aID) == False):\n self.assign_for_student(lst[i]._sID, aID)\n def find_Student(self, ID):\n lst = self._studentList.getList()\n for i in range(0, len(lst)):\n if(lst[i].getID() == ID):\n return lst[i]\n return None\n def update_Student(self, ID, newName, newGroup):\n lst = self._studentList.getList()\n for i in range(0, len(lst)):\n if(lst[i].getID() == ID):\n self._studentList[i]._name = newName\n if(newGroup != \"0\"):\n self._studentList[i]._group = newGroup\n break\n def delete_student_assignment(self, sID, aID):\n for i in range(0, len(self._studentList)):\n if(self._studentList[i]._sID == sID):\n for j in range(0, len(self._studentList[i]._assignments)):\n if(self._studentList[i]._assignments[j] == aID):\n del self._studentList[i]._assignments[j]\n break\n break\n def delete_group_assignment(self, group, aID):\n for i in range(0, len(self._studentList)):\n if(self._studentList[i]._group == group):\n for j in range(0, len(self._studentList[i]._assignments)):\n if(self._studentList[i]._assignments[j] == aID):\n del self._studentList[i]._assignments[j]\n break\n def students_with_assignment(self, aID):\n lst = self._studentList.getList()\n sLst = []\n for student in lst:\n if(aID in student.getAssignmentList()):\n sLst.append(student)\n return sLst\n def find_for_validation(self, sID):\n lst = self._studentList.getList()\n for i in range(0, len(lst)):\n if(lst[i].getID() == sID):\n return lst[i]\n return Student(1, \"n\", \"n\")\n def alphaSorted(self):\n lst = self.get_student_list()\n lst = self._studentList.gnomeSort(lst, compareAlphaS)\n return lst\n def filteredByGroup(self, group):\n newList = self._studentList.filterFunc(group, filterByGroup)\n return newList\nclass TestStudentRepo(unittest.TestCase):\n def setUp(self):\n self.sRepo = StudentRepo()\n self.s1 = Student(12, \"Darjan\", \"912\")\n self.s2 = Student(13, \"Andrei\", \"912\")\n self.s3 = Student(14, \"Rad\", \"931\")\n self.s4 = Student(15, \"Cristi\", \"917\")\n self.sRepo.store(self.s1)\n self.sRepo.store(self.s2)\n self.sRepo.store(self.s3)\n def test_store(self):\n self.sRepo.store(self.s4)\n self.assertEqual(self.sRepo._studentList, [self.s1, self.s2, self.s3, self.s4])\n self.assertTrue(self.sRepo._groups == [\"912\", \"931\", \"917\"])\n self.assertTrue(self.sRepo._IDs == [12, 13, 14, 15])\n self.assertNotEqual(self.sRepo._studentList, [self.s1, self.s2])\n def test_get(self):\n self.assertEqual(self.sRepo.get_student_list(), [self.s1, self.s2, self.s3])\n self.assertEqual(self.sRepo.get_groups_list(), [\"912\", \"931\"])\n self.assertEqual(self.sRepo.get_ID_list(), [12, 13, 14])\n def test_removeS(self):\n self.sRepo.remove_student(13)\n self.assertEqual(self.sRepo.get_student_list(), [self.s1, self.s3])\n self.assertEqual(self.sRepo.get_groups_list(), [\"912\", \"931\"])\n self.assertEqual(self.sRepo.get_ID_list(), [12, 14])\n def test_assign(self):\n self.sRepo.assign_for_student(12, \"A1\")\n self.assertEqual(self.sRepo.get_assignments(12), [\"A1\"])\n self.sRepo.assign_for_group(\"912\", \"A1\")\n self.sRepo.assign_for_student(13, \"A2\")\n self.assertEqual(self.sRepo.get_assignments(12), [\"A1\"])\n self.assertEqual(self.sRepo.get_assignments(13), [\"A1\", \"A2\"])\n def test_update(self):\n self.sRepo.update_Student(12, \"Drjn\", \"944\")\n self.sRepo.update_Student(13, \"And\", \"0\")\n lst = self.sRepo.get_student_list()\n for i in range(0, len(lst)):\n if(lst[i].getID() == 12):\n self.assertEqual(lst[i].getName(), \"Drjn\")\n self.assertEqual(lst[i].getGroup(), \"944\")\n elif(lst[i].getID() == 13):\n self.assertEqual(lst[i].getName(), \"And\")\n self.assertEqual(lst[i].getGroup(), \"912\")\n def test_find(self):\n self.assertEqual(self.sRepo.find_Student(12), self.s1)\n self.assertNotEqual(self.sRepo.find_Student(12), self.s2)\n self.assertEqual(self.sRepo.find_Student(34), None)\n def test_get_assignments(self):\n self.sRepo.assign_for_student(12, \"A1\")\n self.sRepo.assign_for_student(12, \"A2\")\n self.assertEqual(self.sRepo.get_assignments(12), [\"A1\", \"A2\"])\n def test_deleteAssignments(self):\n self.sRepo.assign_for_student(12, \"A1\")\n self.sRepo.assign_for_student(12, \"A2\")\n self.sRepo.delete_student_assignment(12, \"A1\")\n self.assertEqual(self.sRepo.get_assignments(12), [\"A2\"])\n self.sRepo.assign_for_student(12, \"A1\")\n self.sRepo.assign_for_student(12, \"A2\")\n self.sRepo.assign_for_student(13, \"A2\")\n self.sRepo.delete_group_assignment(\"912\", \"A2\")\n self.assertEqual(self.sRepo.get_assignments(12), [\"A1\"])\n self.assertEqual(self.sRepo.get_assignments(13), [])\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Repositories/studentRepo.py","file_name":"studentRepo.py","file_ext":"py","file_size_in_byte":7114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"165891018","text":"#Default Imports\nimport numpy as np\n\nipl_matches_array =np.genfromtxt(\"data/ipl_matches_small.csv\", dtype=\"|S50\", skip_header=1, delimiter=\",\")\n\n#Your Solution\n\ndef get_wicket_delivery_numbers_array(player):\n delivery_nos = []\n for i in ipl_matches_array[:,[11,20]]:\n if i[1] == player:\n delivery_nos.append(i[0])\n\n return delivery_nos\n","sub_path":"q02_get_wicket_delivery_numbers_array/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"407209705","text":"\r\n\r\n#Check if server access is available via ssh without password\r\n#Assuming there is a public key file\r\n#convert .ppk to OpenSSH key for paramiko\r\n#Author: Brookly Younce\r\n#Date last modified: 07/29/2019\r\n\r\n\r\n\r\n\r\n# sys for use with command line args\r\n# paramiko for ssh support with windows\r\nimport sys, time, paramiko\r\n\r\n\r\n\r\n\r\ndef connectToHost(line, ssh, ip, hostname, usernameForSSH, key):\r\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n ssh.connect(ip, username=usernameForSSH, pkey=key, look_for_keys=False, allow_agent=False)\r\n stdin, stdout, stderr = ssh.exec_command('pwd')\r\n print(stdout.readline())\r\n\r\n\r\n# arg 1 would be the file name as arg[0] is always the name of the script being run\r\nfileWithServerIPs = sys.argv[1]\r\nfilenameForResults = sys.argv[2]\r\nusernameForSSH = sys.argv[3]\r\nfilePathToKey = sys.argv[4]\r\nprint(\"File to read \", fileWithServerIPs)\r\n\r\ntry:\r\n # make file obj, open only with read rights\r\n fileObj = open(fileWithServerIPs, \"r\")\r\n fileResults = open(filenameForResults, \"a\")\r\n ip = \"\"\r\n hostname = \"\"\r\n connectionError = False\r\n sshClientFailure = False\r\n for line in fileObj:\r\n #IP, hostname\r\n #take all the spaces down to one space, remove duplicates\r\n lineData = \" \".join(line.split())\r\n lineData = line.split()\r\n ip = lineData[1].strip()\r\n hostname = lineData[0].strip()\r\n writeString = \"Connection to IP: \" + ip + \" HOSTNAME: \" + hostname\r\n print(\"\\nAttempting connection to\", ip, hostname)\r\n\r\n try:\r\n connectionError = False\r\n ssh = paramiko.SSHClient()\r\n key = paramiko.RSAKey.from_private_key_file(filename=filePathToKey, password=None)\r\n connectToHost(line, ssh, ip, hostname, usernameForSSH, key)\r\n except Exception as ex:\r\n writeString = \"*** \" + writeString + \" FAILED with \" + str(ex) + \"\\n\"\r\n connectionError = True\r\n finally:\r\n ssh.close()\r\n\r\n if connectionError != True:\r\n writeString = \"*** \" + writeString + \" was SUCCESSFUL\" + \"\\n\"\r\n\r\n fileResults.write(writeString)\r\n print(writeString)\r\n\r\nexcept Exception as e:\r\n print(\"--> An error occurred, see below \\n\\n\\n\")\r\n print(e)\r\n\r\nfinally:\r\n fileObj.close()\r\n fileResults.close()\r\n\r\n\r\n\r\n","sub_path":"CheckAccess.py","file_name":"CheckAccess.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"218802141","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom osv import fields,osv\nimport csv, os\nimport unicodedata\nimport base64\nfrom datetime import datetime\n\n\nclass cardex_cardex(osv.osv_memory):\n _name = 'cardex.cardex'\n _columns = {\n 'product_ids': fields.many2many('product.product', 'cardex_product_rel', 'cardex_id','product_id', 'Productos'),\n 'location_id': fields.many2one('stock.location', 'Ubicacion de Stock'),\n 'date': fields.date('Fecha'), \n 'csv_file' :fields.binary('Csv Report File', readonly=True),\n 'export_filename': fields.char('Export CSV Filename', size=128) \n }\n \n def report_cardex(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n wz = self.browse(cr, uid, ids[-1], context)\n context['product_ids'] = map(lambda x:x.id, wz.product_ids) \n context['date'] = wz.date\n context['location_id'] = wz.location_id \n data = self.__search_stock_move_by_products(cr, uid, ids, context)\n res = self.__create_csv(cr, uid, ids, data, context)\n return {\n 'name': 'Reporte de inventario',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'view_id': [res and res[1] or False],\n 'res_model': 'cardex.cardex',\n 'context': \"{}\",\n 'type': 'ir.actions.act_window',\n 'nodestroy': True,\n 'target': 'new',\n 'res_id': ids[0] or False,##please replace record_id and provide the id of the record to be opened \n }\n\n def special(self,valor):# saco caracteres especiales\n if valor == None:\n return ''\n return str(unicodedata.normalize('NFKD', unicode(valor)).encode('ascii','ignore'))\n\n\n def __create_csv(self, cr, uid, ids, data, context=None):\n path = '/tmp/reporte_inventario.csv'\n fieldnames = ['date', 'description','in','out','residue','pin','pout','presidue']\n pp = self.pool.get('product.product')\n with open(path, 'a') as myfile: \n writer = csv.DictWriter(myfile, delimiter=';',fieldnames=fieldnames) \n x = 0\n for cont in data:\n x+=1\n product = pp.browse(cr, uid, int(cont.keys()[0]))\n writer.writerow({\n 'description':'Codigo: %s' % product.default_code,\n })\n writer.writerow({\n 'description':'Nombre: %s' % self.special(product.name),\n })\n writer.writerow({\n 'out': 'Cantidad',\n 'pout': 'Precio Promedio Unitario',\n })\n writer.writerow({\n 'date': 'Fecha',\n 'description':'Descripcion',\n 'in': 'Entrada',\n 'out': 'Salida',\n 'residue': 'Saldo',\n 'pin': 'Entrada',\n 'pout': 'Salida',\n 'presidue': 'Saldo'\n })\n \n for d in cont[cont.keys()[0]]: \n writer.writerow({\n 'date': datetime.strptime(d['date'][:10],'%Y-%m-%d').strftime('%d-%m-%Y') if d['date'] else '',\n 'description': self.special(d['description']),\n 'in': d['in'],\n 'out': d['out'],\n 'residue': d['residue'],\n 'pin': d['p_in'],\n 'pout': d['p_out'],\n 'presidue': d['p_residue']\n })\n else:\n writer.writerow({\n 'date': '',\n 'description':'',\n 'in': '',\n 'out': '',\n 'residue': '',\n 'pin': '',\n 'pout': '',\n 'presidue': ''\n })\n \n with open(path, 'r') as myfile:\n b64data = base64.b64encode(myfile.read())\n self.write(cr, uid, ids, {'csv_file':b64data}, {})\n self.write(cr, uid, ids, {'export_filename':'reporte_inventario.csv'}, {})\n os.remove(path)\n mod_obj = self.pool.get('ir.model.data')\n res = mod_obj.get_object_reference(cr, uid, 'econube_reporte_stock', 'report_cardex_cardex') \n return res\n\n def validate_uom_product(self, cr, uid, ids, stock, context=None):\n if stock.origin:\n origin = stock.origin[:stock.origin.index(':')] if ':' in stock.origin else stock.origin \n elif 'fv:inventario' in stock.name.lower():\n origin = '/'\n purchase_order = self.pool.get('purchase.order')\n line = []\n if origin and 'po' in origin.lower():\n id = purchase_order.search(cr, uid, [('name','=', origin)], limit=1) \n for order in purchase_order.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id , order.order_line)\n if line and line[0].product_uom.id != stock.product_id.uom_id.id:\n return round(line[0].product_qty / (1/line[0].product_uom.factor_inv)) , round(line[0].product_uom.factor_inv) \n return stock.product_qty, False \n \n def __search_stock_move_by_products(self, cr, uid, ids, context=None):\n stock_obj = self.pool.get('stock.move')\n data_print = []\n for product_id in context['product_ids']:\n if context['location_id']:\n st_ids = stock_obj.search(cr, uid, [('product_id','=', product_id),('state','=', 'done'),('date','<=', context['date']),('location_id','<=', context['location_id'].id)], order = 'date asc',context = context)\n else:\n st_ids = stock_obj.search(cr, uid, [('product_id','=', product_id),('state','=', 'done'),('date','<=', context['date'])], order = 'date asc',context = context)\n if not st_ids:\n continue\n data = {str(product_id): []}\n last_qty = 0\n last_residue = 0\n for stock in stock_obj.browse(cr, uid, st_ids, context):\n if stock.type == 'in':\n d = {\n 'date' : stock.date, \n 'description' : stock.origin,\n 'out' : 0,\n 'p_out' : 0\n }\n qty, factor = self.validate_uom_product(cr, uid, ids, stock, context)\n d['in'] = qty \n price = self.__validate_residual(cr, uid, ids, stock, 'in', context)\n self.validate_factor_price(factor, price, d)\n d['residue'] = last_qty + d['in']\n if not d['p_in'] or d['p_in'] == 0:\n continue\n last_residue = self.__validate_presidual(cr, uid, ids, last_qty, last_residue, d['p_in'], d['in'], stock, 'in', context)\n d['p_residue'] = last_residue \n last_qty += d['in']\n data[str(product_id)].append(d)\n\n elif stock.type == 'out':\n d = {\n 'date' : stock.date, \n 'description' : stock.origin,\n 'in' : 0,\n 'out' : stock.product_qty,\n 'residue' : last_qty - stock.product_qty,\n 'p_in' : 0,\n 'p_out' : self.__validate_residual(cr, uid, ids, stock, 'out', context)\n }\n if not d['p_out']:\n continue\n last_residue = self.__validate_presidual(cr, uid, ids, last_qty, last_residue, d['p_out'], d['in'], stock, 'out', context)\n d['p_residue'] = last_residue \n last_qty -= stock.product_qty\n data[str(product_id)].append(d)\n\n elif 'fv:inventario' in stock.name.lower():\n d = {\n 'date' : stock.date, \n 'description' : stock.name,\n 'out' : 0,\n 'p_out' : 0\n }\n qty, factor = self.validate_uom_product(cr, uid, ids, stock, context)\n d['in'] = qty \n price = self.__validate_residual(cr, uid, ids, stock, 'in', context)\n self.validate_factor_price(factor, price, d)\n d['residue'] = last_qty + d['in']\n last_residue = self.__validate_presidual(cr, uid, ids, last_qty, last_residue, d['p_in'], d['in'], stock, 'in', context)\n d['p_residue'] = last_residue \n last_qty += d['in']\n data[str(product_id)].append(d)\n data_print.append(data) \n return data_print\n \n def validate_factor_price(self, factor, price, d):\n if factor:\n d['p_in'] = price * (1/factor)\n else:\n d['p_in'] = price if price else 0\n\n \n def __validate_residual(self, cr, uid, ids, stock, type, context=None):\n \n if stock.origin:\n origin = stock.origin[:stock.origin.index(':')] if ':' in stock.origin else stock.origin \n elif 'fv:inventario' in stock.name.lower():\n origin = '/'\n invoice = self.pool.get('account.invoice')\n if type == 'in':\n if 'fact' in origin.lower():\n id = invoice.search(cr, uid, [('number','=', origin)], limit=1)\n for inv in invoice.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id , inv.invoice_line)\n return line[0].price_unit\n return 1\n\n elif 'po' in origin.lower():\n purchase_order = self.pool.get('purchase.order')\n id = purchase_order.search(cr, uid, [('name','=', origin)], limit=1) \n for order in purchase_order.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id , order.order_line)\n return line[0].price_unit\n return 1 \n\n elif 'trans' in origin.lower() or 'bol' in origin.lower(): \n pos_order = self.pool.get('pos.order')\n id = pos_order.search(cr, uid, [('name','=', origin)], limit=1)\n for order in pos_order.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id , order.lines)\n return line[0].price_unit\n return 1\n\n elif origin.lower() == '/' and stock.picking_id:\n account_move = self.pool.get('account.move')\n id = account_move.search(cr, uid, [('ref','=', stock.picking_id.name),('amount','>', 0)]) \n for order in account_move.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id and x.debit >0, order.line_id)\n if line:\n return line[0].debit / stock.product_qty\n return 1\n\n elif type == 'out': \n if stock.name:\n cr.execute(\"\"\"\n select debit from account_move_line \n where name = '%s' \n and account_id = 2262\n and debit >0\n and product_id = %d\n order by id desc limit 1\n \"\"\"% (stock.name, stock.product_id.id))\n price = cr.fetchone()\n if price and price[0] is not None:\n return price[0]\n \n if 'fact' in origin.lower():\n id = invoice.search(cr, uid, [('number','=', origin)], limit=1)\n for inv in invoice.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id , inv.invoice_line)\n if line:\n return line[0].price_unit\n\n elif 'trans' in origin.lower() or 'bol' in origin.lower(): \n pos_order = self.pool.get('pos.order')\n id = pos_order.search(cr, uid, [('name','=', origin)], limit=1)\n for order in pos_order.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id , order.lines)\n if line:\n return line[0].price_unit\n elif 'nv' in origin.lower():\n sale_order = self.pool.get('sale.order')\n id = sale_order.search(cr, uid, [('name','=', origin)], limit=1) \n for order in sale_order.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id , order.order_line)\n if line:\n return line[0].price_unit\n\n elif origin.lower() == '/' and stock.picking_id:\n account_move = self.pool.get('account.move')\n id = account_move.search(cr, uid, [('ref','=', stock.picking_id.name),('amount','>', 0)]) \n for order in account_move.browse(cr, uid, id, context):\n line = filter( lambda x:x.product_id.id == stock.product_id.id and x.credit >0, order.line_id)\n if line:\n return line[0].credit / stock.product_qty\n return stock.product_id.list_price\n return False\n \n def __validate_presidual(self, cr, uid, ids, last_qty, last_residue, price, qty, stock, type, context):\n if type == 'in':\n if last_qty + qty != 0:\n return (qty * price + \n last_qty * last_residue\n )/ (last_qty + qty)\n else:\n return (qty * price + \n last_qty * last_residue\n )/ 1\n \n elif type == 'out':\n if last_qty - stock.product_qty != 0:\n return ( last_qty * last_residue)/ (last_qty - stock.product_qty)\n else:\n return ( last_qty * last_residue)/ 1\ncardex_cardex()","sub_path":"models/cardex.py","file_name":"cardex.py","file_ext":"py","file_size_in_byte":15680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"556396355","text":"# setup.py\n# -*- coding: UTF-8 -*-\n# vi:si:et:sw=4:sts=4:ts=4\ntry:\n from setuptools import setup\nexcept:\n from distutils.core import setup\n\ndef get_version():\n return 34 #import subprocess\n rev = subprocess.check_output(['git', 'rev-list', 'HEAD', '--count']).strip()\n return rev or u'unknown'\n\nsetup(name='oxtimelines',\n version='0.%s' % get_version() ,\n scripts=[\n 'bin/oxtimelines',\n ],\n packages=[\n 'oxtimelines',\n ],\n author='0x2620',\n author_email='0x2620@0x2620.org',\n url=\"https://wiki.0x2620.org/wiki/oxtimelines\",\n download_url=\"http://code.0x2620.org/oxtimelines/download\",\n license=\"GPLv3\",\n description='extract timelines from videos',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Utilities'\n ],\n)\n\n","sub_path":"pypi_install_script/oxtimelines-0.34.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"451754796","text":"# coding=utf-8\nimport json\nimport urllib\n\nimport telegram\nfrom bs4 import BeautifulSoup\n\n\ndef run(bot, chat_id, user, keyConfig, message, totalResults=1):\n requestText = message.replace(bot.name, \"\").strip()\n airportCode, error = get_airport_code(requestText)\n if airportCode != 'No matching entries found...':\n bot.sendMessage(chat_id=chat_id, text=airportCode)\n return True\n else:\n if error:\n bot.sendMessage(chat_id=chat_id,\n text='I\\'m sorry ' + (user if not user == '' else 'Dave') +\n error)\n else:\n bot.sendMessage(chat_id=chat_id,\n text='I\\'m sorry ' + (user if not user == '' else 'Dave') +\n ', I\\'m afraid I can\\'t quite place ' + requestText.encode('utf-8') + '.')\n\n\ndef get_airport_code(cityName):\n airportsUrl = 'http://www.webflyer.com/travel/milemarker/getmileage_ft.cgi?city='\n realUrl = airportsUrl + cityName.encode('utf-8')\n code = urllib.urlopen(realUrl).read()\n data = BeautifulSoup(code, 'html.parser')\n error = data.find('b').string\n rawAirportCode = str(data.findAll('b')[1]) if error != 'No matching entries found...' else ''\n airportCode = rawAirportCode[4:rawAirportCode.index(')
')] if len(rawAirportCode) > 15 else ''\n return airportCode, error.replace('Here are the results of your search:', '')","sub_path":"commands/getflight.py","file_name":"getflight.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"257608742","text":"import http.client\nimport json\nimport os\nimport re\nimport unittest\n\nfrom httpserver import Package\n\n\nclass HttpClient(object):\n def __init__(self):\n API_DOMAIN = 'localhost:'+str(os.environ.get('PORT', '8080'))\n self.conn = http.client.HTTPConnection(API_DOMAIN)\n\n\nclass TestPakage(unittest.TestCase):\n def testPackage(self):\n json_data_error = '''{\n \"name\": \"Magic Mouse\",\n \"height\": \"0,75\",\n \"length\": \"1,10\",\n asdfsadsfasfda\n \"width\": \"0,60\",\n fasdfa \"price\": \"150,00\"\n }'''\n package = Package().fromString(json_data_error)\n self.assertEqual(package, 'ERRO: FORMATO DO PACOTE INVALIDO')\n\n json_data = '''{\n \"name\": \"Magic Mouse\",\n \"height\": \"0,75\",\n \"length\": \"1,10\",\n \"width\": \"0,60\",\n \"weight\": \"400\",\n \"price\": \"150,00\"\n }'''\n dict = {\n \"name\": \"Magic Mouse\",\n \"height\": \"0,75\",\n \"length\": \"1,10\",\n \"width\": \"0,60\",\n \"weight\": \"400\",\n \"price\": \"150,00\"\n }\n package = Package().fromString(json_data)\n self.assertEqual(package.toDict(), package.toDict())\n\n package = Package().fromString(json_data)\n self.assertEqual(json.loads(package.toJson()), json.loads(json_data))\n\n\n\n\n def testCalcTax(self):\n json_data = '''{\n \"name\": \"Magic Mouse\",\n \"height\": \"0,75\",\n \"length\": \"1,10\",\n \"width\": \"0,60\",\n \"weight\": \"400\",\n \"price\": \"150,00\"\n }'''\n package = Package().fromString(json_data)\n package.calcTax()\n self.assertEqual(package.tax, \"59,40\")\n\n\n\n\n\nclass TestHttpServer(unittest.TestCase):\n\n def testEndpointTax(self):\n headers = {'Content-type': 'application/json'}\n json_data = '''{\n \"name\": \"Magic Mouse\",\n \"height\": \"0,75\",\n \"length\": \"1,10\",\n \"width\": \"0,60\",\n \"weight\": \"400\",\n \"price\": \"150,00\"\n }'''\n\n httpClient = HttpClient()\n httpClient.conn.request('POST', '/tax', json_data, headers)\n response = httpClient.conn.getresponse()\n self.assertEqual(response.read().decode(), '''{\"tax\":\"59.40\"}''')\n\n def testEndpointTrack(self):\n headers = {'Content-type': 'application/json'}\n json_data = '''{\n \"name\": \"Magic Mouse\",\n \"height\": \"0,75\",\n \"length\": \"1,10\",\n \"width\": \"0,60\",\n \"weight\": \"400\",\n \"price\": \"150,00\"\n }'''\n\n httpClient = HttpClient()\n httpClient.conn.request('POST', '/track', json_data, headers)\n response = httpClient.conn.getresponse().read().decode()\n self.assertTrue(re.match(\"{ \\\"id\\\" :\\\"[A-Za-z0-9]+\\\" }$\", response))\n\n\n\n def testEndpointTrackId(self):\n headers = {'Content-type': 'application/json'}\n ENDPOINT = '/track/5d62b1761223a5512304c906'\n\n httpClient = HttpClient()\n httpClient.conn.request('GET', ENDPOINT,' ', headers)\n response = httpClient.conn.getresponse().read().decode()\n self.assertEqual(response,'''{\"id\": \"5d62b1761223a5512304c906\", \"name\": \"Magic Mouse\", \"height\": \"0,75\", \"length\": \"1,10\", \"width\": \"0,60\", \"weight\": \"400\", \"price\": \"150,00\", \"tax\": \"59,40\"}''')\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"548373237","text":"import pygame\nimport re\nclass ModelHandler:\n def __init__(self,modelRoot=None):\n self.modelRoot=modelRoot\n self.testDot = [pygame.color.THECOLORS['green'],(10.0,10.0),6,0]\n self.velocity = [100.4,100.3] #px per second\n def loadMode(self,mode):\n self.modelRoot=convertModel(mode.model.deepcopy())\n\ndef convertModel(node):\n if isinstance(node,list):\n for i in range(len(node)):\n node[i] = convertModel(node[i])\n elif isinstance(node,dict):\n for key in node.keys():\n node[key] = convertModel(node[key])\n else:\n if re.fullmatch('\\d+',node):\n return int(node)\n elif re.fullmatch('\\d*\\.\\d+',node):\n return float(node)\n else:\n return node\n","sub_path":"elemental/model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"3502957","text":"import cProfile\n\n# Project Euler 1: Multiples of 3 and 5\n\ndef multThree (n):\n sum = 0\n for i in range(n):\n if i % 3 == 0 or i % 5 == 0:\n sum += i\n return sum\n\nprint(multThree(1000))\ncProfile.run('multThree(1000)')\n\n","sub_path":"001-fizzbuzz.py","file_name":"001-fizzbuzz.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"424416994","text":"import neural_network\nimport data\n\n\n\n\n\nlearning_rate = float(input(\"Unesite learning rate: \"))\nprint(\"Odaberite aktivacionu f-ju za skriveni i izlazni sloj:\")\nprint(\"1 - sigmoidna f-ja\")\nprint(\"2 - tanges hiperbolna f-ja\")\nprint(\"3 - RLU f-ja\")\nprint(\"4 - LRLU f-ja\")\nactivation_function_for_hidden = int(input(\"Vas izbor za skriveni sloj: \"))\nactivation_function_for_output = int(input(\"Vas izbor za izlazni sloj: \"))\n\n\n\nnn = neural_network.NeuralNetwork(learning_rate,activation_function_for_hidden,activation_function_for_output)\n\n\n# training neural network \nnumber_of_iterations = 1000\nnumber_of_instances = 100\nX,Y = data.generate_data(number_of_instances)\nnn.train(X,Y,number_of_iterations)\n\n\n#testing neural network\nx = [[3,1,2]]\ny = [[0.47, 0.66, 0.51]]\nnn.test(x,y)\n\n\n\n\n\n\n\n\t\n\t\n\n\n\n\n\n","sub_path":"neural_network/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"21528659","text":"command = '' # set empty command\nreplaceCount = 0 # set counter of letters\ndictOfSimbols = {} # set empty dictionary\n\n# edit the entered sentence\ndef enterSentence(originalSentence):\n originalSentence = originalSentence.upper() # make all letters in the sentence UPPER\n newSentence = originalSentence.strip()\n return newSentence\n\n# the main functional part is replace letters in a sentence\ndef replaceLetters(existSentence, existLetter, needLetter):\n needSentence = ''\n\n for i in range(len(existSentence)):\n\n if existSentence[i] == existLetter:\n needSentence = needSentence + needLetter\n elif existSentence[i] == needLetter:\n needSentence = needSentence + existLetter\n else:\n needSentence = needSentence + existSentence[i]\n\n return needSentence\n\n# the main operation of changing letters, collect the entered letters\ndef replaceMain(existSentence):\n global dictSim1, dictSim2, dictOfSimbols,replaceCount\n existLetter = input('The letter: ').upper()\n needLetter = input('is equal: ').upper()\n\n replaceCount += 1\n # change the symbols, original part\n dictOfSimbols[replaceCount] = [existLetter,needLetter]\n needSentence = replaceLetters(existSentence, existLetter, needLetter)\n return needSentence\n\n# one step back\ndef undo():\n global replaceCount, dictOfSimbols, newSentence\n\n if replaceCount != 0:\n key = replaceCount\n replaceCount -= 1\n oldLetter = dictOfSimbols[key]\n newSentence = replaceLetters(newSentence,oldLetter[0],oldLetter[1])\n return newSentence\n else:\n print(\"Nothing to undo\")\n return newSentence\n\n# cancel step back\ndef redo():\n global replaceCount, dictOfSimbols, newSentence\n\n try:\n replaceCount += 1\n key = replaceCount\n oldLetter = dictOfSimbols[key]\n newSentence = replaceLetters(newSentence,oldLetter[0],oldLetter[1])\n return newSentence\n except KeyError:\n print(\"Nothing to redo\")\n return newSentence\n\n\noriginal = input('Enter the sentence: ') # enter the original sentence\nnewSentence = enterSentence(original)\nwhile command != 'exit':\n if command == 'undo':\n newSentence = undo()\n print('\\n' + newSentence)\n elif command == 'redo':\n newSentence = redo()\n print('\\n' + newSentence)\n else:\n newSentence = replaceMain(newSentence)\n print('\\n' + newSentence)\n\n print()\n command = input('Enter the EXIT to exit\\nEnter the UNDO to cancel last letters\\nor press ENTER to continue ')\n command = command.lower()\n print()","sub_path":"kriptogramm_V2.py","file_name":"kriptogramm_V2.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"602529971","text":"#Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).\n#If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.\n\n#For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.\n\n#Evaluate the sum of all the amicable numbers under 10000.\n\ndef get_prime_divs(x):\n divs = list()\n while x > primes[len(primes)-1]:\n next(a)\n if x in primes:\n return([x])\n else:\n _ = x\n for i in [a for a in primes if a < x ** 0.5 + 1]:\n while _ % i == 0:\n divs.append(i)\n _ /= i\n if _ == 1:\n break\n return(divs)\n\ndiv_list = []\ndivdict = {1: [1]}\n\ndef get_divs(x):\n divlist = []\n while x > primes[len(primes)-1]:\n next(a)\n if x in primes:\n divdict.update({x:[x]})\n else:\n for y in [a for a in primes if a < x ** 0.5 + 1]:\n if x % y == 0:\n divlist.append(y)\n if int(x/y) not in divdict:\n get_divs(int(x/y))\n for z in divdict[int(x/y)]:\n if z not in divlist:\n divlist.append(z)\n if z * y not in divlist:\n divlist.append(z*y)\n divdict.update({x:divlist})\n return(divdict[x])\n\nprimes = [2]\n\ncurr = 3\n\ndef gen_next_prime():\n while 1:\n global curr\n for z in primes:\n if z > curr ** 0.5:\n primes.append(curr)\n yield\n break\n if curr % z == 0:\n break\n curr += 1\n\na = gen_next_prime()\n\nddict = {1:1}\n\nfor num in range(2,10**4 + 1):\n get_divs(num)\n\nfor num in range(2,10**4 + 1):\n divdict[num] = set(divdict[num])\n divdict[num].add(1)\n divdict[num] = divdict[num] - {num}\n\nfor num in range(2,10**4 + 1):\n ddict.update({num:sum(divdict[num])})\n\namicable = []\n\nfor x in ddict:\n try:\n if x == ddict[ddict[x]] and x != ddict[x]:\n amicable.append(x)\n except KeyError:\n pass\n\nsum = 0\n\nfor x in amicable:\n sum += x\n\nprint(sum)\n\n","sub_path":"21.py","file_name":"21.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"343278057","text":"from pcinput import getString\r\nwhile True:\r\n x= getString(\"enter a string: \")\r\n y=bool(x)\r\n if y==True:\r\n count=1\r\n run=1\r\n run1=1\r\n temp=\"\"\r\n temp1=\"\"\r\n for i in x:\r\n if temp==i:\r\n if temp1!= i and count!=1:\r\n count+=1\r\n count+=1\r\n run+=1\r\n if run>run1:\r\n run1=run\r\n temp1=i\r\n else:\r\n run=1\r\n temp=i\r\n if count>1:\r\n print(\"{} {}{}{} {}\".format(\"count\",count,\"\\n\",\"max\",run1))\r\n else:\r\n print(\"{} {}{}{} {}\".format(\"count\",\"0\",\"\\n\",\"max\",\"0\"))\r\n else:\r\n print(\"{} {}{}{} {}\".format(\"count\",\"0\",\"\\n\",\"max\",\"0\"))\r\n break\r\n","sub_path":"CountConsecutiveChars.py","file_name":"CountConsecutiveChars.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"128743813","text":"import random\nimport json\n\ndef leerCoordenadas():\n \"\"\" Crea un archivos de coordenadas leidas desde teclado y lo retorna\"\"\"\n\n f = open('coordenadas.txt', 'w')\n for i in range(1,6):\n c = input(\"Coordenada: \")\n f.write(c + '\\n')\n f.close()\n return f\n\n# Abro los archivos\narchivoDeCoordenadas = open(leerCoordenadas().name, 'r')\narchivoDeColores = open('colores.txt', 'r')\n\n# Función anónima para borrar los saltos de linea\nextraerDato = lambda x: x.strip('\\n')\n\n# Paso los datos a listas\ncoordenadas = list(map(extraerDato, archivoDeCoordenadas))\ncolores = list(map(extraerDato, archivoDeColores))\n\n# Cierro los archivos\narchivoDeColores.close()\narchivoDeCoordenadas.close()\n\n# Asocio aleatoriamente\ndic = {}\nfor coord in coordenadas:\n color = colores[random.randint(0, 4)]\n while color in dic.values():\n color = colores[random.randint(0, 4)]\n dic[eval(coord)] = color\nprint('Diccionario generado: \\n' + str(dic) + '\\n')\n\n# Exporto a JSON\narchivoJSON = open('archivoJSON.json', 'w')\njson.dump(dic, archivoJSON, indent = 4)\nprint(\"Diccionario exportado en archivo json\")\n\n# Guardar la coordenada como una tupla me genera un error al exportar a JSON.\n# Si lo guardo como string, funciona, pero pierdo los parentesis si no los agrego explicitamente.\n","sub_path":"Practica3/Ejercicio2/Ejercicio2.py","file_name":"Ejercicio2.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"509268254","text":"import socket\nimport argparse\nfrom sys import stdin\n\n# Define a constant for our buffer size\n\nBUFFER_SIZE = 2048\n\n# Our main function.\n\ndef main():\n\n # Check command line arguments to retrieve a URL.\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"host\", help=\"Host name of server\")\n parser.add_argument(\"port\", help=\"Port number of server\")\n args = parser.parse_args()\n host = args.host\n port = int(args.port)\n\n # Now we try to make a connection to the server.\n\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n for line in stdin:\n client_socket.sendto(line.rstrip().encode(), (host,port))\n client_socket.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"app/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"414857651","text":"import ray\nfrom ray import train\nfrom ray.train import DataConfig, ScalingConfig\nfrom ray.train.torch import TorchTrainer\n\nimport torch.distributed as dist\nimport numpy as np\n\nfrom benchmark import Benchmark, BenchmarkMetric\n\n\nimport time\nimport torchvision\nimport torch\n\n\n# This benchmark does the following:\n# 1) Read files (images or parquet) with ray.data\n# 2) Apply preprocessing with map_batches()\n# 3) Train TorchTrainer on processed data\n# Metrics recorded to the output file are:\n# - ray.torchtrainer.fit: Throughput of the final epoch in\n# TorchTrainer.fit() (step 3 above)\n\n\ndef parse_args():\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--data-root\", type=str, help=\"Root of data directory\")\n parser.add_argument(\n \"--read-local\",\n action=\"store_true\",\n default=False,\n help=\"Whether to read from local fs for default datasource (S3 otherwise)\",\n )\n parser.add_argument(\n \"--file-type\",\n default=\"image\",\n type=str,\n help=\"Input file type; choose from: ['image', 'parquet']\",\n )\n parser.add_argument(\n \"--repeat-ds\",\n default=1,\n type=int,\n help=\"Read the input dataset n times, used to increase the total data size.\",\n )\n parser.add_argument(\n \"--read-task-cpus\",\n default=1,\n type=int,\n help=\"Number of CPUs specified for read task\",\n )\n parser.add_argument(\n \"--batch-size\",\n default=32,\n type=int,\n help=\"Batch size to use.\",\n )\n parser.add_argument(\n \"--num-epochs\",\n # Use 3 epochs and report the throughput of the last epoch, in case\n # there is warmup in the first epoch.\n default=3,\n type=int,\n help=\"Number of epochs to run. The throughput for the last epoch will be kept.\",\n )\n parser.add_argument(\n \"--num-workers\",\n default=1,\n type=int,\n help=\"Number of workers.\",\n )\n parser.add_argument(\n \"--use-gpu\",\n action=\"store_true\",\n default=False,\n help=\"Whether to use GPU with TorchTrainer.\",\n )\n parser.add_argument(\n \"--local-shuffle-buffer-size\",\n default=200,\n type=int,\n help=\"Parameter into ds.iter_batches(local_shuffle_buffer_size=...)\",\n )\n parser.add_argument(\n \"--preserve-order\",\n action=\"store_true\",\n default=False,\n help=\"Whether to configure Train with preserve_order flag.\",\n )\n args = parser.parse_args()\n\n if args.data_root is None:\n # use default datasets if data root is not provided\n if args.file_type == \"image\":\n # 1GB ragged dataset\n args.data_root = \"s3://imagenetmini1000/1gb/train/\"\n\n # Alternative larger dataset\n # args.data_root = \"s3://air-example-data-2/10G-image-data-synthetic-raw\" # noqa: E501\n\n elif args.file_type == \"parquet\":\n args.data_root = (\n \"s3://air-example-data-2/20G-image-data-synthetic-raw-parquet\"\n )\n else:\n raise Exception(\n f\"Unknown file type {args.file_type}; \"\n \"expected one of: ['image', 'parquet']\"\n )\n if args.repeat_ds > 1:\n args.data_root = [args.data_root] * args.repeat_ds\n return args\n\n\n# Constants and utility methods for image-based benchmarks.\nDEFAULT_IMAGE_SIZE = 224\n\n\ndef get_transform(to_torch_tensor):\n # Note(swang): This is a different order from tf.data.\n # torch: decode -> randCrop+resize -> randFlip\n # tf.data: decode -> randCrop -> randFlip -> resize\n transform = torchvision.transforms.Compose(\n [\n torchvision.transforms.RandomResizedCrop(\n size=DEFAULT_IMAGE_SIZE,\n scale=(0.05, 1.0),\n ratio=(0.75, 1.33),\n ),\n torchvision.transforms.RandomHorizontalFlip(),\n ]\n + ([torchvision.transforms.ToTensor()] if to_torch_tensor else [])\n )\n return transform\n\n\ndef crop_and_flip_image(row):\n transform = get_transform(False)\n # Make sure to use torch.tensor here to avoid a copy from numpy.\n row[\"image\"] = transform(torch.tensor(np.transpose(row[\"image\"], axes=(2, 0, 1))))\n return row\n\n\ndef train_loop_per_worker():\n it = train.get_dataset_shard(\"train\")\n device = train.torch.get_device()\n\n for i in range(args.num_epochs):\n print(f\"Epoch {i+1} of {args.num_epochs}\")\n num_rows = 0\n start_t = time.time()\n for batch in it.iter_torch_batches(\n batch_size=args.batch_size,\n ):\n num_rows += args.batch_size\n end_t = time.time()\n\n # Workaround to report the final epoch time from each worker, so that we\n # can sum up the times at the end when calculating throughput.\n world_size = ray.train.get_context().get_world_size()\n all_workers_time_list = [\n torch.zeros((2), dtype=torch.double, device=device) for _ in range(world_size)\n ]\n curr_worker_time = torch.tensor([start_t, end_t], dtype=torch.double, device=device)\n dist.all_gather(all_workers_time_list, curr_worker_time)\n\n all_num_rows = [\n torch.zeros((1), dtype=torch.int32, device=device) for _ in range(world_size)\n ]\n curr_num_rows = torch.tensor([num_rows], dtype=torch.int32, device=device)\n dist.all_gather(all_num_rows, curr_num_rows)\n\n train.report(\n {\n \"time_final_epoch\": [tensor.tolist() for tensor in all_workers_time_list],\n \"num_rows\": [tensor.item() for tensor in all_num_rows],\n }\n )\n\n\ndef benchmark_code(\n args,\n cache_output_ds=False,\n cache_input_ds=False,\n):\n \"\"\"\n - cache_output_ds: Cache output dataset (ds.materialize()) after preprocessing fn.\n - cache_input_ds: Cache input dataset, then apply a preprocessing fn.\n \"\"\"\n assert (\n sum([cache_output_ds, cache_input_ds]) <= 1\n ), \"Can only test one caching variant at a time\"\n\n # 1) Read in data with read_images() / read_parquet()\n if args.file_type == \"image\":\n ray_dataset = ray.data.read_images(\n args.data_root,\n mode=\"RGB\",\n )\n elif args.file_type == \"parquet\":\n ray_dataset = ray.data.read_parquet(\n args.data_root,\n )\n else:\n raise Exception(f\"Unknown file type {args.file_type}\")\n\n if cache_input_ds:\n ray_dataset = ray_dataset.materialize()\n\n # 2) Preprocess data by applying transformation with map/map_batches()\n ray_dataset = ray_dataset.map(crop_and_flip_image)\n if cache_output_ds:\n ray_dataset = ray_dataset.materialize()\n\n # 3) Train TorchTrainer on processed data\n options = DataConfig.default_ingest_options()\n options.preserve_order = args.preserve_order\n\n if args.num_workers == 1 or args.use_gpu:\n torch_trainer = TorchTrainer(\n train_loop_per_worker,\n datasets={\"train\": ray_dataset},\n scaling_config=ScalingConfig(\n num_workers=args.num_workers,\n use_gpu=args.use_gpu,\n ),\n dataset_config=ray.train.DataConfig(\n execution_options=options,\n ),\n )\n else:\n torch_trainer = TorchTrainer(\n train_loop_per_worker,\n datasets={\"train\": ray_dataset},\n # In the multi-node case without GPUs, we use a SPREAD placement strategy\n # to ensure that tasks are spread across nodes. We reserve one worker\n # for the driver.\n scaling_config=ScalingConfig(\n num_workers=args.num_workers - 1,\n use_gpu=args.use_gpu,\n placement_strategy=\"STRICT_SPREAD\",\n ),\n dataset_config=ray.train.DataConfig(\n execution_options=options,\n ),\n )\n\n result = torch_trainer.fit()\n\n # Report the throughput of the last epoch, sum runtime across all workers.\n time_start_last_epoch, time_end_last_epoch = zip(\n *result.metrics[\"time_final_epoch\"]\n )\n runtime_last_epoch = max(time_end_last_epoch) - min(time_start_last_epoch)\n num_rows_last_epoch = sum(result.metrics[\"num_rows\"])\n tput_last_epoch = num_rows_last_epoch / runtime_last_epoch\n\n return {\n BenchmarkMetric.THROUGHPUT.value: tput_last_epoch,\n }\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n benchmark_name = (\n f\"read_{args.file_type}_repeat{args.repeat_ds}_train_{args.num_workers}workers\"\n )\n if args.preserve_order:\n benchmark_name = f\"{benchmark_name}_preserve_order\"\n\n benchmark = Benchmark(benchmark_name)\n\n benchmark.run_fn(\"cache-none\", benchmark_code, args=args)\n benchmark.run_fn(\"cache-output\", benchmark_code, args=args, cache_output_ds=True)\n benchmark.run_fn(\"cache-input\", benchmark_code, args=args, cache_input_ds=True)\n # TODO: enable after implementing prepartition case.\n # benchmark.run_fn(\n # \"prepartition-ds\", benchmark_code, args=args, prepartition_ds=True,\n # )\n benchmark.write_result(\"/tmp/multi_node_train_benchmark.json\")\n","sub_path":"release/nightly_tests/dataset/multi_node_train_benchmark.py","file_name":"multi_node_train_benchmark.py","file_ext":"py","file_size_in_byte":9154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"491207074","text":"# coding=UTF-8\nimport argparse\nimport sys\nimport logging\nimport math\nimport numpy as np\nimport os\nimport pandas as pd\nimport pickle\nimport json\nimport six\n\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../../\"))\nfrom duplicate_questions.data.data_manager import DataManager\nfrom duplicate_questions.data.embedding_manager import EmbeddingManager\nfrom duplicate_questions.data.instances.weizhong_instance import WeizhongInstance\nfrom duplicate_questions.models.siamese_bilstm.siamese_bilstm import SiameseBiLSTM\nfrom duplicate_questions.data.data_indexer import DataIndexer\n\nif six.PY2:\n reload(sys)\n sys.setdefaultencoding('utf-8')\n\nlogger = logging.getLogger(__name__)\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\n\n\ndef main():\n project_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)\n\n # Parse config arguments\n argparser = argparse.ArgumentParser(\n description=(\"Run a baseline Siamese BiLSTM model \"\n \"for paraphrase identification.\"))\n argparser.add_argument(\"mode\", type=str,\n choices=[\"train\", \"predict\"],\n help=(\"One of {train|predict}, to \"\n \"indicate what you want the model to do. \"\n \"If you pick \\\"predict\\\", then you must also \"\n \"supply the path to a pretrained model and \"\n \"DataIndexer to load.\"))\n argparser.add_argument(\"--model_load_dir\", type=str,\n default=os.path.join(project_dir,\n \"models/\"),\n help=(\"The path to a directory with checkpoints to \"\n \"load for evaluation or prediction. The \"\n \"latest checkpoint will be loaded.\"))\n argparser.add_argument(\"--dataindexer_load_path\", type=str,\n default=os.path.join(project_dir,\n \"models/\"),\n help=(\"The path to the dataindexer fit on the \"\n \"train data, so we can properly index the \"\n \"test data for evaluation or prediction.\"))\n argparser.add_argument(\"--train_file\", type=str,\n default=os.path.join(project_dir,\n \"data/processed/weizhong/\"\n \"weizhong_train_train_split.txt\"),\n help=\"Path to a file to train on.\")\n argparser.add_argument(\"--val_file\", type=str,\n default=os.path.join(project_dir,\n \"data/processed/weizhong/\"\n \"weizhong_train_val_split.txt\"),\n help=\"Path to a file to monitor validation acc. on.\")\n argparser.add_argument(\"--test_file\", type=str,\n default=os.path.join(project_dir,\n \"data/raw/\"\n \"weizhong_dev.txt\"))\n argparser.add_argument(\"--batch_size\", type=int, default=512,\n help=\"Number of instances per batch.\")\n argparser.add_argument(\"--num_epochs\", type=int, default=200,\n help=(\"Number of epochs to perform in \"\n \"training.\"))\n argparser.add_argument(\"--early_stopping_patience\", type=int, default=100,\n help=(\"number of epochs with no validation \"\n \"accuracy improvement after which training \"\n \"will be stopped\"))\n argparser.add_argument(\"--num_sentence_words\", type=int, default=25,\n help=(\"The maximum length of a sentence. Longer \"\n \"sentences will be truncated, and shorter \"\n \"ones will be padded.\"))\n argparser.add_argument(\"--word_embedding_dim\", type=int, default=300,\n help=\"Dimensionality of the word embedding layer\")\n argparser.add_argument(\"--pretrained_embeddings_file_path\", type=str,\n help=\"Path to a file with pretrained embeddings.\",\n default=os.path.join(project_dir,\n \"data/external/\",\n \"word2vec_finance_train_use.txt\"))\n argparser.add_argument(\"--fine_tune_embeddings\", action=\"store_true\",\n help=(\"Whether to train the embedding layer \"\n \"(if True), or keep it fixed (False).\"))\n argparser.add_argument(\"--rnn_hidden_size\", type=int, default=256,\n help=(\"The output dimension of the RNN.\"))\n argparser.add_argument(\"--share_encoder_weights\", action=\"store_true\",\n help=(\"Whether to use the same encoder on both \"\n \"input sentences (thus sharing weights), \"\n \"or a different one for each sentence\"))\n argparser.add_argument(\"--rnn_output_mode\", type=str, default=\"last\",\n choices=[\"mean_pool\", \"last\"],\n help=(\"How to calculate the final sentence \"\n \"representation from the RNN outputs. \"\n \"\\\"mean_pool\\\" indicates that the outputs \"\n \"will be averaged (with respect to padding), \"\n \"and \\\"last\\\" indicates that the last \"\n \"relevant output will be used as the \"\n \"sentence representation.\"))\n argparser.add_argument(\"--output_keep_prob\", type=float, default=0.9,\n help=(\"The proportion of RNN outputs to keep, \"\n \"where the rest are dropped out.\"))\n argparser.add_argument(\"--log_period\", type=int, default=10,\n help=(\"Number of steps between each summary \"\n \"op evaluation.\"))\n argparser.add_argument(\"--val_period\", type=int, default=250,\n help=(\"Number of steps between each evaluation of \"\n \"validation performance.\"))\n argparser.add_argument(\"--log_dir\", type=str,\n default=os.path.join(project_dir,\n \"logs/\"),\n help=(\"Directory to save logs to.\"))\n argparser.add_argument(\"--save_period\", type=int, default=250,\n help=(\"Number of steps between each \"\n \"model checkpoint\"))\n argparser.add_argument(\"--save_dir\", type=str,\n default=os.path.join(project_dir,\n \"models/\"),\n help=(\"Directory to save model checkpoints to.\"))\n argparser.add_argument(\"--run_id\", type=str, required=True,\n help=(\"Identifying run ID for this run. If \"\n \"predicting, you probably want this \"\n \"to be the same as the train run_id\"))\n argparser.add_argument(\"--model_name\", type=str, required=True,\n help=(\"Identifying model name for this run. If\"\n \"predicting, you probably want this \"\n \"to be the same as the train run_id\"))\n argparser.add_argument(\"--reweight_predictions_for_kaggle\", action=\"store_true\",\n help=(\"Only relevant when predicting. Whether to \"\n \"reweight the prediction probabilities to \"\n \"account for class proportion discrepancy \"\n \"between train and test.\"))\n\n config = argparser.parse_args()\n\n model_name = config.model_name\n run_id = config.run_id\n mode = config.mode\n\n # Get the data.\n batch_size = config.batch_size\n if mode == \"train\":\n # Read the train data from a file, and use it to index the validation data\n data_manager = DataManager(WeizhongInstance)\n num_sentence_words = config.num_sentence_words\n get_train_data_gen, train_data_size = data_manager.get_train_data_from_file(\n [config.train_file], min_count=2,\n max_lengths={\"num_sentence_words\": num_sentence_words})\n get_val_data_gen, val_data_size = data_manager.get_validation_data_from_file(\n [config.val_file], max_lengths={\"num_sentence_words\": num_sentence_words})\n else:\n # Load the fitted DataManager, and use it to index the test data\n logger.info(\"Loading pickled DataManager \"\n \"from {}\".format(config.dataindexer_load_path))\n\n config.dataindexer_load_path = os.path.join(config.dataindexer_load_path, config.model_name,\n config.run_id.zfill(2), config.model_name + \"-\" + config.run_id.zfill(2) + \"-\" + \"DataManager.pkl\")\n\n data_manager = pickle.load(open(config.dataindexer_load_path, \"rb\"))\n test_data_gen, test_data_size = data_manager.get_test_data_from_file(\n [config.test_file])\n\n vars(config)[\"word_vocab_size\"] = data_manager.data_indexer.get_vocab_size()\n\n # Log the run parameters.\n log_dir = config.log_dir\n log_path = os.path.join(log_dir, model_name, run_id.zfill(2))\n logger.info(\"Writing logs to {}\".format(log_path))\n if not os.path.exists(log_path):\n logger.info(\"log path {} does not exist, \"\n \"creating it\".format(log_path))\n os.makedirs(log_path)\n params_path = os.path.join(log_path, mode + \"params.json\")\n logger.info(\"Writing params to {}\".format(params_path))\n with open(params_path, 'w') as params_file:\n json.dump(vars(config), params_file, indent=4)\n\n # Get the embeddings.\n embedding_manager = EmbeddingManager(data_manager.data_indexer)\n embedding_matrix = embedding_manager.get_embedding_matrix(\n config.word_embedding_dim,\n config.pretrained_embeddings_file_path)\n vars(config)[\"word_embedding_matrix\"] = embedding_matrix\n\n # Initialize the model.\n model = SiameseBiLSTM(vars(config))\n model.build_graph()\n\n if mode == \"train\":\n # Train the model.\n num_epochs = config.num_epochs\n num_train_steps_per_epoch = int(math.ceil(train_data_size / batch_size))\n num_val_steps = int(math.ceil(val_data_size / batch_size))\n log_period = config.log_period\n val_period = config.val_period\n\n save_period = config.save_period\n save_dir = os.path.join(config.save_dir, model_name, run_id.zfill(2) + \"/\")\n save_path = os.path.join(save_dir, model_name + \"-\" + run_id.zfill(2))\n\n logger.info(\"Checkpoints will be written to {}\".format(save_dir))\n if not os.path.exists(save_dir):\n logger.info(\"save path {} does not exist, \"\n \"creating it\".format(save_dir))\n os.makedirs(save_dir)\n\n logger.info(\"Saving fitted DataManager to {}\".format(save_dir))\n data_manager_pickle_name = \"{}-{}-DataManager.pkl\".format(model_name,\n run_id.zfill(2))\n\n pickle.dump(data_manager,\n open(os.path.join(save_dir, data_manager_pickle_name), \"wb\"))\n\n patience = config.early_stopping_patience\n\n model.train(get_train_instance_generator=get_train_data_gen,\n get_val_instance_generator=get_val_data_gen,\n batch_size=batch_size,\n num_train_steps_per_epoch=num_train_steps_per_epoch,\n num_epochs=num_epochs,\n num_val_steps=num_val_steps,\n save_path=save_path,\n log_path=log_path,\n log_period=log_period,\n val_period=val_period,\n save_period=save_period,\n patience=patience)\n else:\n # Predict with the model\n model_load_dir = os.path.join(config.model_load_dir, config.model_name, config.run_id.zfill(2))\n\n num_test_steps = int(math.ceil(test_data_size / batch_size))\n # Numpy array of shape (num_test_examples, 2)\n raw_predictions, lineids = model.predict(get_test_instance_generator=test_data_gen,\n model_load_dir=model_load_dir,\n batch_size=batch_size,\n num_test_steps=num_test_steps)\n # Remove the first column, so we're left with just the probabilities\n # that a question is a duplicate.\n # Write the predictions to an output submission file\n output_predictions_path = os.path.join(log_path, model_name + \"-\" +\n run_id.zfill(2) +\n \"-output_predictions.csv\")\n\n with open(output_predictions_path, \"w\") as output_file:\n output_file.write(\"test_id,result\\n\")\n for index, lineid in enumerate(lineids):\n output_file.write(str(lineid) + \",\" + str(raw_predictions[index])+ \"\\n\")\n\n logger.info(\"Writing predictions to {}\".format(output_predictions_path))\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(format=\"%(asctime)s - %(levelname)s \"\n \"- %(name)s - %(message)s\",\n level=logging.INFO)\n main()\n","sub_path":"scripts/run_model_weizhong/run_siamese_weizhong.py","file_name":"run_siamese_weizhong.py","file_ext":"py","file_size_in_byte":13876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"48399683","text":"import numpy as np\nfrom scipy.io import loadmat\n\n\nclass Utils:\n def onehot(self, length, origin): # (onehot 배열 크기, 1이 되야하는 인덱스)\n onehot = np.zeros([len(origin), length], dtype=np.uint8)\n onehot[range(len(origin)), origin] = 1\n\n return onehot\n\n def convert_images2arr(self, images, pixel_depth=255.0): #pixel_depth는 픽셀이 가지는 값 크기(ex> rgb의 r값의 범위)\n rows = images.shape[0]\n cols = images.shape[1]\n channels = images.shape[2] #depth라고 부르기도 함\n num_images = images.shape[3]\n\n scalar = 1.0 / pixel_depth #사용 안하려면 pixel_depth=1.0으로 하면 된다.\n\n new_array = np.empty(shape=(num_images, rows, cols, channels), dtype=np.float32)\n\n for x in range(0, num_images): #normalize 부��, 0~1값으로 변환한다.\n channels = images[:, :, :, x]\n norm_vector = (255-channels) * scalar\n new_array[x] = norm_vector\n\n return new_array\n\nclass SVHN(Utils):\n def __init__(self):\n self.dataset_path = \"../Data/SVHN\"\n self.trainset = \"../Data/SVHN/train_32x32.mat\"\n self.testset = \"../Data/SVHN/test_32x32.mat\"\n\n def process_data(self, file):\n data = loadmat(file)\n images = data['X']\n labels = data['y'].flatten()\n labels[labels == 10] = 0\n labels_onehot = self.onehot(10, labels)\n image_array = self.convert_images2arr(images, pixel_depth=1.0)\n\n return image_array, labels_onehot\n\n def get_trainset(self):\n with open(self.trainset, 'rb') as file:\n data = self.process_data(file)\n\n return data\n\n def get_testset(self):\n with open(self.testset, 'rb') as file:\n data = self.process_data(file)\n\n return data\n\nif __name__ == \"__main__\":\n dataset = SVHN()\n\n train_images, train_labels = dataset.get_trainset()\n test_images, test_labels = dataset.get_testset()\n print(train_images.shape, train_labels.shape)\n print(test_images.shape, test_labels.shape)\n\n print(train_images[0].shape)\n print(train_images[0], train_labels[0])","sub_path":"Data/svhn_bak.py","file_name":"svhn_bak.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"397855844","text":"from soaptest.soaplib_handler import (\n DjangoSoapApp, soapmethod, soap_types\n )\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n\ndef index(request):\n return HttpResponse('howdy')\n\n\nclass SmsGatewayService(DjangoSoapApp):\n\n __tns__ = 'http://mismsgw01.milano.ea.it/soap'\n\n @soapmethod(\n soap_types.String, \n soap_types.String, \n soap_types.String, \n soap_types.Integer,\n soap_types.Boolean, \n soap_types.Boolean, \n soap_types.String, \n _returns=soap_types.Any\n )\n def sendSms(\n self, \n sendTo, \n numSender,\n senderDescription,\n timeToLive,\n isDelivered,\n isStatistics,\n messageText\n ):\n\n retCode = 'OK'\n\n return retCode\n\n def index(self):\n return 'OK'\n\nsms_gateway_service = csrf_exempt(SmsGatewayService())\n\n\nclass HelloWorldService(DjangoSoapApp):\n\n __tns__ = 'http://my.namespace.org/soap/'\n\n @soapmethod(soap_types.String, soap_types.Integer, _returns=soap_types.Array(soap_types.String))\n def say_hello(self, name, times):\n results = []\n for i in range(0, times):\n results.append('Hello, %s'%name)\n return results\n\nhello_world_service = HelloWorldService()\n","sub_path":"karma/django/mysite/soaptest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"531391840","text":"'''\n1. You are given a number n, representing the number of houses.\n2. In the next n rows, you are given 3 space separated numbers representing the cost of painting nth house with red or blue or green color.\n3. You are required to calculate and print the minimum cost of painting all houses without painting any consecutive house with same color.\n\nInput Format:\n\nA number n\n\nn1red n1blue n1green\nn2red n2blue n2green\n.. n number of elements\n\n\nSample Input:\n\n4\n\n1 5 7\n5 8 4\n3 2 9\n1 2 4\n\nSample Output:\n\n8\n\n\nhttps://www.youtube.com/watch?v=kh48JLieeW8&list=PL-Jc9J83PIiG8fE6rj9F5a6uyQ5WPdqKy&index=23\n\n\n'''\n\ndef paintHouse(arr, n):\n \n dp = [[0 for j in range(len(arr[0]))] for i in range(n)]\n #print(dp)\n \n dp[0][0] = arr[0][0]\n dp[0][1] = arr[0][1]\n dp[0][2] = arr[0][2]\n \n for i in range(1, n):\n \n dp[i][0] = arr[i][0] + min(dp[i - 1][1], dp[i - 1][2])\n dp[i][1] = arr[i][1] + min(dp[i - 1][0], dp[i - 1][2])\n dp[i][2] = arr[i][2] + min(dp[i - 1][0], dp[i - 1][1])\n \n #print(dp)\n \n finalAns = min(dp[n - 1][0], dp[n - 1][1], dp[n - 1][2])\n return finalAns\n\n\nif __name__ == \"__main__\":\n \n n = 4\n arr = [\n [1, 5, 7],\n [5, 8, 4],\n [3, 2, 9],\n [1, 2, 4]\n ]\n \n print(paintHouse(arr, n))","sub_path":"pepcoding/dynamic_programming/17_paint_house_difficult.py","file_name":"17_paint_house_difficult.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"21937485","text":"#!/usr/bin/python3\n\nimport jbpp\nimport jbppui\n\nclass Fibbage(jbppui.JBPPUI):\n def __init__(self):\n super().__init__()\n \n super().set_game_name(\"Fibbage\")\n \n super().set_path(\"assets/games/Fibbage\")\n super().set_content_file(\"content/shortie.jet\")\n super().set_question_path(\"content/questions/%s\")\n super().set_question_file(\"data.jet\")\n super().set_content_field(\"questions\")\n \n super().set_content_template({\"id\": 0, \"category\": \"\", \"x\": True, \"bumper\": \"\"})\n super().set_question_template({\n \"fields\":[ \n { \n \"t\":\"B\",\n \"v\":\"false\",\n \"n\":\"HasBumperAudio\"\n },\n { \n \"t\":\"B\",\n \"v\":\"false\",\n \"n\":\"HasBumperType\"\n },\n { \n \"t\":\"B\",\n \"v\":\"false\",\n \"n\":\"HasCorrectAudio\"\n },\n { \n \"t\":\"B\",\n \"v\":\"false\",\n \"n\":\"HasQuestionAudio\"\n },\n { \n \"t\":\"S\",\n \"v\":\"Suggestions (comma separated)\",\n \"n\":\"Suggestions\"\n },\n { \n \"t\":\"S\",\n \"v\":\"Category\",\n \"n\":\"Category\"\n },\n { \n \"t\":\"S\",\n \"v\":\"Correct answer\",\n \"n\":\"CorrectText\"\n },\n { \n \"t\":\"S\",\n \"v\":\"None\",\n \"n\":\"BumperType\"\n },\n { \n \"t\":\"S\",\n \"v\":\"Question \",\n \"n\":\"QuestionText\"\n },\n { \n \"t\":\"S\",\n \"v\":\"Alternative spellings (comma separated)\",\n \"n\":\"AlternateSpellings\"\n },\n { \n \"t\":\"A\",\n \"n\":\"BumperAudio\"\n },\n { \n \"t\":\"A\",\n \"v\":\"372356_0f\",\n \"n\":\"CorrectAudio\"\n },\n { \n \"t\":\"A\",\n \"v\":\"372353_1\",\n \"n\":\"QuestionAudio\"\n }\n ]\n })\n \n super().add_ui_field(\"Category\", jbppui.TEXTBOX, \"Category\", \"category\")\n super().add_ui_field(\"Question\", jbppui.TEXTBOX, \"QuestionText\", \"What is ?\")\n super().add_ui_field(\"Answer\", jbppui.TEXTBOX, \"CorrectText\", \"\")\n super().add_ui_field(\"Alternate spellings\", jbppui.TEXTBOX, \"AlternateSpellings\", \"spelling1,spelling2,...\")\n super().add_ui_field(\"Suggestions\", jbppui.TEXTBOX, \"Suggestions\", \"suggestion1,suggestion2,...\")\n \n super().set_display_name(\"category\", jbppui.CONTENT)\n super().add_copy_field(\"Category\", \"category\")\n \n super().main_screen()\n\n \n \napp = Fibbage()\napp.root.mainloop() \n","sub_path":"fibbage.py","file_name":"fibbage.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"595559438","text":"import sys\nimport pickle\ntry:\n\timport gensim\nexcept ImportError:\n\tpass\nimport pandas as pd\nimport numpy\ntry:\n\timport xgboost\nexcept ImportError:\n\tpass\n\n\ndef pad_vectors(list_of_vecs):\n\tfor j in range(len(list_of_vecs), 2**2):\n\t\tlist_of_vecs.append(numpy.zeros(2**2))\n\treturn numpy.array(list_of_vecs)\n\n\ndef preprocess(df):\n\ttokens = df.content.astype(str).apply(lambda x: list(gensim.utils.tokenize(x)))\n\ttokens = tokens.apply(lambda x: x[:2**2])\n\tvectorized = tokens.apply(lambda x: list(map(lambda y: ft_model.wv[y], x)))\n\tpadded_vectors = vectorized.apply(pad_vectors)\n\tpadded_vectors = padded_vectors.apply(lambda x: x.flatten())\n\tdata = padded_vectors.to_list()\n\tdata = numpy.array(data)\n\tdata = pd.DataFrame(data, index = padded_vectors.index, columns = range(2**4))\n\treturn data\n\n\n# modelop.init\ndef conditional_begin():\n\tif 'xgboost' in sys.modules:\n\t\tbegin()\n\n\ndef begin():\n\tglobal threshold, xgb_model, ft_model\n\txgb_model_artifacts = pickle.load(open('./assets/xgb_model_artifacts.pkl', 'rb'))\n\tthreshold = xgb_model_artifacts['threshold']\n\tft_model = xgb_model_artifacts['ft_model']\n\n\txgb_model = xgboost.XGBClassifier()\n\txgb_model.load_model('./assets/xgb_model.model')\n\tpass\n\n\n# modelop.score\ndef action(df):\n\n\tcleaned = preprocess(df)\n\tpred_proba = xgb_model.predict_proba(cleaned)[:,1]\n\tpred_proba = pd.Series(pred_proba, index = df.index)\n\tpreds = pred_proba.apply(lambda x: x > threshold).astype(int)\n\n\toutput = pd.concat([df, preds], axis=1)\n\toutput.columns = ['id', 'content', 'prediction']\n\tyield output\n\n\n# modelop.metrics\ndef metrics(datum):\n\tyield {\n\t\t\"ROC\": [\n\t\t\t{\n\t\t\t\t\"fpr\": 0,\n\t\t\t\t\"tpr\": 0\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0,\n\t\t\t\t\"tpr\": 0.3333333333333333\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.0375,\n\t\t\t\t\"tpr\": 0.3333333333333333\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.0375,\n\t\t\t\t\"tpr\": 0.6666666666666666\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.1875,\n\t\t\t\t\"tpr\": 0.6666666666666666\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.1875,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.25,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.275,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.5375,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.5625,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.65,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.675,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.75,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 0.9,\n\t\t\t\t\"tpr\": 1\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"fpr\": 1,\n\t\t\t\t\"tpr\": 1\n\t\t\t}\n\t\t],\n\t\t\"auc\": 0.9249999999999999,\n\t\t\"f2_score\": 0.5263157894736842,\n\t\t\"cost_per_f2_point\": 1.16,\n\t\t\"confusion_matrix\": [\n\t\t\t{\n\t\t\t\t\"Compliant\": 75,\n\t\t\t\t\"Non-Compliant\": 5\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"Compliant\": 1,\n\t\t\t\t\"Non-Compliant\": 2\n\t\t\t}\n\t\t],\n\t\t\"shap\" : {\n\n\t\t},\n\t\t\"bias\" : {\n\t\t\t\"attributeAudited\": \"Gender\",\n\t\t\t\"referenceGroup\": \"Male\",\n\t\t\t\"fairnessThreshold\": \"80%\",\n\t\t\t\"fairnessMeasures\": [\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"Equal Parity\",\n\t\t\t\t\t\"result\": \"Failed\",\n\t\t\t\t\t\"group\": \"Female\",\n\t\t\t\t\t\"disparity\": 0.67\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"Proportional Parity\",\n\t\t\t\t\t\"result\": \"Passed\",\n\t\t\t\t\t\"group\": None,\n\t\t\t\t\t\"disparity\": 1.1\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"False Positive Rate Parity\",\n\t\t\t\t\t\"result\": \"Passed\",\n\t\t\t\t\t\"group\": \"Female\",\n\t\t\t\t\t\"disparity\": 1.17\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"False Discovery Rate Parity\",\n\t\t\t\t\t\"result\": \"Passed\",\n\t\t\t\t\t\"group\": \"Female\",\n\t\t\t\t\t\"disparity\": 0.82\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"False Negative Rate Parity\",\n\t\t\t\t\t\"result\": \"Passed\",\n\t\t\t\t\t\"group\": \"Female\",\n\t\t\t\t\t\"disparity\": 1.1\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"False Omission Rate Parity\",\n\t\t\t\t\t\"result\": \"Passed\",\n\t\t\t\t\t\"group\": \"Female\",\n\t\t\t\t\t\"disparity\": 0.88\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t}\n","sub_path":"enron_ecomm_xgboost.py3","file_name":"enron_ecomm_xgboost.py3","file_ext":"py3","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"314528736","text":"from DataLoader import DatasetKspace\nfrom Networks import unet11\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data\nfrom utils import Logger\nimport os\nimport argparse\nimport sys\nimport pickle\nimport time\nimport numpy as np\n\nif __name__ == '__main__':\n \"\"\"\n Run directly\n \"\"\"\n ## timestamping the model and log files is a good practice for keeoing track of your experiments\n TIME_STAMP = time.strftime('%Y-%m-%d-%H-%M-%S') # year-month-day=hour-minute-second\n # dir_project='C:\\\\Users\\\\Reasat\\\\Projects\\\\MR2CTsynthesis'\n # dir_data='D:\\\\Data\\\\MR2CTsynthesis'\n dir_project = r'C:\\Users\\ranab\\PycharmProjects\\MRCTFR'\n dir_data = r'D:\\PaddedMRCT' #where images are split into train, valid and test folders\n\n path_out = os.path.join(dir_project,'out','{}.out'.format(TIME_STAMP))\n\n sys.stdout = Logger(path_out)\n\n print(TIME_STAMP)\n parser = argparse.ArgumentParser()\n parser.add_argument('epoch', type=int, help='epochs')\n parser.add_argument('batchSize', type=int, help='batch size')\n parser.add_argument('lr', type=float, help='learning rate')\n args = parser.parse_args()\n\n config = vars(args) #todo: why\n config_ls = sorted(list(config.items()))\n print(\n '--------------------------------------------------------------------------------------------------------------------')\n for item in config_ls: #todo: why printing these\n print('{}: {}'.format(item[0], item[1]))\n print(\n '--------------------------------------------------------------------------------------------------------------------')\n\n use_cuda = torch.cuda.is_available() #gives True if CUDA is available ->True\n device = torch.device(\"cuda:0\"if use_cuda else \"cpu\") # -> cuda:0\n # cudnn.benchmark = True\n\n ## Setup directories\n\n # directory structure\n # ** Manually make these directories **\n # MR2CTsynthesis (Project directory for small files which will be pushed to git )\n # --code (put scripts in the code folder)\n # --log\n # Data (directory for large files which will be stored locally, too large for git)\n # --MR_CT_data\n # --Train\n # --Valid\n # --Test\n # --model\n\n\n dir_model = os.path.join(dir_data, 'model')\n dir_log = os.path.join(dir_project, 'log')\n dir_train = os.path.join(dir_data, 'Images','Train')\n dir_test = os.path.join(dir_data, 'Images','Test')\n dir_valid = os.path.join(dir_data, 'Images','Valid')\n FILEPATH_MODEL_SAVE = os.path.join(dir_model, '{}.pt'.format(TIME_STAMP)) # save model here\n # FILEPATH_MODEL_LOAD = os.path.join(dir_model, '{}.pt'.format(TIME_STAMP)) # load model weights to resume training\n FILEPATH_MODEL_LOAD=None\n FILEPATH_LOG = os.path.join(dir_log, '{}.bin'.format(TIME_STAMP)) # save loss history here\n\n ## Training hyper-parameters\n\n max_epochs = args.epoch\n lr = args.lr\n\n ## Setup loaders\n with open(os.path.join(dir_data, 'Images','train.txt'), 'r') as f:\n filenames_train = f.readlines()\n filenames_train = [item.strip() for item in filenames_train]\n with open(os.path.join(dir_data, 'Images','valid.txt'), 'r') as f:\n filenames_valid = f.readlines()\n filenames_valid = [item.strip() for item in filenames_valid]\n with open(os.path.join(dir_data, 'Images','test.txt'), 'r') as f:\n filenames_test = f.readlines()\n filenames_test = [item.strip() for item in filenames_test]\n\n train_dataset = DatasetKspace(dir_train,filenames_train) #dir_train\n train_loader = data.DataLoader(train_dataset, batch_size=args.batchSize, shuffle=True) #data comes from torch.utils\n print('train directory has {} samples'.format(len(train_dataset)))\n\n valid_dataset = DatasetKspace(dir_valid,filenames_valid) #dir_valid\n valid_loader = data.DataLoader(valid_dataset, batch_size=args.batchSize, shuffle=False)\n print('validation directory has {} samples'.format(len(valid_dataset)))\n\n test_dataset = DatasetKspace(dir_test,filenames_test) #dir_test\n test_loader = data.DataLoader(test_dataset, batch_size=args.batchSize, shuffle=False)\n print('test directory has {} samples'.format(len(test_dataset)))\n\n model_save_criteria = np.inf # initialize the threshold for saving the model #todo: এর মানে কি?\n train_states = {} # initialze a dict to save training state of the model\n\n model11 = unet11(pretrained=True).to(device) #unet11 imported from UNet_models.py\n criterion = nn.MSELoss() #loss will be calculated in Mean Square Error algorithm per batch size?\n optimizer = torch.optim.Adam(model11.parameters(), lr=lr) #Optimization will be performed using Adam optimizer\n\n ## resuming a training session\n if FILEPATH_MODEL_LOAD is not None:\n train_states = torch.load(FILEPATH_MODEL_LOAD)\n model11.load_state_dict(train_states['train_states_latest']['model_state_dict'])\n optimizer.load_state_dict(train_states['train_states_latest']['optimizer_state_dict'])\n train_states_best = train_states['train_states_best']\n # loss_valid_min=train_states_best['loss_valid_min'] # change\n model_save_criteria = train_states_best['model_save_criteria'] # change\n\n else:\n train_states={}\n model_save_criteria = np.inf #todo: এর মানে কি?\n\n ## Train\n loss_epoch_train=[]\n loss_epoch_valid=[]\n\n for epoch in range(max_epochs):\n running_loss = 0\n running_time_batch = 0\n time_batch_start = time.time()\n model11.train()\n for i, sample in enumerate(train_loader):\n time_batch_load = time.time() - time_batch_start\n time_compute_start = time.time()\n mr = sample[0].float().to(device)\n abs = sample[1].float().to(device) #todo: float or int16\n # phase = sample[2].float().to(device) #todo: float or int16\n\n output = model11(mr)\n optimizer.zero_grad()\n loss = criterion(abs, output)\n loss.backward()\n optimizer.step()\n running_loss += loss.item()\n mean_loss = running_loss / (i + 1)\n\n # print time stats\n time_compute = time.time() - time_compute_start\n time_batch = time_batch_load + time_compute\n running_time_batch += time_batch\n time_batch_avg = running_time_batch / (i + 1)\n\n print(\n 'epoch: {}/{}, batch: {}/{}, loss-train: {:.4f}, batch time taken: {:.2f}s, eta_epoch: {:.2f} hours'.format(\n epoch + 1,\n max_epochs,\n i + 1,\n len(train_loader),\n mean_loss,\n time_batch,\n time_batch_avg * (len(train_loader) - (i + 1)) / 3600,\n )\n )\n time_batch_start=time.time()\n loss_epoch_train.append(mean_loss)\n\n ## Validation\n for i, sample in enumerate(valid_loader):\n running_loss = 0\n model11.eval()\n with torch.no_grad():\n mr = sample[0].float().to(device)\n abs = sample[1].float().to(device)\n output = model11(mr)\n loss = criterion(abs, output)\n running_loss += loss.item()\n mean_loss = running_loss / (i + 1)\n print(\n 'epoch: {}/{}, batch: {}/{}, loss-valid: {:.4f}'.format(\n epoch + 1,\n max_epochs,\n i + 1,\n len(valid_loader),\n mean_loss,\n )\n )\n loss_epoch_valid.append(mean_loss)\n\n ## Save model if loss decreases\n chosen_criteria = mean_loss\n print('criteria at the end of epoch {} is {:.4f}'.format(epoch + 1, chosen_criteria))\n\n if chosen_criteria < model_save_criteria: # save model if true\n print('criteria decreased from {:.4f} to {:.4f}, saving model...'.format(model_save_criteria,\n chosen_criteria))\n train_states_best = {\n 'epoch': epoch + 1,\n 'model_state_dict': model11.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'model_save_criteria': chosen_criteria,\n }\n train_states = {\n 'train_states_best': train_states_best,\n }\n torch.save(train_states, FILEPATH_MODEL_SAVE)\n\n model_save_criteria = chosen_criteria\n\n log = {\n 'loss_train': loss_epoch_train,\n 'loss_valid': loss_epoch_valid,\n }\n with open(FILEPATH_LOG, 'wb') as pfile:\n pickle.dump(log, pfile)\n\n ## also save the latest model after each epoch as you may want to resume training at a later time\n train_states_latest = {\n 'epoch': epoch + 1,\n 'model_state_dict': model11.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'model_save_criteria': chosen_criteria,\n }\n train_states['train_states_latest'] = train_states_latest\n torch.save(train_states, FILEPATH_MODEL_SAVE)\n\n ## Test\n for i, sample in enumerate(test_loader):\n running_loss = 0\n model11.eval() # sets the model in evaluation mode\n with torch.no_grad():\n mr = sample[0].float().to(device)\n abs = sample[1].float().to(device)\n output = model11(mr)\n loss = criterion(abs, output)\n running_loss += loss.item()\n mean_loss = running_loss / (i + 1)\n print('test_loss {:.4f}'.format(mean_loss))\n # break\n\n\n # print('Debug here')\n # break\n\n # import matplotlib.pyplot as plt\n # plt.imshow(output)\n # plt.show()\n\n\n","sub_path":"code/MRCTFR/train_kspace.py","file_name":"train_kspace.py","file_ext":"py","file_size_in_byte":9936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"314474523","text":"#!/usr/bin/python\nimport RPi.GPIO as GPIO\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nGPIO.setwarnings(False)\ndef get_html(url):\n try:\n r = requests.get(url)\n r.raise_for_status()\n return r.text\n except:\n print(\"requests_wrong\")\n return 0\n\ndef get_index(html,index):\n soup = BeautifulSoup(html,\"html.parser\")\n index[1] = (int(soup.find('span',attrs={\"article-read\"}).string))\n\ndef light():\n GPIO.output(26,1)\n time.sleep(0.5)\n GPIO.output(26,0)\n\nindex = [0,0]\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(26,GPIO.OUT)\nGPIO.output(26,0)\nurl = \"http://www.zybuluo.com/itachigiotto/note/659241\"\nwhile True:\n html = get_html(url)\n get_index(html,index)\n if index[1]-index[0] > 1:\n print(\"got\")\n light()\n else:\n print(\"waiting\")\n index[0] = index[1]\n","sub_path":"webgetter_light.py","file_name":"webgetter_light.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"600390503","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport pandas as pd\nfrom datacuration.data_struct import TimeSeries\n\n__author__ = \"Tozammel Hossain\"\n__email__ = \"tozammel@isi.edu\"\n\n\ndef load_a_time_series(filepath, header=0, name='count', index_name='date'):\n ts = pd.read_csv(filepath, header=header, parse_dates=True, index_col=0,\n squeeze=True)\n ts.name = name\n ts.index.name = index_name\n fname = os.path.split(filepath)[1]\n fname_wo_ext = os.path.splitext(fname)[0]\n return TimeSeries(ts, name=fname_wo_ext)\n\n\ndef load_time_series(filelist, header=0, name='count', index_name='date'):\n tslist = list()\n for f in filelist:\n fname = os.path.split(f)[1]\n fname_wo_ext = os.path.splitext(fname)[0]\n ts = pd.read_csv(f, header=header, parse_dates=True, index_col=0,\n squeeze=True)\n ts.name = name\n ts.index.name = index_name\n cts = TimeSeries(ts, name=fname_wo_ext)\n tslist.append(cts)\n return tslist\n\n\ndef load_ts(filepath, start_date=None, end_date=None):\n print(\"Loading:\", filepath)\n ts = pd.read_csv(filepath, header=0, index_col=0,\n parse_dates=True, squeeze=True)\n print(\"Min date =\", ts.index.min())\n print(\"Max date =\", ts.index.max())\n print(ts.describe())\n\n if start_date is not None or end_date is not None:\n ts = ts[start_date:end_date]\n return ts\n","sub_path":"datacuration/process_time_series.py","file_name":"process_time_series.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"385625647","text":"\"\"\"Test comparison operators.\"\"\"\n\nfrom pytype.tests import test_base\n\n\nclass DecoratorsTest(test_base.TargetPython3BasicTest):\n\n def testAnnotatedSuperCallUnderBadDecorator(self):\n _, errors = self.InferWithErrors(\"\"\"\\\n\n class Foo(object):\n def Run(self) -> None: ...\n class Bar(Foo):\n @bad_decorator # line 5\n def Run(self):\n return super(Bar, self).Run()\n \"\"\")\n self.assertErrorLogIs(errors, [(5, \"name-error\", r\"bad_decorator\")])\n\n\ntest_base.main(globals(), __name__ == \"__main__\")\n","sub_path":"pytype/tests/py3/test_decorators.py","file_name":"test_decorators.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"253053342","text":"import json\r\nimport socket\r\nfrom datetime import datetime\r\nfrom threading import Thread\r\n\r\nimport action_operator\r\nfrom database_handler import add_to_database\r\n\r\nHOST = '127.0.0.1'\r\nPORT = 8080\r\nBLOCK_SIZE = 1024\r\nPRICE_PER_HOUR = 100\r\n\r\n\r\ndef init_server():\r\n global server_socket\r\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\r\n server_socket.bind((HOST, PORT))\r\n server_socket.listen(5)\r\n print('waiting for connection...')\r\n add_to_database({\"type\": \"log\", \"date\": datetime.now(), \"text\": f\"Server started\"})\r\n Thread(target=connect_users).start()\r\n\r\n\r\ndef connect_users():\r\n global conn\r\n\r\n while True:\r\n conn, address = server_socket.accept()\r\n print('connected:', address)\r\n add_to_database({\"type\": \"log\", \"date\": datetime.now(), \"text\": f\"Connected user{address}\"})\r\n\r\n Thread(target=handle_connected_user, args=(conn, address,)).start()\r\n\r\n\r\ndef handle_connected_user(conn, address):\r\n is_admin = action_operator.authenticate(address, conn)\r\n\r\n try:\r\n while True:\r\n data = conn.recv(BLOCK_SIZE).decode(\"utf-8\")\r\n if not data:\r\n break\r\n\r\n data = json.loads(data)\r\n action = data.get(\"type\", None)\r\n add_to_database({\"type\": \"log\", \"date\": datetime.now(), \"text\": f\"Got action {action} from user {address}\"})\r\n\r\n if action == \"park\":\r\n car_number = data.get(\"number\", None)\r\n action_operator.park(car_number, conn, address)\r\n\r\n elif action == \"unpark\":\r\n car_number = data.get(\"number\", None)\r\n action_operator.unpark(car_number, conn, address)\r\n\r\n elif action == \"history\" and is_admin:\r\n action_operator.get_big_data(action, conn)\r\n\r\n elif action == \"log\" and is_admin:\r\n action_operator.get_big_data(action, conn)\r\n\r\n elif action == \"total\" and is_admin:\r\n action_operator.get_total(conn)\r\n\r\n elif action == \"exit\":\r\n print(f\"User {address} disconnected.\")\r\n return\r\n\r\n except ConnectionResetError:\r\n print(\"User disconnected\")\r\n\r\n\r\nif __name__ == '__main__':\r\n init_server()\r\n","sub_path":"Lab04_git/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"531922354","text":"\"\"\"\nRNASeq 1\n\"\"\"\nimport os\n\nfrom airflow import DAG\nfrom airflow.utils.dates import days_ago\nfrom airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator\nfrom airflow.contrib.kubernetes.volume import Volume\nfrom airflow.contrib.kubernetes.volume_mount import VolumeMount\n\n\n##\n# Persistent Volume Configuration\n##\n\n## Reference Volume\ninput_ref_config= {\n 'persistentVolumeClaim':\n {\n 'claimName': 'pvc-references'\n }\n }\n\ninput_ref_volume = Volume(name='reference-mount', configs=input_ref_config)\ninput_ref_mount = VolumeMount(name='reference-mount',\n mount_path='/rnaseq/ref',\n sub_path='ref',\n read_only=True)\n\n# Input Data Volume\ninput_data_config= {\n 'persistentVolumeClaim':\n {\n 'claimName': 'pvc-input'\n }\n }\n\ninput_data_volume = Volume(name='input-mount', configs=input_data_config)\ninput_data_mount = VolumeMount(name='input-mount',\n mount_path='/rnaseq/data',\n sub_path=None,\n read_only=True)\n\n### Output Volume\noutput_config= {\n 'persistentVolumeClaim':\n {\n 'claimName': 'pvc-output'\n }\n }\n\noutput_volume = Volume(name='output-mount', configs=output_config)\noutput_mount = VolumeMount(name='output-mount',\n mount_path='/rnaseq/output',\n sub_path=None,\n read_only=False)\n\n\nargs = {\n 'owner': 'airflow',\n 'start_date': days_ago(2)\n}\n\n\n##\n# RNA Seq 1\n##\nwith DAG(\n dag_id='rnaseq1',\n default_args=args,\n schedule_interval=None,\n tags=['example'],\n) as dag:\n\n rna_seq = KubernetesPodOperator(\n task_id=\"rna_seq_fat\",\n name = \"rnaseq1_pipeline\",\n namespace='default',\n image=\"dchen71/rna:202003\",\n volumes=[input_ref_volume, input_data_volume, output_volume],\n volume_mounts=[input_ref_mount, input_data_mount, output_mount],\n resources={'request_memory':'24Gi', 'limit_memory': '32Gi', 'request_cpu': '4', 'limit_cpu': '4'},\n is_delete_operator_pod=True\n )\n\n # Order for pipeline to do stuff\n ## ls mount > create files > write to files\n rna_seq\n \n","sub_path":"rnaseq1.py","file_name":"rnaseq1.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"92192121","text":"\"\"\"\n6.\tВ программе генерируется случайное целое число от 0 до 100.\nПользователь должен его отгадать не более чем за 10 попыток. После каждой\nнеудачной попытки должно сообщаться больше или меньше введенное пользователем\nчисло, чем то, что загадано. Если за 10 попыток число не отгадано,\nто вывести загаданное число.\n\nРешите через рекурсию. Решение через цикл не принимается.\nДля оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7\nДля оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7\n\"\"\"\n\nimport random\n\n\ndef guess_rec(number, TTL=0, my_try=1):\n try:\n if my_try > TTL:\n return f\"У Вас не получилось угадать - закончились попытки, число: {number}\"\n else:\n answer = int(input(\"Введите целое число от 0 до 100 \"))\n if answer == number:\n return f'Вы угадали число - {number}, Поздравляю!'\n else:\n if answer < number:\n print('Число больше!')\n return guess_rec(number, TTL, my_try + 1)\n else:\n print('Число меньше!')\n return guess_rec(number, TTL, my_try + 1)\n\n except ValueError:\n return guess_rec(number, TTL, my_try + 1)\n\n\nTOTAL_TRIES = 10\n\nprint(guess_rec(random.randint(0, 100), TOTAL_TRIES))\n\n","sub_path":"Урок 2. Практическое задание/task_6.py","file_name":"task_6.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"39343165","text":"import tensorflow as tf\nimport dataset, ops\nimport shutil\nimport time\nimport os\n\n\nclass Logger(object):\n def __init__(self, log_path):\n self.fp = open(log_path, 'a')\n self.last_time_stamp = time.time()\n\n self.batch_metrics = []\n\n def __del__(self):\n self.fp.close()\n\n def close(self):\n self.fp.close()\n\n def timer(self):\n eta = time.time() - self.last_time_stamp\n self.last_time_stamp = time.time()\n\n return eta\n\n def add_batch(self, metrics):\n self.batch_metrics.append(metrics)\n\n def zip_batch(self):\n metrics = {}\n for batch in self.batch_metrics:\n for k, v in batch.items():\n if k not in metrics: metrics[k] = []\n metrics[k].append(v)\n\n self.batch_metrics = []\n return {k: sum(v) / len(v) for k, v in metrics.items()}\n\n def __call__(self, current_iters, total_iters, val_metrics):\n eta = self.timer()\n train_metrics = self.zip_batch()\n\n print_msg = '[*] {0}/{1} \\t train ({3}) \\t validation ({4}) \\t ETA: {2:.1f}'.format(\n current_iters, total_iters, eta,\n ', '.join(['{}: {:.4f}'.format(k, v) for k, v in train_metrics.items()]),\n ', '.join(['{}: {:.4f}'.format(k, v) for k, v in val_metrics.items()]))\n log_msg = '{0}\\t{1}\\t{3}\\t{4}\\t{2}\\n'.format(\n current_iters, total_iters, eta,\n ' '.join(['{} {}'.format(k, v) for k, v in train_metrics.items()]),\n ' '.join(['{} {}'.format(k, v) for k, v in val_metrics.items()]))\n\n print(print_msg)\n self.fp.write(log_msg)\n self.fp.flush()\n\ndef create_train_ops(FLAGS, model_fn):\n iterator = (dataset\n .create_imagenet_train_dataset(FLAGS.dataset_dir, FLAGS.train_batch_size)\n .make_one_shot_iterator())\n features, labels = iterator.get_next()\n\n if FLAGS.use_fp16:\n # cast the input to float16 and the output to float32\n features = tf.cast(features, tf.float16)\n\n logits = model_fn(features, is_training=True)\n logits = tf.cast(logits, tf.float32)\n else:\n logits = model_fn(features, is_training=True)\n\n # calculate the loss and accuracy metrics\n loss_op = ops.softmax_loss(logits, labels)\n accuracy_1_op = ops.accuracy(logits, labels, top_k=1)\n accuracy_5_op = ops.accuracy(logits, labels, top_k=5)\n\n with tf.variable_scope('optimization'):\n global_step = tf.train.get_or_create_global_step()\n learning_rate = ops.cyclic_learning_rate(global_step, FLAGS.total_iters, FLAGS.max_lr, FLAGS.min_lr)\n \n optimizer = tf.train.MomentumOptimizer(learning_rate, FLAGS.momentum)\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n if FLAGS.use_fp16:\n # use loss scaling to preserve small gradient magnitudes\n grad_and_vars = optimizer.compute_gradients(loss_op * FLAGS.loss_scale)\n grad_and_vars = [(grad / FLAGS.loss_scale, var) for grad, var in grad_and_vars if grad is not None]\n else:\n grad_and_vars = optimizer.compute_gradients(loss_op)\n\n # apply gradients to each variables\n train_op = optimizer.apply_gradients(grad_and_vars, global_step)\n\n return train_op, {'loss': loss_op, 'top-1-accuracy': accuracy_1_op, 'top-5-accuracy': accuracy_5_op}\n\ndef create_test_ops(FLAGS, model_fn, evaluation=False):\n iterator = (dataset\n .create_imagenet_test_dataset(FLAGS.dataset_dir, FLAGS.test_batch_size, evaluation)\n .make_one_shot_iterator())\n features, labels = iterator.get_next()\n\n # do not use the half-precision for precise evaluation\n logits = model_fn(features, is_training=False)\n\n # calculate the loss and accuracy metrics\n loss_op = ops.softmax_loss(logits, labels)\n accuracy_1_op = ops.accuracy(logits, labels, top_k=1)\n accuracy_5_op = ops.accuracy(logits, labels, top_k=5)\n\n return {'loss': loss_op, 'top-1-accuracy': accuracy_1_op, 'top-5-accuracy': accuracy_5_op}\n\ndef train(FLAGS, model_fn, only_weights=False):\n train_ops = create_train_ops(FLAGS, model_fn)\n\n tf.get_variable_scope().reuse_variables()\n test_ops = create_test_ops(FLAGS, model_fn, evaluation=False)\n\n with tf.Session() as sess:\n sess.run(tf.initializers.global_variables())\n\n # restore weights if there is a checkpoint file\n latest_ckpt = tf.train.latest_checkpoint(FLAGS.model_path)\n if latest_ckpt:\n var_list = [v for v in tf.global_variables() if not v.name.startswith('optimization')]\n tf.train.Saver(var_list if only_weights else None).restore(sess, latest_ckpt)\n\n logger = Logger(FLAGS.log_path)\n latest_step = sess.run(tf.train.get_global_step())\n for step in range(latest_step + 1, FLAGS.total_iters + 1):\n _, metrics = sess.run(train_ops)\n logger.add_batch(metrics)\n\n # get metrics for test dataset and log the training results\n if step % FLAGS.log_iters == 0:\n logger(step, FLAGS.total_iters, sess.run(test_ops))\n\n # save the model to resume the training after stopped\n if step % FLAGS.save_iters == 0:\n if os.path.exists(FLAGS.model_path): shutil.rmtree(FLAGS.model_path)\n tf.train.Saver().save(sess, os.path.join(FLAGS.model_path, 'model.ckpt'), step)\n\n logger.close()\n if os.path.exists(FLAGS.model_path): shutil.rmtree(FLAGS.model_path)\n\n var_list = [v for v in tf.global_variables() if not v.name.startswith('optimization')]\n tf.train.Saver(var_list).save(sess, os.path.join(FLAGS.model_path, 'model.ckpt'))\n\ndef evaluate(FLAGS, model_fn):\n eval_ops = create_test_ops(FLAGS, model_fn, evaluation=True)\n\n total_metrics = {}\n with tf.Session() as sess:\n tf.train.Saver().restore(sess, os.path.join(FLAGS.model_path, 'model.ckpt'))\n\n try:\n while True:\n for k, v in sess.run(eval_ops).items():\n if k not in total_metrics: total_metrics[k] = []\n total_metrics[k].append(v)\n except tf.errors.OutOfRangeError: pass\n\n return {k: sum(v) / len(v) for k, v in total_metrics.items()}\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"543655434","text":"#Rafael Romero Bello A01747730\r\n#imprime las dimensiones de dos triangulos y luego los comprara\r\n\r\ndef calcularP1(b,h):\r\n p1=(2*b)+(2*h)\r\n return p1\r\n\r\ndef calcularP2(b2,h2):\r\n p2=(2*b2)+(2*h2)\r\n return p2\r\n\r\ndef calculararea1(b,h):\r\n a1=b*h\r\n return a1\r\n\r\ndef calcularArea2(b2,h2):\r\n a2=b2*h2\r\n return a2\r\n\r\ndef compararArea(a1,a2):\r\n if a1 < a2:\r\n r=\"el area mas grande es la figura 2\"\r\n elif a1>a2:\r\n r=\"el area mas grande es la figura 1\"\r\n elif a1==a2:\r\n r=\"sus areas son iguales\"\r\n else:\r\n r=\"algo esta mal\"\r\n return r\r\n\r\ndef main():\r\n Base1=int(input(\"Inserte la base1\"))\r\n Base2=int(input(\"inserte la base2\"))\r\n Altura1=int(input(\"inserte la altura1\"))\r\n Altura2=int(input(\"inserte la altura2\"))\r\n pe1=calcularP1(Base1,Altura1)\r\n pe2=calcularP2(Base2,Altura2)\r\n A1=calculararea1(Base1,Altura1)\r\n A2=calcularArea2(Base2,Altura2)\r\n Rf=compararArea(A1,A2)\r\n print(\"perimetro 1\",pe1)\r\n print(\"perimetro 2\",pe2)\r\n print(\"area1\",A1)\r\n print(\"area2\",A2)\r\n print(Rf)\r\n\r\nmain()","sub_path":"rectangulos.py","file_name":"rectangulos.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"507505780","text":"import decimal\nimport numbers\nimport warnings\n\nimport monotonic\n\nfrom .config import set_config\nfrom .report import Report\n\n\nclass IOpipe(object):\n def __init__(self, client_id=None, url=None, debug=None, **options):\n if client_id is not None:\n options['client_id'] = client_id\n if url is not None:\n options['url'] = url\n if debug is not None:\n options['debug'] = debug\n\n self.config = set_config(**options)\n\n def create_report(self, start_time, context):\n \"\"\"\n Used in advanced usage to manually set the report start_report\n \"\"\"\n self.report = Report(self.config)\n return self.report\n\n def log(self, key, value):\n \"\"\"\n Add custom data to the report\n \"\"\"\n event = {\n 'name': str(key)\n }\n\n # Add numerical values to report\n # We typecast decimals as strings: not JSON serializable and casting to floats can result in rounding errors.\n if isinstance(value, numbers.Number) and not isinstance(value, decimal.Decimal):\n event['n'] = value\n else:\n event['s'] = str(value)\n self.report.custom_metrics.append(event)\n\n def err(self, err):\n self.report.retain_err(err)\n self.report.send()\n raise err\n\n def decorator(self, fun):\n def wrapped(event, context):\n # if env var IOPIPE_ENABLED is set to False skip reporting\n if self.config['enabled'] is False:\n return fun(event, context)\n\n if not self.config['client_id']:\n warnings.warn('Your function is decorated with iopipe, but a valid token was not found.')\n\n err = None\n start_time = monotonic.monotonic()\n self.create_report(start_time, context)\n\n try:\n result = fun(event, context)\n except Exception as err:\n self.report.retain_err(err)\n raise err\n finally:\n try:\n self.report.update_data(context, start_time)\n except Exception as err:\n self.report.retain_err(err)\n raise err\n finally:\n self.report.send()\n return result\n return wrapped\n","sub_path":"iopipe/iopipe.py","file_name":"iopipe.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"508370816","text":"import os, subprocess\nimport json\nimport logging\nfrom homeassistant.components.http import HomeAssistantView\n_LOGGER = logging.getLogger(__name__)\n\nfrom .util import DOMAIN, XUNFEI_API\n\nclass XunfeiView(HomeAssistantView):\n\n url = XUNFEI_API\n name = DOMAIN\n requires_auth = False\n\n async def put(self, request):\n hass = request.app[\"hass\"]\n query = request.query\n type = query.get('type', '')\n root_path = hass.config.path(r\"custom_components/conversation/xunfei_pi/\")\n iat_sample = f'{root_path}iat_sample'\n try:\n # 判断程序文件是否存在\n if os.path.exists(iat_sample) == False:\n return self.json({ 'code': 1, 'msg': '文件不存在'})\n\n # 读取文件\n reader = await request.multipart()\n file = await reader.next()\n filename = f\"{root_path}voice.wav\"\n size = 0\n with open(filename, 'wb') as f:\n while True:\n chunk = await file.read_chunk() # 默认是8192个字节。\n if not chunk:\n break\n size += len(chunk)\n f.write(chunk)\n\n # 语音转文本\n pi = os.popen(f'{root_path}iat_sample.sh')\n text = pi.read()\n _LOGGER.debug(text)\n arr = text.split('=============================================================')\n if len(arr) > 0:\n result = arr[1].strip('\\n')\n # 调用语音识别服务\n if(type == 'conversation'):\n hass.async_create_task(hass.services.async_call('conversation', 'process', {'source': 'XunFei','text': result}))\n return self.json({ 'code': 0, 'msg': '识别成功', 'data': result})\n else:\n return self.json({ 'code': 1, 'msg': '识别失败', 'data': text}) \n except Exception as e:\n _LOGGER.debug(e)\n return self.json({ 'code': 1, 'msg': '出现异常'})","sub_path":"custom_components/conversation/xunfei_view.py","file_name":"xunfei_view.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"296792442","text":"# -*- coding: utf-8 -*-\n\nimport cv2\nimport sys\nimport os\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QFileDialog\nfrom MainWin import Ui_MainWindow\nfrom PyQt5 import QtGui\nfrom detect import *\nfrom sift import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5 import QtCore\nfrom PyQt5.QtGui import *\nimport qdarkstyle\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtSql import QSqlDatabase, QSqlQuery\n#import matplotlib.pyplot as plt\nfrom getFileName import *\nfrom cropImg import *\nimport time\nimport pygame\nimport csv\nimport pandas as pd\nfrom inquireFromCsv import *\nfrom readCSV import *\nfrom ZoomWindow import *\nimport re\nfrom isRoll import *\n\nclass MainForm(QMainWindow, Ui_MainWindow, QWidget):\n def __init__(self):\n super(MainForm, self).__init__()\n self.setupUi(self)\n self.model = QStandardItemModel(50, 3)\n self.model.setHorizontalHeaderLabels(['ID', 'Time', 'Status'])\n\n for row in range(50):\n for column in range(3):\n item = QStandardItem(\"row %s, column %s\" % (row, column))\n self.model.setItem(row, column, item)\n\n #self.tableView = QTableView()\n self.tableView.setModel(self.model)\n self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.tableView.doubleClicked.connect(self.table_change) # 双击事件函数\n dlgLayout = QVBoxLayout()\n dlgLayout.addWidget(self.tableView)\n self.setLayout(dlgLayout)\n\n self._create_csv()\n\n #初始化定时器\n self.timer = QTimer(self)\n self.timer.timeout.connect(self.showImg)\n\n # 点击show按钮开始每隔30秒钟显示一次图像\n self.pushButton_2.clicked.connect(self.startTimer)\n\n # 点击stop按钮暂停图片显示\n self.pushButton_3.clicked.connect(self.endTimer)\n # 点击zoom按钮显示放大的图像\n self.zoom_in.clicked.connect(self.zoomImg)\n\n # 点击inquire按钮显示需要检测的结果\n self.pushButton.clicked.connect(self.inquire)\n\n # 点击“回看查询”回看图片\n # self.pushButton_4.clicked.connect(self.playBack)\n\n # 点击“按时间查询”回看时间轴\n self.pushButton_5.clicked.connect(self.timeTable)\n\n # 近期疑似毛刺点查询\n self.negButton.clicked.connect(self.negSample)\n\n #设置字体格式\n self.label_2.setStyleSheet(\"border:2px solid black;\")\n self.label_2.setFont(QFont(\"Roman times\", 20, QFont.Bold))\n self.label_2.setAlignment(Qt.AlignCenter)\n self.label_3.setStyleSheet(\"border:2px solid black;\")\n self.label_3.setFont(QFont(\"Roman times\", 20, QFont.Bold))\n self.label_3.setAlignment(Qt.AlignCenter)\n self.label_4.setStyleSheet(\"border:2px solid black;\")\n self.label_4.setFont(QFont(\"Roman times\", 15, QFont.Bold))\n self.label_4.setAlignment(Qt.AlignCenter)\n self.label_5.setStyleSheet(\"border:2px solid black;\")\n self.label_5.setFont(QFont(\"Roman times\", 15, QFont.Bold))\n self.label_5.setAlignment(Qt.AlignCenter)\n self.label_7.setStyleSheet(\"border:2px solid black;\")\n self.label_10.setStyleSheet(\"border:2px solid red;\")\n self.label_12.setStyleSheet(\"border:2px solid blue;\")\n self.pushButton.setFont(QFont(\"Roman times\", 10, QFont.Bold))\n self.pushButton_2.setFont(QFont(\"Roman times\", 15, QFont.Bold))\n self.zoom_in.setFont(QFont(\"Roman times\", 15, QFont.Bold))\n self.pushButton_3.setFont(QFont(\"Roman times\", 15, QFont.Bold))\n self.pushButton_5.setFont(QFont(\"Roman times\", 10, QFont.Bold))\n\n self.storeDest1 = 'C:/ca_project/Demo/front' # 正面图片初始保存位置\n self.storeDest2 = 'C:/ca_project/Demo/back' # 背面图片初始保存位置\n self.finalDest1 = 'C:/ca_project/Demo/frontfinal'\n self.finalDest2 = 'C:/ca_project/Demo/backfinal'\n self.cropedDst1 = \"C:/ca_project/Demo/cropedImageFwd/image_croped.jpg\"\n self.cropedDst2 = \"C:/ca_project/Demo/cropedImageBwd/image_croped.jpg\"\n self.numbers = 0 #检测到角点个数\n self.findNew1 = False #目标路径下是否有新的图片\n self.findNew2 = False\n self.numbers1 = 0\n self.number2 = 0\n pygame.init()\n\n def closeEvent(self, event): # 退出警告\n ret = QMessageBox.question(self, \"警告\", \"确定要退出吗?\", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if ret == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n def negSample(self):\n pass\n\n def table_change(self, index): # index为当前点击的行列好\n QMessageBox.about(self, \"双击事件\", \"双击事件触发成功: \" + str(self.model.data(self.model.index(index.row(), 0))))\n\n def startTimer(self): #启动定时器\n self.timer.start(5000)\n self.pushButton_2.setEnabled(False)\n self.pushButton_3.setEnabled(True)\n\n def endTimer(self): # 结束定时器\n self.timer.stop()\n pygame.mixer.music.stop()\n self.pushButton_2.setEnabled(True)\n self.pushButton_3.setEnabled(False)\n\n # def playBack(self): #回看图片\n # playBackID = self.lineEdit_2.text()\n # self.s3 = PlayBackWindow()\n # self.s3.setWindowTitle('回看图片')\n # playDst = self.finalDest1 + '/' + playBackID + '.jpg'\n # if os.path.exists(playDst):\n # self.s3.label_10.setPixmap(QtGui.QPixmap(playDst))\n # self.s3.label_10.setScaledContents(True) # 让图片自适应label大小\n # # self.setStyleSheet(\"background: black\")\n # self.s3.label_10.setStyleSheet(\"border:2px solid black;\")\n # if not self.s3.isVisible():\n # self.s3.show()\n # else:\n # reply = QMessageBox.about(self, \"查询结果\", \"未找到符合要求的钢卷,请重新输入\")\n\n def zoomImg(self): #放大图片\n self.s1 = SecondWindow()\n self.s1.setWindowTitle('Fwd')\n self.s1.label_10.setPixmap(QtGui.QPixmap(\"./detectDst/test1.jpg\"))\n self.s1.label_10.setScaledContents(True) # 让图片自适应label大小\n # self.setStyleSheet(\"background: black\")\n self.s1.label_10.setStyleSheet(\"border:2px solid black;\")\n if not self.s1.isVisible():\n self.s1.show()\n\n self.s2 = SecondWindow()\n self.s2.setWindowTitle('Bwd')\n self.s2.label_10.setPixmap(QtGui.QPixmap(\"./detectDst/test2.jpg\"))\n self.s2.label_10.setScaledContents(True) # 让图片自适应label大小\n # self.setStyleSheet(\"background: black\")\n self.s2.label_10.setStyleSheet(\"border:2px solid black;\")\n if not self.s2.isVisible():\n self.s2.show()\n\n\n def inquire(self): #查询数据\n kwd = self.lineEdit.text() #获得输入钢卷ID\n # print(str)\n #self.textBrowser.setText(str)\n df = pd.read_csv('./database/database.csv')\n #print(df)\n # find, s1, s2, s3 = getCSV(kwd)\n self.play_back = PictureZoom()\n #self.paly_back.setWindowTitle(\"回放\")\n self.play_back.show()\n #print(find)\n # if (find == False):\n # reply = QMessageBox.about(self, \"查询结果\", \"未找到符合要求的钢卷,请重新输入\")\n # else:\n # reply = QMessageBox.about(self, \"查询结果\", \"ID: \" + s1 + \"\\tTime: \" + s2 + \"\\tStatus: \" + s3)\n\n #print(reply)\n\n\n def _selfCheck(self, src): # 检查文件夹中是否有没拍到钢卷的图像,有的话删除\n file_name_list = os.listdir(src)\n # print(file_name_list)\n check(src, file_name_list)\n\n\n\n\n def showImg(self): #显示图片\n self._selfCheck(self.storeDest1) # 除错图\n self._selfCheck(self.storeDest2)\n if not os.listdir(self.storeDest1) or not os.listdir(self.storeDest2): # 没有图则不做任何操作\n return\n findNew1, imgName1 = new_report(self.storeDest1, self.finalDest1)\n findNew2, imgName2 = new_report(self.storeDest2, self.finalDest2)\n #print(findNew1, imgName1, findNew2, imgName2)\n\n pygame.mixer.music.stop()\n\n self.cropName1 = cropAndSave(imgName1, self.cropedDst1)\n #print(self.cropName1)\n self.label_2.setPixmap(QtGui.QPixmap(imgName1))\n self.label_2.setScaledContents(True) # 让图片自适应label大小\n self.numbers1 = sift(self.cropName1, 1)\n if self.numbers1 > 500:\n self.label_2.setStyleSheet(\"border:2px solid red;\")\n #print(self.numbers1)\n else:\n self.label_2.setStyleSheet(\"border:2px solid black;\")\n\n self.cropName2 = cropAndSave(imgName2, self.cropedDst2)\n self.label_3.setPixmap(QtGui.QPixmap(imgName2))\n self.label_3.setScaledContents(True) # 让图片自适应label大小\n self.numbers2 = sift(self.cropName2, 2)\n if self.numbers2 > 500:\n self.label_3.setStyleSheet(\"border:2px solid red;\")\n else:\n self.label_3.setStyleSheet(\"border:2px solid black;\")\n\n #print(self.numbers1)\n #print(self.numbers2)\n if self.numbers1 > 200 or self.numbers2 > 200:\n #print(2)\n track = pygame.mixer.music.load(r\"./sound/1.mp3\")\n pygame.mixer.music.play()\n\n else:\n #print(1)\n pygame.mixer.music.stop()\n pygame.init()\n #print(self.numbers1, self.numbers2)\n\n num, df = readCSV('./database/database.csv')\n self.updateTable(num, df)\n\n\n str = \"当前正面图像为\" + imgName1 + \"\\n\" + \"当前反面图像为\" + imgName2\n self.textBrowser.setText(str)\n self.textBrowser.setFont(QFont(\"Microsoft YaHei\", 15))\n\n def updateTable(self, num, df):\n #pass\n if (num>50):\n for row in range(50):\n item = QStandardItem(str(df[-row-1][0]))\n self.model.setItem(row, 0, item)\n item = QStandardItem(df[-row-1][1])\n self.model.setItem(row, 1, item)\n item = QStandardItem(df[-row-1][2])\n self.model.setItem(row, 2, item)\n\n else:\n for row in range(num):\n item = QStandardItem(str(df[-row-1][0]))\n self.model.setItem(row, 0, item)\n item = QStandardItem(str(df[-row-1][1]))\n self.model.setItem(row, 1, item)\n item = QStandardItem(str(df[-row-1][2]))\n self.model.setItem(row, 2, item)\n item.setBackground(QColor(255, 0, 0))\n\n def timeTable(self):\n text = self.lineEdit_3.text()\n # print(text)\n if (not re.match('^[0-9]+-[0-9]+', text)):\n QMessageBox.about(self, \"错误\", \"时间查询有误,请检查并重新输入\")\n else:\n self.s4 = TimeWindow()\n self.s4.setWindowTitle('回看数据')\n if not self.s4.isVisible():\n self.s4.show()\n\n def _create_csv(self):\n if (not os.path.exists('./database/database.csv')):\n with open('./database/database.csv', 'w+') as f:\n csv_write = csv.writer(f)\n csv_head = [\"ID\", \"Time\", \"Status\"]\n csv_write.writerow(csv_head)\n\n def createDB(self): #连接至数据库\n db = QSqlDatabase.addDatabase('QSQLITE')\n db.setDatabaseName('c:/ca_project/Demo/TestSql/database.db')\n\n if not db.open():\n QMessageBox.critical(None, (\"无法打开数据库\"),\n (\"无法建立到数据库的连接,这个例子需要SQLite 支持,请检查数据库配置。\\n\\n\"\n \"点击取消按钮退出应用。\"),\n QMessageBox.Cancel)\n return False\n\n\nclass SecondWindow(QWidget):\n def __init__(self, parent=None):\n super(SecondWindow, self).__init__(parent)\n self.resize(1010, 1010)\n self.label_10 = QtWidgets.QLabel(self)\n self.label_10.setGeometry(QtCore.QRect(5, 5, 1000, 1000))\n self.label_10.setFrameShadow(QtWidgets.QFrame.Plain)\n self.label_10.setLineWidth(10)\n self.label_10.setObjectName(\"label_10\")\n\nclass PlayBackWindow(QWidget):\n def __init__(self, parent=None):\n super(PlayBackWindow, self).__init__(parent)\n self.resize(1900, 910)\n self.table1 = QTableView()\n self.table1.setGeometry(QtCore.QRect(5, 5, 1800, 900))\n self.table1.setLineWidth(10)\n self.scene1 = QGraphicsScene(self)\n self.item1 = QGraphicsPixmapItem()\n #item1.setPixmap(QPixmap('./Miane.jpg'))\n # scene1 = QGraphicsScene()\n # scene1.addItem(item1)\n # self.table1.setModel(scene1)\n # self.label_10 = QtWidgets.QLabel(self)\n # self.label_10.setGeometry(QtCore.QRect(5, 5, 900, 900))\n # self.label_10.setFrameShadow(QtWidgets.QFrame.Plain)\n # self.label_10.setLineWidth(10)\n # self.label_10.setObjectName(\"label_10\")\n #\n # self.label_11 = QtWidgets.QLabel(self)\n # self.label_11.setGeometry(QtCore.QRect(5, 910, 900, 900))\n # self.label_11.setFrameShadow(QtWidgets.QFrame.Plain)\n # self.label_11.setLineWidth(10)\n # self.label_11.setObjectName(\"label_11\")\n\n\n\nclass PictureZoom(QMainWindow, Zoom_Window):\n \"\"\"\n Class documentation goes here.\n \"\"\"\n\n def __init__(self, parent=None, file_name = 'Miane.jpg'):\n \"\"\"\n Constructor\n\n @param parent reference to the parent widget\n @type QWidget\n \"\"\"\n super(PictureZoom, self).__init__(parent)\n self.setupUi(self)\n img = cv2.imread(file_name) # 读取图像\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换图像通道\n x = img.shape[1] # 获取图像大小\n y = img.shape[0]\n self.zoomscale = 1 # 图片放缩尺度\n frame = QImage(img, x, y, QImage.Format_RGB888)\n pix = QPixmap.fromImage(frame)\n self.item = QGraphicsPixmapItem(pix) # 创建像素图元\n # self.item.setScale(self.zoomscale)\n self.scene = QGraphicsScene() # 创建场景\n self.scene.addItem(self.item)\n self.picshow.setScene(self.scene) # 将场景添加至视图\n self.setWindowTitle(\"回放\")\n\n @pyqtSlot()\n def on_zoomin_clicked(self):\n \"\"\"\n 点击缩小图像\n \"\"\"\n # TODO: not implemented yet\n self.zoomscale = self.zoomscale - 0.05\n if self.zoomscale <= 0:\n self.zoomscale = 0.2\n self.item.setScale(self.zoomscale) # 缩小图像\n\n @pyqtSlot()\n def on_zoomout_clicked(self):\n \"\"\"\n 点击方法图像\n \"\"\"\n # TODO: not implemented yet\n self.zoomscale = self.zoomscale + 0.05\n if self.zoomscale >= 1.2:\n self.zoomscale = 1.2\n self.item.setScale(self.zoomscale) # 放大图像\n\n\n\nclass TimeWindow(QWidget):\n def __init__(self, parent=None):\n super(TimeWindow, self).__init__(parent)\n self.resize(400, 1800)\n self.tableView = QtWidgets.QTableView()\n self.tableView.setGeometry(QtCore.QRect(10, 10, 380, 1800))\n self.tableView.setObjectName(\"tableView\")\n self.model = QStandardItemModel(50, 3)\n self.model.setHorizontalHeaderLabels(['ID', 'Time', 'Status'])\n self.zoomWin = PictureZoom()\n\n for row in range(50):\n for column in range(3):\n item = QStandardItem(\"row %s, column %s\" % (row, column))\n self.model.setItem(row, column, item)\n\n # self.tableView = QTableView()\n self.tableView.setModel(self.model)\n self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)\n dlgLayout = QVBoxLayout()\n dlgLayout.addWidget(self.tableView)\n self.setLayout(dlgLayout)\n self.tableView.doubleClicked.connect(self.showZoomImg)\n\n def showZoomImg(self, index):\n #\n #QMessageBox.about(self, \"双击事件\", \"双击事件触发成功: \" + str(self.model.data(self.model.index(index.row(), 0))))\n\n self.zoomWin.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\n win = MainForm()\n #s = SecondWindow()\n #win.zoom_in.clicked.connect(s.handle_click)\n #win.btn.clicked.connect(ex.hide)\n win.show()\n sys.exit(app.exec_())\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":16525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"603217714","text":"'''\nThis code duplicates the sequence outlined in Prep.bat\n'''\n\n\nfrom sorting_gqsort import gqsort_Hgdat, gqsort_Hgdatext\nfrom forward_NDMMF import calc_Hg\n#debug\nfrom LOO import drop_ID\n#\nimport numpy as np\nimport os\nimport time\n\n# ##\n# This function calculates the Hg concentration for a left out observation\n# Parameters are estimated with the observation (and any broken connections) left out\n# then, the Hg concentration is calculated with those new, estimated parameters\n# ##\nMasterfile = 'NatfishFinalAllobs_20110617_MNF.csv'\nConnectionsfile = 'comparable_calcs_20110630.dat'\nID_to_drop = 1\n\ndatfile = 'Hgdata.dat'\nsrtfile = 'Hgdata.srt'\nextfile = 'Hgdata.datext'\nextsrtfile = 'Hgdata.datextsrt'\nndxfile = 'Hgdata.ndx'\n\n\n# read in and parse the entire validation data set\nMasterData = np.loadtxt(Masterfile,skiprows=1,delimiter=',')\nheaders = open(Masterfile,'r').readline().strip().split(',')\nMKind = headers.index('ID')\nID = MasterData[:,MKind].astype(int)\nSpC = MasterData[:,headers.index('SpC')].astype(int)\nevent = MasterData[:,headers.index('Event')].astype(int)\nlength = MasterData[:,headers.index('length')].astype(float)\nHg_obs = MasterData[:,headers.index('Hg')].astype(float)\n\n# adjust the weights by a log transformation\nWt = MasterData[:,headers.index('Wt')].astype(float)\nWt[Wt<2]=1\nWt = np.log(Wt) + 1.0\nMasterData[:,headers.index('Wt')]=Wt\n# debug printing of weights\n#np.savetxt('debug_weights',MasterData)\n\n# first find the event, species, and length of the ID that is to be dropped - this is required\n# later for the forward calculation\nindex_to_drop = np.nonzero(ID==ID_to_drop)[0]\ncsp = SpC[index_to_drop]\ncev = event[index_to_drop]\nclen = length[index_to_drop]\nobsHg = Hg_obs[index_to_drop]\n# find all IDs that need to be dropped\ndropIDs = drop_ID(ID_to_drop,Connectionsfile)\n\nMKlist = np.setdiff1d(ID,dropIDs)\n\n# make a set out of the ID field\n# SORT MasterData by ID\nMasterData = MasterData[MasterData[:,MKind].argsort()]\nMasterData[:,MKind] = MasterData[:,MKind].astype(int)\n\n\n\n# excellent way to dereference the Master Data - requires that the MasterData matrix\n# be sorted by MKind (done above outside the loop)\n# for more details see: \n#http://stackoverflow.com/questions/5505380/most-efficient-way-to-pull-specified-rows-from-a-2-d-array\nCurrMasterData = MasterData[np.searchsorted(MasterData[:,MKind],MKlist),:]\n \n\n# now, write out the datfile in proper formats\n# from Donato's code:\n# SPC, Event, length, Result, DL, WT\nofp = open(datfile,'w')\nfor line in CurrMasterData:\n ofp.write('%3d %7d %13.8f %13.8f %2d %13.8f\\n' \n %(line[6],line[7],line[1],line[4],line[3],line[2]))\nofp.close()\n\n# trim away any orphaned SpC or Events\nallSPC = np.unique(CurrMasterData[:,6])\nallEVENT = np.unique(CurrMasterData[:,7])\n# now read in the parameter starting values files and trim out irrelevant parameters\nspcdat = np.loadtxt('Hgspc.srt.master')\ncurrspc = spcdat[np.searchsorted(spcdat[:,0],allSPC),:] # see above for ref. on this technique\nofp = open('Hgspc.srt','w')\nfor line in currspc:\n ofp.write('%10d %20f\\n' %(line[0],line[1]))\nofp.close()\n\neventdat = np.loadtxt('Hgevent.srt.master')\ncurrevent = eventdat[np.searchsorted(eventdat[:,0],allEVENT),:] # see above for ref. on this technique\nofp = open('Hgevent.srt','w')\nfor line in currevent:\n ofp.write('%10d %20f\\n' %(line[0],line[1]))\nofp.close()\n\n\n# memory cleanup\ndel CurrMasterData\n\n# gqsort on Hgdata.dat, sorting by event, SPC, and DL\ngqsort_Hgdat(datfile,srtfile)\n\n# append a sequence number after sorting\n# analagous to MLEprep01.c and write out to extfile\n\nindat = np.loadtxt(srtfile)\nofp = open(extfile,'w')\ni = 0\nfor line in indat:\n i += 1\n ofp.write('%3d %7d %13.8f %13.8f %2d %13.8f %8d\\n'\n %(line[0],\n line[1],\n line[2],\n line[3],\n line[4],\n line[5],\n i))\nofp.close()\n\n# now sort by SPC\ngqsort_Hgdatext(extfile,extsrtfile)\n\n# Finally, strip out the index from extsrtfile and save in the .ndx file\nindat = np.loadtxt(extsrtfile)\nofp = open(ndxfile,'w')\nfor line in indat:\n ofp.write('%8d\\n' %(line[-1]))\nofp.close()\n\n\n\nos.exit()\n# call the external C-code Newton-Raphson parameter estimation code\nos.system('./NRparest') \n\n# finally, read in the results and make the Hg prediction for the left-out value\n# SpC parameters\nSpCpars = np.loadtxt('BestSPs')\n# Event parameters\nEventpars = np.loadtxt('BestEPs')\n\n# pull the parameter values necessary for calculating Hg for the left-out value\nspcind = np.nonzero(SpCpars[:,0]==csp)[0]\nevind = np.nonzero(Eventpars[:,0]==cev)[0]\n\n# calculate mercury for this index\ncHg = calc_Hg(SpCpars[spcind,1],Eventpars[evind,1],clen)\ncHg = (np.exp(cHg)-1)/1000.0\n# return the left-out modeled Hg concentraion.\n#return cHg, obsHg\n\n \n\n \n \n \n \n\n","sub_path":"RRS/LOOworking.py","file_name":"LOOworking.py","file_ext":"py","file_size_in_byte":4823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"82510891","text":"#!/usr/bin/env python\n'''\n Copyright (C) 2014 gWahl\n\n 'piSchedule' is an python extension for pilight \n Installed on RaspberryPI together with pilight it supports time scheduled\n switching of devices and with calling\n http:// + server + ':' + port + message\n\n 'server' and 'port' are those working with pilight and have to be \n stored in a file named 'piSchedule.prefs.json'\n\n 'message' is build from location, devices and time with state on/off.\n Those details have to be consistent with the pilight-config definitions\n and are stored in a JSON or INI file.\n That file name can be passed to piSchedule as an argument or be\n passed with piClient.py.\n\n 'Calling' ./piSchedule.py [argument]\n\n 'piSchedule.MD' more details and descriptions\n\n Schedule with 'Date/Time'\n A very flexible date/time handling is achieved with using \n [dateutil](http://labix.org/python-dateutil/). \n That utility allows piSchedule to support a very broad range of \n date/time formats.\n Also switching based on sunrise/sunset is possible. 'ephem' is used. \n Details see [pyphem](http://rhodesmill.org/pyephem/)\n'''\n# ------------------------------------------------------------------------------\nfrom __future__ import print_function\nimport os\nimport sys\nimport urllib2\nimport json\n\nimport datetime\nfrom datetime import date\nfrom dateutil import parser\n\nimport time\nfrom time import sleep\n\nfrom multiprocessing.connection import Listener\nfrom threading import Event, Thread\n\nimport socket\n\nimport ephem\nimport random\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\nimport struct\nimport re\n\n#import signal\n\n#def signal_handler(signal, frame):\n# print ('You pressed Ctrl+C!')\n# sys.exit(0)\n#signal.signal(signal.SIGINT, signal_handler)\n\n\n\ndef piParam():\n#---------------------------------\n parameter = {}\n def set(n, x):\n# print (n + \" is:\" + str(x))\n parameter[n] = x\n def get(n):\n if n is None:\n return \"\"\n else:\n try: ## make 'onTime' has datetime format\n return parameter[n]\n except:\n return None\n return set, get\npiSet,piGet=piParam()\n\n\n# globals\n#---------------------------------\n__version__ = '0.1g'\n\n\ndef discover(service, timeout=2, retries=1):\n#---------------------------------\n group = (\"239.255.255.250\", 1900)\n message = \"\\r\\n\".join([\n 'M-SEARCH * HTTP/1.1',\n 'HOST: {0}:{1}'.format(*group),\n 'MAN: \"ssdp:discover\"',\n 'ST: {st}','MX: 3','',''])\n\n responses = {}\n i = 0;\n for _ in range(retries):\n i += 1\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack('LL', 0, 10000));\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)\n sock.sendto(message.format(st=service), group)\n while True:\n try:\n responses[i] = sock.recv(1024);\n break;\n except socket.timeout:\n break;\n except:\n print (\"no pilight ssdp connections found\")\n break;\n return responses.values()\n\n\nsched = BackgroundScheduler()\njobs = [] # store scheduled tasks\n\ndef clearTerm():\n if os.name == 'nt':\n command = 'cls'\n else:\n command = 'clear'\n os.system(command)\n\n\ndef suntime():\n#---------------------------------\n# support Sunrise/Sunset with time values\n# time is calculated for actual day!\n\n if (piGet('latitude')) and (piGet('longitude')):\n\n atHome = ephem.Observer()\n atHome.date = datetime.datetime.now()\n atHome.lat = piGet('latitude')\n atHome.lon = piGet('longitude')\n\n sun = ephem.Sun()\n piSet('sunrise', ephem.localtime(atHome.next_rising(sun, date.today())))\n piSet('sunset', ephem.localtime(atHome.next_setting(sun, date.today())))\n\n piSet('geo_message',\"\\033[1m GeoLocation\\033[0m\"\n + \"\\n \" + piGet('location')\n + \" Latitude: \" + piGet('latitude') + \" Longitude: \" + piGet('longitude')\n + \"\\n Sunrise: \" + str(piGet('sunrise'))[:19] + \" sunset: \" + str(piGet('sunset'))[:19])\n\n else:\n piSet('geo_message',\"*** pilight/piScheduler 'prefs': \\033[1m GeoCoordinates not supported!\\033[0m\")\n\n\ndef fire_pilight(message):\n#---------------------------------\n message0 = message.split('|')\n message1 = message0[0]\n message2 = \"\"\n if len(message0) > 1:\n message2 = message0[1]\n\n url = ('http://' + piGet('server') + ':' + piGet('port') + message1)\n# print (\" ... piSchedule \" + str(datetime.datetime.now()) + \" | \" + message2\n# + \"\\n url:\", url)\n\n request = urllib2.Request(url)\n response = urllib2.urlopen(request)\n\n\ndef pilightSchedule(onTime, switchLocation, actualDevice, currentSwitch):\n#---------------------------------\n global jobs # holds all scheduled 'fire_pilight' jobs\n\n actualSwitch = currentSwitch.strip().split(\",\")\n message = '/send?{\"message\":\"send\",\"code\":{\"location\":\"' + switchLocation \\\n + '\",\"device\":\"' + str(actualDevice) \\\n + '\",\"state\":\"' + str(actualSwitch[0]) + '\"}}'\n\n # piSchedule direct on/off switching \n if len(actualSwitch) == 1:\n fire_pilight(message)\n sleep(2) # for testing .. delay between directly switching\n return()\n\n xTime = datetime.datetime.now()\n deltaTime = \"*\"\n\n # check xTime if valid and process different time options\n # xTime = '2014-04-17 22:06:00' NEED secs, even if ':00'\n\n for nSwitch in actualSwitch:\n\n # have dateTime or sunrise or sunset\n if nSwitch == 'sunrise':\n xTime = piGet('sunrise')\n elif nSwitch == 'sunset':\n xTime = piGet('sunset')\n\n\n # --- use deltaTime \n # '+' add or '-' subtract time value\n # '~' add or '~-' subtract 'random' time value\n elif nSwitch[0] == '+' or nSwitch[0] == \"-\" \\\n or nSwitch[0] == \"~\":\n h = 0\n min = 0\n sec = 0\n\n random_subtract = False\n if nSwitch[0:2] == \"~-\": # subtract random time \n random_subtract = True\n delta = nSwitch[2:]\n else:\n delta = nSwitch[1:]\n\n xDelta = delta.split(\":\")\n nDelta = len(xDelta)\n if nDelta >= 1:\n h = 0 if xDelta[0] =='' else int(xDelta[0])\n if nDelta >= 2:\n min = 0 if xDelta[1] =='' else int(xDelta[1])\n if nDelta == 3:\n sec = 0 if xDelta[2] =='' else int(xDelta[2])\n deltaTime = datetime.timedelta(hours=h, minutes=min, seconds=sec)\n\n if nSwitch[0] == '+': ## add timedelta\n print (\" delta + : \", nSwitch)\n\n if nSwitch[0] == '-': ## substract timedelta\n print (\" delta - : \", nSwitch)\n deltaTime = -deltaTime\n\n elif nSwitch[0] == '~': ## add random minutes \n rMin = h*60 + min\n print (\" random : \", nSwitch)\n if random_subtract:\n deltaTime = datetime.timedelta(minutes=random.randrange(rMin))\n else:\n deltaTime = datetime.timedelta(minutes=random.randrange(rMin))\n print (\" deltaTime : \", deltaTime)\n # ... use deltaTime\n\n elif nSwitch == 'on' or nSwitch == \"off\" :\n pass\n else:\n xTime = parser.parse(nSwitch)\n\n if deltaTime != \"*\":\n xTime = (xTime + deltaTime)\n\n # make sure xTime has correct datetime type/format\n if str(type(xTime)) == \"\":\n xTime = parser.parse(xTime) \n\n # remember 'on' state time, for 'off' set to now\n if actualSwitch[0] == 'on':\n onTime = xTime\n else:\n onTime = datetime.datetime.now()\n\n # check if xTime is before actual time\n if (xTime < datetime.datetime.now()):\n print (\" *** error : \", str(xTime)[0:19],\n \" :: \" + currentSwitch.strip(), \" *** before current time ***\")\n else:\n print (\" xTime : \", str(xTime)[0:19], \" ::\", currentSwitch)\n jobName = str(int(time.time()*1000))[6:]\n\n info = '{0:14} {1:14} {2:15}'.format(switchLocation[0:12], actualDevice[0:12], currentSwitch).replace(',',' ')\n jobs.append(sched.add_job(fire_pilight, 'date', run_date=str(xTime), args=[message + \"|\" + info], name=jobName))\n\n return onTime\n\n\ndef jobListINI(jobList, name):\n#---------------------------------\n '''\n ebene1; lampe2; on\n ebene1; lampe2; on,22:50;off,+:10\n ebene1; lampe2; on,+:02; off,+:03:00\n * text/comment\n ebene1; lampe2; on,+:02;off,+:03:00\n ebene1; lampe2; on,+01:02,sunrise;off,-01:30,sunset;on,~:10,18:00;off,~:15,21:05\n '''\n\n for cJobs in jobList:\n cJobs = cJobs.strip()\n # strip out empty or comment lines \n if len(cJobs) == 0 or cJobs[0] == '*':\n continue\n\n print (' {0} - Job >{1}<'.format(name, cJobs))\n\n cJob = cJobs.split(\";\")\n cJobLen = len(cJob)\n if cJobLen > 1 :\n switchLocation = cJob[0].strip()\n actualDevice = cJob[1].strip()\n\n now = datetime.datetime.now()\n n = 2\n while n < (cJobLen):\n currentSwitch = cJob[n].strip()\n now = pilightSchedule(now, switchLocation, actualDevice, currentSwitch)\n n += 1\n\ndef jobListJSON(jobFile):\n#---------------------------------\n jobList = json.loads(jobFile.read())\n for cJob in jobList:\n\n location = jobList[cJob][\"location\"]\n for aLocation in location:\n switchLocation = str(aLocation)\n cLocation = location[aLocation]\n\n for actualDevice in cLocation:\n print (\" ----------\")\n\n # switch directly with on/off\n if ('on' in cLocation[actualDevice]) or ('off' in cLocation[actualDevice]):\n message = '/send?{\"message\":\"send\",\"code\":{\"location\":\"' + switchLocation \\\n + '\",\"device\":\"' + str(actualDevice) \\\n + '\",\"state\":\"' + str(cLocation[actualDevice]) + '\"}}'\n\n # +++ piSchedule direct on/off switching\"\n fire_pilight(message)\n sleep(2) # for testing .. delay between directly switching\n\n # using the APScheduler for 'Simple date-based scheduling'\n if 'switch' in cLocation[actualDevice]:\n currentSwitch = cLocation[actualDevice]['switch']\n\n sTimes = str(currentSwitch).strip().split(\";\")\n sTimesLen = len(sTimes)\n now = datetime.datetime.now()\n print (\" +++ piSchedule : \", str(now)[0:19], \" ::\", str(currentSwitch))\n\n jNo = 0\n while jNo < sTimesLen:\n pass\n now = pilightSchedule(now, switchLocation, actualDevice, sTimes[jNo])\n jNo += 1\n\n\ndef next_switchTime():\n#---------------------------------\n nextSwitchTime = piGet('nextSwitchTime')\n\n if date.today() == nextSwitchTime:\n nextSwitchTime = date.today() + datetime.timedelta(hours=24)\n suntime()\n\n piSet('nextSwitchTime', nextSwitchTime)\n return nextSwitchTime\n\n\ndef updateJobsListing():\n#---------------------------------\n clearTerm()\n print (piGet('mainTitle'), \n str(datetime.datetime.now())[:19], \n \" (\", str(piGet('nextSwitchTime'))[:19] + \")\",\n \"\\n\" + piGet('geo_message'),\n \"\\n\" + \"\\033[1m Current Jobs \\033[0m\" + \" [\" + str(piGet('job_file')) + \"]\")\n\n\n if len(sched.get_jobs()) == 0:\n pass \n #exit()\n else:\n n = 0\n output = []\n while n < len(sched.get_jobs()):\n info = str(sched.get_jobs()[n].args).split('|')\n\n output.append(\" \" + (str(sched.get_jobs()[n].trigger).replace(\"date\",'') + \" \"\n + str(sched.get_jobs()[n].name) + \" \"\n + info[1].replace(\"',)\",'')))\n n += 1\n output.sort()\n\n n = 0\n while n < len(output):\n print (output[n])\n n += 1\n\n\ndef job_commands(message, name):\n#---------------------------------\n if message != None:\n # process as new switch file or string passing\n if '.json' in message or '.ini' in message:\n piSet('job_file', message)\n try:\n jobFile = open(message, 'r')\n if '.json' in message:\n jobListJSON(jobFile)\n if '.ini' in message:\n jobListINI(jobFile, name)\n\n finally:\n pass\n\n else:\n # ebene1; lampe2; on,22:00\n jobListINI([message], name)\n\n\ndef jobs_listing(exit_event, name, calling):\n#---------------------------------\n try:\n while not exit_event.is_set(): # loop to keep scheduler alive\n updateJobsListing()\n ''' TODO\n replace with threading /Event \n see http://blog.thomnichols.org/2010/11/use-pythons-threadingevent-for-interruptable-sleep\n '''\n if date.today() == piGet('nextSwitchTime'):\n next_switchTime()\n if name == \"\":\n pass\n # log this to file\n else:\n job_commands(piGet('job_file'), name)\n if calling != \"\":\n job_commands(piGet('job_file'), calling)\n calling = \"\"\n sleep(10)\n\n finally:\n print (' piScheduler - Exit >{0}<'.format(name))\n\n\ndef job_serve(exit_event, name):\n#---------------------------------\n address = (piGet('server'), 6000)\n listener = Listener(address, authkey='secret password')\n\n try:\n while True:\n connection = listener.accept()\n message = connection.recv().strip()\n\n #\n # process the incoming message...\n #\n# print (' .... incoming msg: ', message)\n if (message[0] != \"-\"):\n job_commands(message, name)\n\n else:\n print(' {0} - Command >{1}<'.format(name, message[1:]))\n\n if message[1:] == 'close':\n break\n\n if message[1:] == 'update':\n updateJobsListing()\n except:\n pass\n\n finally:\n caller = str(listener.last_accepted)\n if caller == 'None':\n caller = 'User'\n print(' {0} - Connection closed from {1}'.format(name, caller))\n\n exit_event.set()\n listener.close()\n sched.shutdown()\n sys.exit(0)\n\n\ndef startup():\n#---------------------------------\n os.system('clear')\n\n now = datetime.datetime.now()\n next = next_switchTime()\n\n title1 = piGet('mainTitle') + str(now)[0:19] + \" next: \" + str(next)\n\n jPrefs = 'piSchedule.prefs.json'\n try:\n prefsFile = open(jPrefs, 'r')\n except:\n print (title1, \"\\n*** pilight/piScheduler 'prefs' file \\033[1m'\",\n jPrefs, \"'\\033[0m not found!\")\n exit()\n\n\n prefs = json.loads(prefsFile.read())\n\n# responses = discover(\"urn:schemas-upnp-org:service:pilight:1\");\n# print ('***** discover values **** : \\n', str(responses),'\\n\\n')\n responses = \"\" # TODO \n\n if len(responses) > 0:\n locationsrc = re.search('Location:([0-9.]+):(.*)', str(responses[0]), re.IGNORECASE)\n if locationsrc:\n server = locationsrc.group(1)\n port = locationsrc.group(2)\n\n print (\" **** discover server/port : \", server, port)\n\n if 'server' in prefs:\n piSet('server', prefs['server'])\n else:\n print (title1, \"\\n*** pilight/piScheduler 'prefs' \\033[1m'server'\\033[0m not found!\")\n exit()\n\n if 'port' in prefs:\n piSet('port', prefs['port'])\n else:\n print (title1, \"\\n*** pilight/piScheduler 'prefs' \\033[1m'port'\\033[0m not found!\")\n exit()\n\n next_switchTime()\n# suntime(prefs) #sunrise, sunset, geoInfo = geo_info(prefs)\n if ('Latitude' in prefs) and ('Longitude' in prefs):\n\n piSet('latitude', str(prefs['Latitude']))\n piSet('longitude', str(prefs['Longitude']))\n if 'Location' in prefs:\n piSet('location', str(prefs['Location']))\n suntime()\n else:\n piSet('geo_message',\"*** pilight/piScheduler 'prefs': \\033[1m GeoCoordinates not supported!\\033[0m\")\n\n print (piGet('mainTitle'), \" \",\n str(datetime.datetime.now())[:19], \" next: \", str(next)[:19],\n \"\\n\", piGet('geo_message'))\n\n\ndef main():\n#---------------------------------\n print ('Number of arguments:', len(sys.argv), 'arguments.')\n print ('Argument List:', str(sys.argv))\n\n if len(sys.argv) == 2:\n calling = sys.argv[1]\n piSet('job_file', calling)\n else:\n calling = ' .. ' + str(datetime.datetime.now())\n\n sched.start() # start the scheduler\n piSet('mainTitle', \"\\033[1mpiScheduler vers.\" + __version__ + \"\\033[0m\" + \" \")\n piSet('nextSwitchTime', date.today())\n\n exit_event = Event()\n startup()\n Thread(target=jobs_listing, args=(exit_event, 'pilight Jobs', calling)).start()\n job_serve(exit_event, 'piScheduler')\n\n print ('are we done??')\n sched.shutdown()\n exit()\n#---------------------------------\nif __name__ == \"__main__\":\n main()\n","sub_path":"piSchedule.py","file_name":"piSchedule.py","file_ext":"py","file_size_in_byte":17283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"583091805","text":"import time\nimport gevent\nimport urllib2\nimport simplejson as json\n\nimport gevent.monkey\ngevent.monkey.patch_socket()\n\n\ndef fetch(pid):\n response = urllib2.urlopen('http://api.douban.com/labs/bubbler/user/ahbei')\n result = response.read()\n json_result = json.loads(result)\n uid = json_result['uid']\n\n print('Process %s: %s' % (pid, uid))\n return json_result['uid']\n\n\ndef synchronous():\n for i in range(1, 50):\n fetch(i)\n\ndef asychronous():\n threads = [gevent.spawn(fetch, i) for i in range(1, 50)]\n gevent.joinall(threads)\n\n\nprint('Synchronous:')\nsynchronous()\n\nprint('Asynchronous:')\nasychronous()\n","sub_path":"gevent_tutorial/asyn_fech_data.py","file_name":"asyn_fech_data.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"546901816","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 14 10:22:31 2017\n\n@author: yinghuang\n\"\"\"\n\nimport os\nimport fnmatch\n\nCSV_PATH = \"D:/Development/hy_code/MachineLearning/Tensorflow/GameCharacters_Tensorflow/Samples/\"\nDATA_PATH = \"D:/Development/hy_code/MachineLearning/Tensorflow/GameCharacters_Tensorflow/Samples/\"\nTF_RECORDS_PATH = \"D:/Development/hy_code/MachineLearning/Tensorflow/GameCharacters_Tensorflow/Samples/\"\nRUN_TF_RECORDS_PATH = \"D:/Development/hy_code/MachineLearning/Tensorflow/GameCharacters_Tensorflow/Samples_CoolRunning/\"\nMODELS_PATH = \"D:/Development/hy_code/MachineLearning/Tensorflow/GameCharacters_Tensorflow/Models/\"\nTEST_TF_FILE = TF_RECORDS_PATH + \"test*.tfrecords\"\nTRAIN_TF_FILE = TF_RECORDS_PATH + \"train*.tfrecords\"\nRUN_TEST_TF_FILE = RUN_TF_RECORDS_PATH + \"test*.tfrecords\"\nRUN_TRAIN_TF_FILE = RUN_TF_RECORDS_PATH + \"train*.tfrecords\"\nTEST_CSV_FILE = CSV_PATH+\"test.csv\"\nTRAIN_CSV_FILE = CSV_PATH+\"train.csv\"\nMODEL_NAME = \"Num.pb\"\nFREEZE_MODEL_NAME = \"ModelsNum.pb\"\n\nROWS = 28\nCOLS = 28\nDEPTH = 1\n\n# Training for Poker, Poker has 82921 samples in training set and 28767 samples in testing set.\nPOKER_TRAIN_SAMPLES = 82921\nPOKER_TEST_SAMPLES = 28767\n\n# Training for CoolRunning, CoolRunning has 32342 samples in training set\nRUN_TRAIN_SAMPLES = 32342\nRUN_TEST_SAMPLES = 7362\n\ndef IterFindFiles(path, fnexp):\n for root, dirs, files in os.walk(path):\n for filename in fnmatch.filter(files, fnexp):\n yield os.path.join(root, filename)\n\ndef FindTFRecordsFiles(path, file):\n data = []\n fileFilter = file + \"*\" + \".tfrecords\"\n for filename in IterFindFiles(path, fileFilter) :\n print (filename)\n data.append(filename)\n return data\n\n#统计某文件夹下文件的个数 \n#ls -l |grep \"^-\"|wc -l\n#\n#统计某文件夹下目录的个数  \n#ls -l |grep \"^d\"|wc -l\n#\n#统计文件夹下文件的个数,包括子文件夹里的  \n#ls -lR|grep \"^-\"|wc -l","sub_path":"scikit-learning/MNIST/PythonClassifierApplication1/PythonClassifierApplication1/FileDefines.py","file_name":"FileDefines.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"34886048","text":"'''\r\n116-Easygui buttonbox with image\r\n\r\npip3 install easygui\r\n\r\nBy Steve Shambles July 2019\r\nVisit my blog for more snippets like this\r\nstevepython.wordpress.com\r\n'''\r\nfrom easygui import buttonbox\r\n\r\nimage = \"test.jpg\"\r\nmsg = \"Do you like this picture?\"\r\nchoices = [\"Yes\", \"No\", \"No opinion\", \"Hate it\"]\r\nreply = buttonbox(msg, image=image, choices=choices)\r\n\r\nif reply == \"Yes\":\r\n print(\"Jen say's that's very kind of you to say so.\")\r\n\r\nif reply == \"No\":\r\n print(\"Okay, you are entitled to your incorrect opinion I guess.\")\r\n\r\nif reply == \"No opinion\":\r\n print(\"You just sit on the fence then, you schmuck.\")\r\n\r\nif reply == \"Hate it\":\r\n print(\"How dare you insult the lovely Jen.\")\r\n","sub_path":"Python-code-snippets-101-200/119-easygui-buttonbox with image.py","file_name":"119-easygui-buttonbox with image.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"194254508","text":"print('-' * 30)\nprint(' ' * 5, 'LOJA SUPER BARATÃO')\nprint('-' * 30)\ncont = menor = soma = mil = 0\nnmMenor = ''\n\nwhile(True):\n\n nmProd = str(input('Nome do produto: '))\n precoProd = float(input('Preço do produto: '))\n print('-=' * 10)\n\n soma += precoProd\n\n if(precoProd > 1000):\n mil += 1\n\n if(cont == 0 or precoProd <= menor):\n menor = precoProd\n nmMenor = nmProd\n cont += 1\n\n if(input('Quer continuar [S/N]').strip().upper()[0] == 'N'):\n break\n print('-=' * 10)\n\n\nprint('-' * 10, 'FIM DO PROGRAMA','-' * 10)\nprint('O total da compra foi R${:.2f}'.format(soma))\nprint(f'Temos {mil} produtos custando mais de R$ 1000.00')\nprint('O Produto mais barato foi a {} que custa {:.2f}'.format(nmMenor,menor))","sub_path":"exercicios/ex070.py","file_name":"ex070.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"367680016","text":"from django.conf.urls import url, include\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\n\nurlpatterns = [\n\t#POST\n\turl(r'^$', views.post_home, name='post_home'),\n\turl(r'^create/$', views.post_create, name='post_create'),\t\t\t\t\t\n\turl(r'^posts/(?P\\d+)$', views.post_detail, name='post_detail'),\t\t\t\n\turl(r'^posts/(?P\\d+)/edit/$', views.post_update, name='post_update'),\t\n\turl(r'^posts/(?P\\d+)/delete/$', views.post_delete, name='post_delete'),\t\n\t#LOGIN\n\turl(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='user_login'),\n\turl(r'^logout/$', views.logout_view, name='user_logout'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"138729228","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n\ndef fcl_anno_only(pair_list, song_length):\n \"\"\"\n Finds annotations for all pairs of repeats found in previous step\n \n Args\n ----\n pair_list: \n list of pairs of repeats\n WARNING: bandwidths must be in ascending order\n \n song_length: int\n number of audio shingles in song\n \n Returns\n -------\n out_lst:\n list of pairs of repeats with smaller repeats added and with\n annotation markers\n \"\"\"\n # Find list of unique repeat lengths\n bw_found = np.unique(pair_list[:,4])\n bw_num = bw_found.shape[0]\n \n # Remove longest bandwidth row if it is the length of the full song\n if song_length == bw_found[bw_num - 1]:\n pair_list[-1,:] = []\n bw_found[-1] = []\n bw_num = (bw_num - 1)\n p = pair_list.shape[0]\n \n # Add annotation markers to each pair of repeats\n full_list = []\n for j in range(bw_num):\n band_width = bw_found[j]\n # Isolate pairs of repeats of desired length\n bsnds = np.amin(np.nonzero(pair_list[:,4] == band_width))\n bends = np.nonzero(pair_list[:,4] > band_width)\n \n if np.size(bends) > 0:\n bends = np.amin(bends)\n else:\n bends = p\n \n bw_mat = np.array((pair_list[bsnds:bends,]))\n bw_mat_length = bw_mat.shape[0]\n \n temp_anno_mat = np.concatenate((bw_mat, (np.zeros((bw_mat_length,1)))),\n axis = 1).astype(int)\n\n # Get annotations for this bandwidth\n temp_anno_list = add_annotations(temp_anno_mat, song_length)\n full_list.append(temp_anno_list)\n \n out_list = np.concatenate(full_list)\n \n return out_list\n\n","sub_path":"separated-functions/find_complete_list_anno_only.py","file_name":"find_complete_list_anno_only.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"86328457","text":"from models.modules.moduleEnum import ModuleEnum\nfrom models.module import Module\nfrom bs4 import Tag\nfrom json import JSONEncoder\n#This module matches the Columns module that exists on Wordpress\nclass Columns(Module):\n def __init__(self, tag: Tag):\n #Module enumerator\n self.type = ModuleEnum.COLUMN\n self.tag = tag\n #Header of column module\n self.headers = [] \n #Array of html for each column\n self.contents = []\n\n descendants = tag.descendants\n for element in descendants:\n if type(element) is Tag and \"h\" in element.name:\n self.headers.append(element.prettify())\n elif type(element) is Tag and element.name == \"ul\":\n self.contents.append(element.prettify())\n \n @staticmethod\n def isValid(tag: Tag):\n valid = False\n classString = \"\"\n if type(tag) is Tag and \"class\" in tag.attrs:\n classString = tag.attrs[\"class\"]\n classString = \"\".join(classString)\n if tag.name == \"div\" and \"columns\" in classString:\n descendants = tag.descendants\n for element in descendants:\n if type(element) is Tag and \"h\" in element.name:\n valid = True\n break\n elif type(element) is Tag and element.name == \"ul\":\n valid = True\n break\n return valid\n \n def reprJSON(self):\n oDict = self.__dict__\n oDict[\"type\"] = \"COLUMN\"\n oDict.pop(\"tag\", None)\n return JSONEncoder().encode(oDict)\n ","sub_path":"models/modules/columns.py","file_name":"columns.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"552516142","text":"#BAEKJUN 14681\n#흔한 수학 문제 중 하나는 주어진 점이 어느 사분면에 속하는지 알아내는 것이다. 사분면은 아래 그림처럼 1부터 4까지 번호를 갖는다. \"Quadrant n\"은 \"제n사분면\"이라는 뜻이다.\n\nx=int(input())\ny=int(input())\n\nif x!=0 and y!=0:\n if x > 0:\n if y > 0:\n print(\"1\")\n else:\n print(\"4\")\n else:\n if y > 0:\n print(\"2\")\n else:\n print(\"3\")\n","sub_path":"BEAKJUN 14681.py","file_name":"BEAKJUN 14681.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"182002999","text":"# -*- coding: utf-8 -*-\n\n\n\"\"\"setup.py: setuptools control.\"\"\"\n\n\nimport re\nfrom setuptools import setup\n\nversion = \"0.0.1\"\n\nwith open(\"README.md\", \"rb\") as f:\n long_descr = f.read().decode(\"utf-8\")\n\nsetup(\n name=\"Jpoc\",\n packages=[\"jpoc\"],\n entry_points={\n\n \"console_scripts\": ['jpoc = jpoc.bootstrap:main']\n\n },\n version=version,\n description=\"Python command line application bare bones.\",\n long_description=long_descr,\n author=\"cah-cesar-medrano\",\n author_email=\"cesar.medrano@cardinalhealth.com\",\n)\n","sub_path":"Archive/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"77440489","text":"from Tkinter import *\nimport time\nfrom picamera import PiCamera\nfrom picamera.array import PiRGBArray\nimport cv2\nfrom PIL import Image,ImageTk\n\ndef camera_setup():\n camera=PiCamera()\n camera.resolution=(640,480)\n camera.framerate=30\n rawCapture=PiRGBArray(camera,size=(640,480))\n time.sleep(0.1)\n'''\nfor frame in camera.capture_continuous(rawCapture,format=\"bgr\",use_video_port=True):\n image=frame.array\n cv2.imshow(\"Frame\",image)\n key=cv2.waitKey(1) & 0xFFF\n rawCapture.truncate(0)\n if key == ord(\"q\"):\n break\n'''\ndef video_loop():\n success, image = frame.array \n if success:\n cv2.waitKey(1) & 0xFFF\n #cv2image = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)\n current_image = Image.fromarray(image)\n imgtk = ImageTk.PhotoImage(image=current_image)\n panel.imgtk = imgtk\n panel.config(image=imgtk)\n root.after(1, video_loop)\n\n\ncamera = cv2.VideoCapture(0) \n\nroot = Tk()\nroot.title(\"opencv + tkinter\")\n#root.protocol('WM_DELETE_WINDOW', detector)\n\npanel = Label(root) # initialize image panel\npanel.pack(padx=10, pady=10)\nroot.config(cursor=\"arrow\")\n\nvideo_loop()\n\nroot.mainloop()\ncamera.release()\ncv2.destroyAllWindows()\n","sub_path":"Mobile Embedded/Source_code/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"316001937","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport os\nimport rospy\nimport requests\nimport pandas as pd\n\nfrom std_srvs.srv import Empty, EmptyResponse, Trigger, TriggerRequest\n\nscorefile_path = os.path.join(os.path.dirname(__file__), '..')+\"/scorefile.txt\"\nteam = \"default-usr1\"\n\ndef add_new_scores_to_db(req):\n scores = pd.read_csv(scorefile_path, header=None,\n names=[\"Timestamp\", \"Map\", \"Score\", \"Sent\"])\n\n if not scores['Sent'].all():\n update = scores[scores['Sent']==0]\n for map_name in update['Map'].unique():\n\n new_scores = update[update['Map']==map_name]['Score'].values.tolist()\n for score in new_scores:\n result = requests.post( \n 'https://europe-west1-hackathon-af6d5.cloudfunctions.net/addScore',\n data = {'Map':map_name, 'Team':team, 'Score':score})\n\n if result.status_code != 200:\n return EmptyResponse()\n \n\n if result.status_code == 200:\n scores['Sent'].values[:] = 1\n scores.to_csv(scorefile_path, header=False, index=False)\n\n return EmptyResponse()\n\ndef main():\n global team\n #Init ROS node\n rospy.init_node('scoreboard_service')\n rospy.wait_for_service(\"/teamname\")\n teamname_service = rospy.ServiceProxy(\"/teamname\", Trigger)\n while True:\n res = teamname_service(TriggerRequest())\n if res.success:\n team = res.message\n break\n \n rospy.loginfo(\"Scoreboard server ready for team: \" + team)\n\n s = rospy.Service(\"/publish_scores\", Empty, add_new_scores_to_db)\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n main()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"catkin_ws/src/game_master/scripts/scoreboard_server.py","file_name":"scoreboard_server.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"398208826","text":"def solve( case ):\r\n caseArray = case.split()\r\n k, c, s = (int(x) for x in caseArray)\r\n\r\n if(k == 1):\r\n return 1\r\n return ' '.join([str(k) for k in range(1, k+1)])\r\n \r\ncaseNumbers = input()\r\nfor caseN in xrange(1, caseNumbers+1):\r\n case = raw_input()\r\n print(\"Case #%i: %s\" % (caseN, solve(case)))\r\n","sub_path":"codes/CodeJamCrawler/16_0_4_neat/16_0_4_BTores_D.py","file_name":"16_0_4_BTores_D.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"583568359","text":"#Name=Bharath.P.S\n#email=pedaballibharath@gmail.com\n\nk=int(input())\nif(2<=k<=10):\n def pascal(k):\n line = [1]\n for x in range(max(k,0)):\n line.append(int(line[x]*(k-x)/(x+1)))\n return line\n\n for i in range(k):\n lst = pascal(i)\n\n for j in range(len(lst)):\n print(lst[j],end=\" \") \n print() \n","sub_path":"Bharath_PS_Day5.py","file_name":"Bharath_PS_Day5.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"51460484","text":"import glob, os\nfrom PIL import Image\nimport numpy as np\nimport math\n\ndef moyfond(im, moy, alpha):\n\tmoy = abs(np.multiply(alpha, im) + np.multiply((1-alpha), moy))\n\timM = np.multiply(moy, -1)\n\tD = abs(im + np.multiply(moy, -1))\n\treturn moy, D\n\t\n\nalpha = 0.1\nmoy = np.zeros((480, 752, 3))\nn = 0\n\nfor infile in glob.glob (\"*.png\"):\n\tfile, ext = os.path.splitext(infile)\n\tim = Image.open(infile)\n\tif n == 0 :\n\t\tmoy = im\n\t\tn+=1\n\telse:\n\t\tmoy, D = moyfond(im, moy, alpha)\n\t\tD = Image.fromarray(np.uint8(D))\n\t\tD.save(\"background/\" + file + \".thumbnail\", \"PNG\")\n\t\tn+=1\n","sub_path":"moyenneFond/moyenneFond.py","file_name":"moyenneFond.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"624632464","text":"from plato.tools.cost import negative_log_likelihood_dangerous\nfrom plato.tools.networks import MultiLayerPerceptron\nfrom plato.tools.online_prediction.online_predictors import GradientBasedPredictor\nfrom plato.tools.optimizers import SimpleGradientDescent\nfrom plato.tools.simple_sampling_regressors import GibbsRegressor, HerdedGibbsRegressor\nfrom utils.predictors.predictor_tests import assert_online_predictor_not_broken\nfrom pytest import raises\nimport numpy as np\n\n__author__ = 'peter'\n\n\ndef test_mlp():\n\n assert_online_predictor_not_broken(\n predictor_constructor = lambda n_dim_in, n_dim_out:\n GradientBasedPredictor(\n function = MultiLayerPerceptron(\n layer_sizes = [100, n_dim_out],\n input_size = n_dim_in,\n output_activation='softmax',\n w_init = lambda n_in, n_out, rng = np.random.RandomState(3252): 0.1*rng.randn(n_in, n_out)\n ),\n cost_function=negative_log_likelihood_dangerous,\n optimizer=SimpleGradientDescent(eta = 0.1),\n ).compile(),\n categorical_target=True,\n minibatch_size=10,\n n_epochs=2\n )\n\n\ndef test_mlp_with_scale_learning():\n\n assert_online_predictor_not_broken(\n predictor_constructor = lambda n_dim_in, n_dim_out:\n GradientBasedPredictor(\n function = MultiLayerPerceptron(\n layer_sizes = [100, n_dim_out],\n input_size = n_dim_in,\n output_activation='softmax',\n scale_param = True,\n w_init = lambda n_in, n_out, rng = np.random.RandomState(3252): 0.1*rng.randn(n_in, n_out)\n ),\n cost_function=negative_log_likelihood_dangerous,\n optimizer=SimpleGradientDescent(eta = 0.1),\n ).compile(),\n categorical_target=True,\n minibatch_size=10,\n n_epochs=2\n )\n\n\ndef test_gibbs_logistic_regressor():\n\n assert_online_predictor_not_broken(\n predictor_constructor = lambda n_dim_in, n_dim_out:\n GibbsRegressor(n_dim_in = n_dim_in, n_dim_out = n_dim_out,\n n_alpha = 1,\n possible_ws= (-1, 1),\n seed = 2143\n ).compile(),\n n_extra_tests = 8,\n n_epochs=20\n )\n\n\ndef test_herded_logistic_regressor():\n\n assert_online_predictor_not_broken(\n predictor_constructor = lambda n_dim_in, n_dim_out:\n HerdedGibbsRegressor(n_dim_in = n_dim_in, n_dim_out = n_dim_out,\n n_alpha = 1,\n possible_ws= (-1, 1),\n ).compile(),\n n_epochs=20\n )\n\n\ndef test_gibbs_logistic_regressor_full_update():\n \"\"\"\n This test just demonstrates that you can't just go and update all the weights at once -\n it won't work.\n \"\"\"\n\n with raises(AssertionError):\n assert_online_predictor_not_broken(\n predictor_constructor = lambda n_dim_in, n_dim_out:\n GibbsRegressor(n_dim_in = n_dim_in, n_dim_out = n_dim_out,\n n_alpha = n_dim_in, # All weights updated in one go.\n possible_ws= (-1, 1),\n seed = 2143\n ).compile(),\n n_epochs=80\n )\n\n\nif __name__ == '__main__':\n test_mlp_with_scale_learning()\n test_gibbs_logistic_regressor()\n test_herded_logistic_regressor()\n test_gibbs_logistic_regressor_full_update()\n test_mlp()\n","sub_path":"utils/predictors/test_predictors.py","file_name":"test_predictors.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"484411603","text":"# Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT\n# All rights reserved. This work is under a BSD license, see LICENSE.TXT.\n\nfrom __future__ import print_function\n\nimport sys, os, copy\nfrom collections import OrderedDict\nimport json\n\nfrom .envs import EnvFactory, Env, EnvException\nfrom .attribute import new_attribute, Attribute, Where\nfrom .values import MC_TODO, MC_REQUIRED, _MC_NO_VALUE, _mc_invalid_values\nfrom .repeatable import Repeatable, UserRepeatable\nfrom .excluded import Excluded\nfrom .config_errors import ConfigBaseException, ConfigException, ConfigApiException, ConfigAttributeError\nfrom .config_errors import _api_error_msg, caller_file_line, find_user_file_line, _line_msg as line_msg\nfrom .config_errors import _error_msg, _warning_msg, _error_type_msg\nfrom .json_output import ConfigItemEncoder\n\n_debug_exc = str(os.environ.get('MULTICONF_DEBUG_EXCEPTIONS')).lower() == 'true'\n_warn_json_nesting = str(os.environ.get('MULTICONF_WARN_JSON_NESTING')).lower() == 'true'\n\n\n# pylint: disable=protected-access\n\nclass _McExcludedException(Exception):\n pass\n\n\ndef debug(*args):\n print(*args)\n\n\nclass _ConfigBase(object):\n _mc_nested = []\n\n # Decoration attributes\n _mc_deco_named_as = None\n _mc_deco_repeatable = False\n _mc_deco_nested_repeatables = []\n _mc_deco_required = []\n _mc_deco_required_if = (None, ())\n _mc_deco_unchecked = None\n\n def __init__(self, root_conf, env_factory, mc_json_filter=None, mc_json_fallback=None, **attr):\n self._mc_json_filter = mc_json_filter\n self._mc_json_fallback = mc_json_fallback\n self._mc_root_conf = root_conf\n _mc_attributes = Repeatable()\n self._mc_attributes = _mc_attributes\n self._mc_frozen = False\n self._mc_built = False\n self._mc_where = Where.IN_INIT\n self._mc_user_validated = False\n self._mc_previous_child = None\n self._mc_is_excluded = False\n self._mc_included_envs_mask = env_factory._all_envs_mask\n self._mc_json_errors = 0\n\n # Prepare attributes with default values\n file_name, line_num = find_user_file_line(up_level_start=3)\n\n __class__ = object.__getattribute__(self, '__class__')\n _mc_deco_nested_repeatables = __class__._mc_deco_nested_repeatables\n for key, value in sorted(attr.items()):\n if key in _mc_deco_nested_repeatables:\n raise ConfigException(repr(key) + ' defined as default value shadows a nested-repeatable')\n try:\n object.__getattribute__(__class__, key)\n raise ConfigException(\"The attribute \" + repr(key) + \" (not ending in '!') clashes with a property or method\")\n except AttributeError:\n pass\n attribute = Attribute(key, override_method=False)\n if value not in _mc_invalid_values:\n attribute.set_env_provided(env_factory._mc_init_group)\n attribute.set_current_env_value(value, env_factory._mc_init_group, Where.IN_INIT, file_name, line_num)\n else:\n attribute.set_invalid_value(value, env_factory._mc_init_group, Where.IN_INIT, file_name, line_num)\n _mc_attributes[key] = attribute\n\n for key in _mc_deco_nested_repeatables:\n ur = UserRepeatable()\n ur.contained_in = self\n _mc_attributes[key] = ur\n\n # If a base class is unchecked, the attribute need not be fully defined, here. The remaining envs may receive values in the base class mc_init\n _mc_deco_unchecked = object.__getattribute__(self, '_mc_deco_unchecked')\n self._mc_check = _mc_deco_unchecked != __class__ and _mc_deco_unchecked not in __class__.__bases__\n\n def named_as(self):\n \"\"\"Return the named_as property set by the @named_as decorator\"\"\"\n __class__ = object.__getattribute__(self, '__class__')\n if __class__._mc_deco_named_as:\n return __class__._mc_deco_named_as\n if __class__._mc_deco_repeatable:\n return __class__.__name__ + 's'\n return __class__.__name__\n\n def _mc_get_attributes_where(self):\n where = object.__getattribute__(self, '_mc_where')\n if where == Where.IN_BUILD:\n return object.__getattribute__(self, '_mc_build_attributes'), where\n else:\n return object.__getattribute__(self, '_mc_attributes'), where\n\n def __repr__(self):\n # Don't call property methods in repr, it is too dangerous, leading to double errors in case of incorrect user implemented property methods\n json_method = object.__getattribute__(self, 'json')\n return json_method(compact=True, property_methods=False, builders=True)\n\n def _mc_insert_item(self, child_item):\n # Freeze attributes on previously defined child\n previous_item = self._mc_previous_child\n if previous_item and not previous_item.frozen:\n try:\n previous_item._mc_freeze()\n except Exception as ex:\n print(\"Exception validating previously defined object -\", file=sys.stderr)\n print(\" type:\", type(previous_item), file=sys.stderr)\n print(\"Stack trace will be misleading!\", file=sys.stderr)\n print(\"This happens if there is an error (e.g. missing required attributes) in an object that was not\", file=sys.stderr)\n print(\"directly enclosed in a with statement. Objects that are not arguments to a with statement will\", file=sys.stderr)\n print(\"not be validated until the next ConfigItem is declared or an outer with statement is exited.\", file=sys.stderr)\n\n if hasattr(ex, '_mc_in_user_code') or _debug_exc:\n raise\n raise ex\n\n if not child_item._mc_is_excluded:\n self._mc_previous_child = child_item\n\n # Insert child_item in attributes\n child_key = child_item.named_as()\n attributes, where = self._mc_get_attributes_where()\n\n if child_item.__class__._mc_deco_repeatable:\n # Validate that this class specifies item as repeatable\n if isinstance(self, _ConfigBuilder):\n ur = UserRepeatable()\n ur.contained_in = self\n attributes.setdefault(child_key, UserRepeatable())\n elif child_key not in self.__class__._mc_deco_nested_repeatables:\n raise ConfigException(child_item._error_msg_not_repeatable_in_container(child_key, self))\n\n repeatable = attributes[child_key]\n\n # Repeatable excluded items are simply excluded, but in order to lookup excluded keys during config setup\n # we mark the repeatable as _mc_is_excluded\n if child_item._mc_is_excluded:\n repeatable._mc_is_excluded = True\n return\n\n # Calculate key to use when inserting repeatable item in Repeatable dict\n # Key is calculated as 'obj.id', 'obj.name' or id(obj) in that preferred order\n cha = child_item._mc_attributes\n specified_key = cha.get('id') or cha.get('name')\n # specified_key._value will be the __init__ value at this point if set\n obj_key = specified_key._value if specified_key is not None and specified_key._value not in _mc_invalid_values else id(child_item)\n item = repeatable.setdefault(obj_key, child_item)\n\n if item is not child_item and where != Where.IN_MC_INIT:\n # We are trying to replace an object with the same id/name\n raise ConfigException(\"Re-used id/name \" + repr(obj_key) + \" in nested objects\")\n child_item._mc_repeatable_item_key = obj_key\n return\n\n if child_key in attributes:\n if where == Where.IN_MC_INIT:\n # TODO? override value from __init__\n return\n\n if isinstance(attributes[child_key], ConfigItem):\n raise ConfigException(\"Repeated non repeatable conf item: \" + repr(child_key))\n if isinstance(attributes[child_key], Repeatable):\n msg = repr(child_key) + ': ' + repr(child_item) + \\\n ' is defined as non-repeatable, but the containing object has repeatable items with the same name: ' + repr(self)\n raise ConfigException(msg)\n raise ConfigException(repr(child_key) + ' is defined both as simple value and a contained item: ' + repr(child_item))\n\n if not child_item._mc_is_excluded:\n attributes[child_key] = child_item\n return\n\n # In case of a Non-Repeatable excluded item we insert an Excluded object which is always False\n # This makes it possible to do 'if x.item: ...' instead of hasattr(x, 'item') and allows for a nicer json dump\n attributes[child_key] = Excluded(child_item)\n\n def json(self, compact=False, property_methods=True, builders=False, skipkeys=True):\n \"\"\"See json_output.ConfigItemEncoder for parameters\"\"\"\n filter_callable = self._mc_find_json_filter_callable()\n fallback_callable = self._mc_find_json_fallback_callable()\n encoder = ConfigItemEncoder(filter_callable=filter_callable, fallback_callable=fallback_callable,\n compact=compact, property_methods=property_methods, builders=builders, warn_nesting=_warn_json_nesting,\n multiconf_base_type=_ConfigBase, multiconf_root_type=ConfigRoot, multiconf_builder_type=_ConfigBuilder)\n # python3 doesn't need separators=(',', ': ')\n json_str = json.dumps(self, skipkeys=skipkeys, default=encoder, check_circular=False, sort_keys=False, indent=4, separators=(',', ': '))\n self._mc_json_errors = encoder.num_errors\n return json_str\n\n def num_json_errors(self):\n \"\"\"\n Returns number of errors encountered when generating json\n Return None if json() has not been called\n \"\"\"\n return self._mc_json_errors\n\n def __enter__(self):\n assert not self._mc_frozen\n self._mc_where = Where.IN_WITH\n self.__class__._mc_nested.append(self)\n return self\n\n def _mc_freeze_validation(self):\n # Validate all unfrozen attributes\n _mc_attributes = object.__getattribute__(self, '_mc_attributes')\n for attr in _mc_attributes.values():\n if not attr._mc_frozen and isinstance(attr, Attribute):\n self.check_attr_fully_defined(attr, num_errors=0)\n\n # Validate @required\n missing = []\n for req in self.__class__._mc_deco_required:\n if req not in _mc_attributes:\n missing.append(req)\n if missing:\n raise ConfigException(\"No value given for required attributes: \" + repr(missing))\n\n # Validate @required_if\n required_if_key = self.__class__._mc_deco_required_if[0]\n if not required_if_key:\n return\n\n try:\n required_if_condition_attr = _mc_attributes[required_if_key]\n required_if_condition = required_if_condition_attr._mc_value()\n if not required_if_condition:\n return\n except KeyError:\n return\n\n missing = []\n for req in self.__class__._mc_deco_required_if[1]:\n if req not in _mc_attributes:\n missing.append(req)\n else:\n attr = _mc_attributes[req]\n if isinstance(attr, Attribute):\n self.check_attr_fully_defined(attr, 0)\n\n if missing:\n raise ConfigException(\"Missing required_if attributes. Condition attribute: \" + repr(required_if_key) + \" == \" + repr(required_if_condition) + \", missing attributes: \" + repr(missing))\n\n def _mc_freeze(self):\n \"\"\"\n Recursively freeze contained items bottom up.\n If self is ready to be validated (exit from with_statement or not declared in a with_statement),\n then self will be frozen and validated\n \"\"\"\n if self._mc_frozen:\n return True\n\n if self._mc_is_excluded:\n self._mc_frozen = True\n return True\n\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n\n self._mc_frozen = self._mc_deco_unchecked != self.__class__ and not root_conf._mc_under_proxy_build\n attributes = object.__getattribute__(self, '_mc_attributes')\n for _child_name, child_value in attributes.items():\n self._mc_frozen &= child_value._mc_freeze()\n\n if not self._mc_built:\n must_pop = False\n if self._mc_nested[-1] != self:\n must_pop = True\n self._mc_nested.append(self)\n try:\n was_under_proxy_build = root_conf._mc_under_proxy_build\n where = self._mc_where\n self._mc_where = Where.IN_MC_INIT\n self.mc_init()\n self._mc_where = where\n for _name, value in attributes.items():\n self._mc_frozen &= value._mc_freeze()\n\n if isinstance(self, _ConfigBuilder):\n self._mc_where = Where.IN_BUILD\n root_conf._mc_under_proxy_build = True\n try:\n self.build()\n except _McExcludedException:\n pass\n for _name, value in self._mc_build_attributes.items():\n self._mc_frozen &= value._mc_freeze()\n self._mc_post_build_update()\n self._mc_where = where\n except Exception as ex:\n ex._mc_in_user_code = True\n raise\n finally:\n root_conf._mc_under_proxy_build = was_under_proxy_build\n if must_pop:\n self._mc_nested.pop()\n self._mc_built = True\n\n if self._mc_frozen:\n self._mc_freeze_validation()\n\n return self._mc_frozen\n\n @property\n def frozen(self):\n \"\"\"Return frozen state\"\"\"\n return self._mc_frozen\n\n def __exit__(self, exc_type, exc_value, traceback):\n try:\n if exc_type is _McExcludedException:\n return True\n self._mc_freeze()\n except Exception as ex:\n ex._mc_in_exit = True\n if not exc_type:\n if hasattr(ex, '_mc_in_user_code') or _debug_exc:\n raise\n raise ex\n\n if not hasattr(exc_value, '_mc_in_exit') or hasattr(ex, '_mc_in_user_code'):\n print(\"Exception in __exit__:\", repr(ex), file=sys.stderr)\n print(\"Exception in with block will be raised\", file=sys.stderr)\n finally:\n self.__class__._mc_nested.pop()\n\n def __setattr__(self, name, value):\n if name[0] == '_':\n # Needed to set private values in __init__\n super(_ConfigBase, self).__setattr__(name, value)\n return\n mc_caller_file_name, mc_caller_line_num = caller_file_line()\n self.setattr(name, mc_caller_file_name=mc_caller_file_name, mc_caller_line_num=mc_caller_line_num, default=value)\n\n @staticmethod\n def _mc_check_reserved_name(name, method_name):\n if name[0] == '_':\n msg = \"Trying to set attribute \" + repr(name) + \" on a config item. \"\n if name.startswith('_mc'):\n raise ConfigException(msg + \"Atributes starting with '_mc' are reserved for multiconf internal usage.\")\n raise ConfigException(msg + \"Atributes starting with '_' can not be set using item.\" + method_name + \". Use assignment instead.\")\n\n def _mc_setattr_common(self, name, attribute, where, mc_caller_file_name, mc_caller_line_num, **kwargs):\n \"\"\"Set attributes with environment specific values\"\"\"\n if not isinstance(attribute, Attribute):\n raise ConfigException(repr(name) + ' ' + repr(type(attribute)) + ' is already defined and may not be replaced with an attribute.')\n\n self._mc_check_reserved_name(name, 'setattr')\n\n # For error messages\n num_errors = 0\n\n if attribute._mc_frozen and where != Where.IN_MC_INIT:\n msg = \"The attribute \" + repr(name) + \" is already fully defined\"\n num_errors = _error_msg(num_errors, msg, file_name=mc_caller_file_name, line_num=mc_caller_line_num)\n raise ConfigException(msg + \" on object \" + repr(self))\n\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n env_factory = object.__getattribute__(root_conf, '_mc_env_factory')\n selected_env = object.__getattribute__(root_conf, '_mc_selected_env')\n\n def type_error(value, other_env, other_type, num_errors):\n line_msg(file_name=mc_caller_file_name, line_num=mc_caller_line_num, msg=eg.name + ' ' + repr(type(value)))\n other_file_name, other_line_num = mc_caller_file_name, mc_caller_line_num\n if not other_env:\n other_env = other_env or env_factory.env_or_group_from_bit(attribute.value_from_eg_bit)\n other_file_name, other_line_num = attribute.file_name, attribute.line_num\n line_msg(file_name=other_file_name, line_num=other_line_num, msg=other_env.name + ' ' + repr(other_type))\n msg = \"Found different value types for property \" + repr(name) + \" for different envs\"\n return _error_type_msg(num_errors, msg)\n\n def repeated_env_error(env, conflicting_egs, num_errors):\n # TODO __file__ line of attribute set in any scope!\n # new_eg_msg = repr(selected_env) + (\"\" if isinstance(eg, EnvGroup) else \" from group \" + repr(eg))\n # new_vfl = (value, (mc_caller_file_name, mc_caller_line_num))\n # prev_eg_msg = repr(previous_eg)\n # prev_vfl = (attribute._value, (attribute.file_name, attribute.line_num))\n # msg = \"A value is already specified for: \" + new_eg_msg + '=' + repr(new_vfl) + \", previous value: \" + prev_eg_msg + '=' + repr(prev_vfl)\n msg = \"Value for env \" + repr(env.name) + \" is specified more than once, with no single most specific group or direct env:\"\n for eg in sorted(conflicting_egs):\n value = kwargs[eg.name]\n msg += \"\\nvalue: \" + repr(value) + \", from: \" + repr(eg)\n return _error_msg(num_errors, msg, file_name=mc_caller_file_name, line_num=mc_caller_line_num)\n\n if where != Where.IN_INIT and self._mc_check:\n attribute._mc_frozen = True\n\n other_env = None\n other_value = attribute._value\n other_type = type(other_value) if other_value is not None and other_value not in _mc_invalid_values else None\n\n orig_attr_where_from = attribute.where_from\n if orig_attr_where_from != Where.NOWHERE:\n orig_attr_value_from_eg_bit = attribute.value_from_eg_bit\n orig_attr_eg = env_factory.env_or_group_from_bit(orig_attr_value_from_eg_bit)\n\n current_env_from_eg = None\n all_ambiguous = {}\n seen_egs = OrderedDict()\n\n # Validate given env values, assign current env value from most specific argument\n for eg_name, value in kwargs.items():\n # debug(\"eg_name:\", eg_name)\n try:\n eg = env_factory.env_or_group_from_name(eg_name)\n if value not in _mc_invalid_values:\n attribute.set_env_provided(eg)\n\n # Validate that attribute has the same type for all envs\n if type(value) != other_type and value is not None:\n if other_type is not None:\n num_errors = type_error(value, other_env, other_type, num_errors)\n else:\n other_env = eg\n other_type = type(value)\n else:\n attribute.set_invalid_value(value, eg, where, mc_caller_file_name, mc_caller_line_num)\n\n # Check if this eg provides a more specific value for selected_env\n if selected_env in eg or selected_env == eg:\n if current_env_from_eg is not None:\n if eg in current_env_from_eg:\n current_env_from_eg = eg\n attribute.set_current_env_value(value, eg, where, mc_caller_file_name, mc_caller_line_num)\n else:\n # Check against already set value from another scope\n update_value = True\n if orig_attr_where_from != Where.NOWHERE:\n if attribute._value == MC_REQUIRED or attribute._value is None:\n # debug(\"Existing value is overridable:\", attribute._value)\n pass\n elif eg in orig_attr_eg:\n # debug(\"New eg is more specific than orig, new:\", eg, \"orig:\", orig_attr_eg)\n pass\n elif orig_attr_eg == eg:\n # debug(\"Same eg, new:\", eg.name, \"orig:\", orig_attr_eg.name)\n if orig_attr_where_from < where or orig_attr_where_from in (Where.IN_INIT, Where.IN_MC_INIT):\n # debug(\"orig where_from < where_from or orig_attr_where_from == mc_where_from_init\")\n pass\n else:\n # debug(\"orig where_from > where_from\")\n update_value = False\n elif orig_attr_eg in eg:\n # debug(\"Orig eg is the more specific, new\", eg.name, \"orig:\", orig_attr_eg.name)\n update_value = False\n\n if update_value:\n current_env_from_eg = eg\n attribute.set_current_env_value(value, eg, where, mc_caller_file_name, mc_caller_line_num)\n\n # Check if this is more specific than a previous eg or not overlapping, and collect bitmask of all seen and ambigous envs\n for other_eg in seen_egs.values():\n more_specific = eg in other_eg\n less_specific = other_eg in eg\n\n ambiguous = 0x0\n if not (less_specific or more_specific):\n ambiguous = eg.mask & other_eg.mask\n if ambiguous:\n all_ambiguous[(other_eg, eg)] = ambiguous\n\n seen_egs[eg_name] = eg\n except EnvException as ex:\n num_errors = _error_msg(num_errors, str(ex), file_name=mc_caller_file_name, line_num=mc_caller_line_num)\n\n # Clear resolved conflicts\n for _eg_name, eg in seen_egs.items():\n cleared = []\n for conflicting_egs, ambiguous in all_ambiguous.items():\n if eg.mask & ambiguous == eg.mask: # mask in or equal to ambiguous\n ambiguous ^= eg.mask & ambiguous\n if ambiguous:\n all_ambiguous[conflicting_egs] = ambiguous\n else:\n cleared.append(conflicting_egs)\n\n for conflicting_egs in cleared:\n del all_ambiguous[conflicting_egs]\n\n # If we still have unresolved conflicts, it is an error\n if all_ambiguous:\n # Reorder to generate one error per ambiguous env\n all_ambiguous_by_envs = {}\n for conflicting_egs, ambiguous in all_ambiguous.items():\n for env in env_factory.envs_from_mask(ambiguous):\n all_ambiguous_by_envs.setdefault(env, set()).update(conflicting_egs)\n\n for env, conflicting_egs in sorted(all_ambiguous_by_envs.items()):\n num_errors = repeated_env_error(env, conflicting_egs, num_errors)\n\n if where != Where.IN_INIT and self._mc_check:\n self.check_attr_fully_defined(attribute, num_errors, file_name=mc_caller_file_name, line_num=mc_caller_line_num)\n\n @staticmethod\n def _mc_check_override_common(item, attribute):\n def get_bases(cls):\n yield cls\n for cls1 in cls.__bases__:\n for cls2 in get_bases(cls1):\n yield cls2\n\n found = False\n for cls in get_bases(object.__getattribute__(item, '__class__')):\n try:\n real_attr = object.__getattribute__(cls, attribute.name)\n found = True\n break\n except AttributeError:\n pass\n\n if found:\n if not attribute.override_method:\n raise ConfigException(\"The attribute \" + repr(attribute.name) + \" (not ending in '!') clashes with a property or method\")\n elif not isinstance(real_attr, property):\n return \"%(name)s! specifies overriding a property method, but attribute '%(name)s' with value '%(value)s' is not a property.\", real_attr\n elif attribute.override_method:\n return \"%(name)s! specifies overriding a property method, but no property named '%(name)s' exists.\", None\n\n return None, None\n\n def setattr(self, name, mc_caller_file_name=None, mc_caller_line_num=None, **kwargs):\n if not mc_caller_file_name:\n mc_caller_file_name, mc_caller_line_num = caller_file_line()\n\n try:\n attribute, name = new_attribute(name)\n err_msg, value = self._mc_check_override_common(self, attribute)\n if err_msg:\n raise ConfigException(err_msg % dict(name=name, value=value))\n attributes = object.__getattribute__(self, '_mc_attributes')\n where = object.__getattribute__(self, '_mc_where')\n attribute = attributes.setdefault(name, attribute)\n self._mc_setattr_common(name, attribute, where, mc_caller_file_name, mc_caller_line_num, **kwargs)\n except ConfigBaseException as ex:\n if _debug_exc:\n raise\n raise ex\n\n def _mc_override_common(self, name, attributes, where, mc_caller_file_name, mc_caller_line_num, value):\n \"\"\"Set attributes with environment specific values\"\"\"\n self._mc_check_reserved_name(name, 'override')\n\n attribute, name = new_attribute(name)\n attributes[name] = attribute\n\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n env_factory = object.__getattribute__(root_conf, '_mc_env_factory')\n\n if where != Where.IN_INIT and self._mc_check:\n attribute._mc_frozen = True\n\n default_group = env_factory._mc_default_group\n if value in _mc_invalid_values:\n attribute.set_invalid_value(value, default_group, where, mc_caller_file_name, mc_caller_line_num)\n if self._mc_check:\n self.check_attr_fully_defined(attribute, 0)\n return\n\n attribute.set_env_provided(default_group)\n attribute.set_current_env_value(value, default_group, where, mc_caller_file_name, mc_caller_line_num)\n\n def override(self, name, value):\n \"\"\"Set attributes with environment specific values\"\"\"\n mc_caller_file_name, mc_caller_line_num = caller_file_line()\n\n where = object.__getattribute__(self, '_mc_where')\n attributes = object.__getattribute__(self, '_mc_attributes')\n try:\n self._mc_override_common(name, attributes, where, mc_caller_file_name, mc_caller_line_num, value)\n except ConfigBaseException as ex:\n if _debug_exc:\n raise\n raise ex\n\n def check_attr_fully_defined(self, attribute, num_errors, file_name=None, line_num=None):\n # In case of override_method, the attribute need not be fully defined, the property method will handle remaining values\n if not attribute.all_set(self._mc_included_envs_mask) and not hasattr(attribute, 'already_checked') and not attribute.override_method:\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n env_factory = object.__getattribute__(root_conf, '_mc_env_factory')\n selected_env = object.__getattribute__(root_conf, '_mc_selected_env')\n\n # Check whether we need to check for conditionally required attributes\n required_if_key = self.__class__._mc_deco_required_if[0]\n if required_if_key:\n # A required_if CONDITION attribute is optional, so it is ok if it is not set or not set for all environments\n if attribute.name == required_if_key:\n return\n\n required_if_attribute_names = self.__class__._mc_deco_required_if[1]\n try:\n attributes = object.__getattribute__(self, '_mc_attributes')\n required_if_condition_attr = attributes[required_if_key]\n except KeyError:\n # The condition property was not specified, so the conditional attributes are not required\n if attribute.name in required_if_attribute_names:\n return\n\n # Check for which envs the attribute is not defined\n missing_envs_mask = self._mc_included_envs_mask & ~attribute.envs_set_mask\n for env in env_factory.envs_from_mask(missing_envs_mask):\n # Check for required_if, the required_if atributes are optional if required_if_condition value is false or not specified for the env\n # Required if condition value is only checked for current env\n # TODO MC_TODO with required_if tests\n if required_if_key and attribute.name in required_if_attribute_names:\n if selected_env != env or not required_if_condition_attr._value or not required_if_condition_attr.envs_set_mask & env.bit:\n continue # pragma: no cover\n\n # Check for which envs the attribute is MC_TODO\n value = _MC_NO_VALUE\n for inv_value, inv_eg, inv_where_from, inv_file_name, inv_line_num in attribute.invalid_values if hasattr(attribute, 'invalid_values') else ():\n # debug(\"Checking MC_TODO, env, inv_value, inv_eg:\", env, inv_value, inv_eg)\n if env.bit & inv_eg.mask:\n if selected_env == env:\n attribute._value = inv_value\n value = inv_value\n break\n\n # debug(\"attribute._value, value:\", attribute._value, value)\n value_msg = (' ' + repr(value)) if value in _mc_invalid_values and value != _MC_NO_VALUE else ''\n current_env_msg = \" current\" if env == self.env else ''\n msg = \"Attribute: \" + repr(attribute.name) + value_msg + \" did not receive a value for\" + current_env_msg + \" env \" + repr(env)\n\n if value == MC_TODO:\n if env != self.env and root_conf._mc_allow_todo:\n self._warning_msg(msg, file_name=file_name, line_num=line_num)\n continue\n if root_conf._mc_allow_current_env_todo:\n self._warning_msg(msg + \". Continuing with invalid configuration!\", file_name=file_name, line_num=line_num)\n continue\n\n num_errors = _error_msg(num_errors, msg, file_name=file_name, line_num=line_num)\n\n if num_errors:\n attribute.already_checked = True\n raise ConfigException(\"There were \" + repr(num_errors) + \" errors when defining attribute \" + repr(attribute.name) + \" on object: \" + repr(self))\n\n def __getattribute__(self, name):\n if name[0] == '_':\n return object.__getattribute__(self, name)\n\n try:\n attributes = object.__getattribute__(self, '_mc_attributes')\n attr = attributes[name]\n except KeyError:\n try:\n return object.__getattribute__(self, name)\n except AttributeError:\n raise ConfigAttributeError(mc_object=self, attr_name=name)\n except AttributeError:\n __class__ = object.__getattribute__(self, '__class__')\n ex_msg = \"An error was detected trying to get attribute \" + repr(name) + \" on class \" + repr(__class__.__name__)\n msg = \"\\n - You did not initailize the parent class (parent __init__ method has not been called).\"\n _api_error_msg(1, ex_msg + msg)\n raise ConfigApiException(ex_msg)\n\n mc_value = attr._mc_value()\n if mc_value != _MC_NO_VALUE:\n return mc_value\n\n if self._mc_is_excluded:\n return Excluded(self)\n\n if attr.override_method:\n try:\n return object.__getattribute__(self, name)\n except Exception:\n # We have both an mc_attribute and a property method on the object\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n selected_env = object.__getattribute__(root_conf, '_mc_selected_env')\n raise AttributeError(\"Attribute \" + repr(name) +\n \" is defined as muticonf attribute and as property method, but value is undefined for env \" +\n repr(selected_env) + \" and method call failed\")\n\n # This can only happen for conditional properties\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n selected_env = object.__getattribute__(root_conf, '_mc_selected_env')\n raise AttributeError(\"Attribute \" + repr(name) + \" undefined for env \" + repr(selected_env))\n\n def items(self):\n attributes = object.__getattribute__(self, '_mc_attributes')\n for key, item in attributes.items():\n value = item._mc_value()\n if value != _MC_NO_VALUE: # _MC_NO_VALUE should only happen in case of a conditional attribute\n yield key, value\n\n # For backwards compatibility\n iteritems = items\n\n def _iterattributes(self):\n attributes = object.__getattribute__(self, '_mc_attributes')\n for key, item in attributes.items():\n yield key, item\n\n @property\n def contained_in(self):\n contained_in = object.__getattribute__(self, '_mc_contained_in')\n if not isinstance(contained_in, _ConfigBuilder):\n return contained_in\n\n root_conf = object.__getattribute__(contained_in, '_mc_root_conf')\n if root_conf._mc_under_proxy_build:\n return contained_in.contained_in\n\n raise ConfigApiException(\"Use of 'contained_in' in not allowed in object while under a ConfigBuilder\")\n\n @property\n def root_conf(self):\n return object.__getattribute__(self, '_mc_root_conf')\n\n @property\n def env(self):\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n return object.__getattribute__(root_conf, '_mc_selected_env')\n\n @property\n def env_factory(self):\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n return object.__getattribute__(root_conf, 'env_factory')\n\n def _mc_find_json_filter_callable(self):\n contained_in = self\n while contained_in:\n if contained_in._mc_json_filter:\n return contained_in._mc_json_filter\n contained_in = contained_in._mc_contained_in\n return None\n\n def _mc_find_json_fallback_callable(self):\n contained_in = self\n while contained_in:\n if contained_in._mc_json_fallback:\n return contained_in._mc_json_fallback\n contained_in = contained_in._mc_contained_in\n return None\n\n def find_contained_in_or_none(self, named_as):\n \"\"\"Find first parent container named as 'named_as', by searching backwards towards root_conf, starting with parent container\"\"\"\n contained_in = self.contained_in\n while contained_in:\n if contained_in.named_as() == named_as:\n return contained_in\n contained_in = contained_in.contained_in\n return None\n\n def find_contained_in(self, named_as):\n \"\"\"Find first parent container named as 'named_as', by searching backwards towards root_conf, starting with parent container\"\"\"\n contained_in = self.contained_in\n while contained_in:\n if contained_in.named_as() == named_as:\n return contained_in\n contained_in = contained_in.contained_in\n\n # Error, create error message\n contained_in = self.contained_in\n contained_in_names = []\n while contained_in:\n contained_in_names.append(contained_in.named_as())\n contained_in = contained_in.contained_in\n\n msg = ': Could not find a parent container named as: ' + repr(named_as) + ' in hieracy with names: ' + repr(contained_in_names)\n raise ConfigException(\"Searching from: \" + repr(type(self)) + msg)\n\n def find_attribute_or_none(self, attribute_name):\n \"\"\"Find first occurence of attribute 'attribute_name', by searching backwards towards root_conf, starting with self.\"\"\"\n contained_in = self\n while contained_in:\n attributes = object.__getattribute__(contained_in, '_mc_attributes')\n attr = attributes.get(attribute_name)\n if attr:\n return getattr(contained_in, attribute_name)\n contained_in = contained_in.contained_in\n return None\n\n def find_attribute(self, attribute_name):\n \"\"\"Find first occurence of attribute 'attribute_name', by searching backwards towards root_conf, starting with self.\"\"\"\n contained_in = self\n while contained_in:\n attributes = object.__getattribute__(contained_in, '_mc_attributes')\n attr = attributes.get(attribute_name)\n if attr:\n return getattr(contained_in, attribute_name)\n contained_in = contained_in.contained_in\n\n # Error, create error message\n contained_in = self\n contained_in_names = []\n while contained_in:\n contained_in_names.append(contained_in.named_as())\n contained_in = contained_in.contained_in\n\n msg = ': Could not find an attribute named: ' + repr(attribute_name) + ' in hieracy with names: ' + repr(contained_in_names)\n raise ConfigException(\"Searching from: \" + repr(type(self)) + msg)\n\n def _user_validate_recursively(self):\n \"\"\"Call the user defined 'validate' methods on all items\"\"\"\n if self._mc_user_validated:\n return\n\n try:\n self.validate()\n except Exception as ex:\n ex._mc_in_user_code = True\n raise\n finally:\n self._mc_user_validated = True\n\n attributes = object.__getattribute__(self, '_mc_attributes')\n for child_value in attributes.values():\n child_value._user_validate_recursively()\n\n def validate(self):\n \"\"\"Can be overridden to provide post-frozen validation\"\"\"\n pass\n\n def mc_init(self):\n \"\"\"Can be overridden in derived classes to instantiate default child objects\"\"\"\n pass\n\n def _mc_value(self):\n return self\n\n def _warning_msg(self, msg, file_name, line_num):\n self._mc_root_conf._mc_num_warnings = _warning_msg(self._mc_root_conf._mc_num_warnings, msg, file_name=file_name, line_num=line_num)\n\n\nclass ConfigRoot(_ConfigBase):\n def __init__(self, selected_env, env_factory, mc_json_filter=None, mc_json_fallback=None, mc_allow_todo=False, mc_allow_current_env_todo=False, **attr):\n __class__ = object.__getattribute__(self, '__class__')\n if not isinstance(env_factory, EnvFactory):\n raise ConfigException(__class__.__name__ + ': env_factory arg must be instance of ' + repr(EnvFactory.__name__) + '; found type '\n + repr(env_factory.__class__.__name__) + ': ' + repr(env_factory))\n\n if not isinstance(selected_env, Env):\n raise ConfigException(__class__.__name__ + ': env must be instance of ' + repr(Env.__name__) + '; found type '\n + repr(selected_env.__class__.__name__) + ': ' + repr(selected_env))\n\n if selected_env.factory != env_factory:\n raise ConfigException(\"The selected env \" + repr(selected_env) + \" must be from the specified 'env_factory'\")\n\n del __class__._mc_nested[:]\n\n self._mc_selected_env = selected_env\n self._mc_env_factory = env_factory\n self._mc_allow_todo = mc_allow_todo or mc_allow_current_env_todo\n self._mc_allow_current_env_todo = mc_allow_current_env_todo\n env_factory = object.__getattribute__(self, '_mc_env_factory')\n env_factory._mc_init_and_default_groups()\n super(ConfigRoot, self).__init__(root_conf=self, env_factory=env_factory, mc_json_filter=mc_json_filter, mc_json_fallback=mc_json_fallback, **attr)\n self._mc_contained_in = None\n self._mc_under_proxy_build = False\n self._mc_num_warnings = 0\n self._mc_config_loaded = False\n\n def __exit__(self, exc_type, exc_value, traceback):\n try:\n super(ConfigRoot, self).__exit__(exc_type, exc_value, traceback)\n if not self._mc_is_excluded:\n self._user_validate_recursively()\n self._mc_config_loaded = True\n except Exception as ex:\n if not exc_type:\n if hasattr(ex, '_mc_in_user_code') or _debug_exc:\n raise\n raise ex\n\n @property\n def env_factory(self):\n return self._mc_env_factory\n\n\nclass ConfigItem(_ConfigBase):\n def __init__(self, mc_json_filter=None, mc_json_fallback=None, mc_include=None, mc_exclude=None, **attr):\n # Set back reference to containing Item and root item\n __class__ = object.__getattribute__(self, '__class__')\n if not __class__._mc_nested:\n raise ConfigException(__class__.__name__ + \" object must be nested (indirectly) in a \" + repr(ConfigRoot.__name__))\n\n contained_in = __class__._mc_nested[-1]\n self._mc_contained_in = contained_in\n root_conf = object.__getattribute__(contained_in, '_mc_root_conf')\n env_factory = object.__getattribute__(root_conf, '_mc_env_factory')\n super(ConfigItem, self).__init__(root_conf=root_conf, env_factory=env_factory,\n mc_json_filter=mc_json_filter, mc_json_fallback=mc_json_fallback, **attr)\n self._mc_select_envs(mc_include, mc_exclude)\n contained_in._mc_insert_item(self)\n\n def _mc_select_envs(self, include, exclude, file_name=None, line_num=None):\n \"\"\"Determine if item (and children) is included in specified env\"\"\"\n # Resolve most specif include/exclude eg\n contained_in = object.__getattribute__(self, '_mc_contained_in')\n contained_in_included_envs_mask = object.__getattribute__(contained_in, '_mc_included_envs_mask')\n _mc_included_envs_mask = object.__getattribute__(self, '_mc_included_envs_mask')\n\n all_ambiguous = {}\n if exclude:\n for eg_excl in exclude:\n if include is None:\n _mc_included_envs_mask &= ~eg_excl.mask\n continue\n\n include_masks = 0b0\n for eg_incl in include:\n # Check if this is more specific than a previous eg or not overlapping, and collect bitmask of all seen and ambiguous envs\n must_excl = eg_excl in eg_incl\n must_incl = eg_incl in eg_excl\n\n ambiguous = 0x0\n if not (must_incl or must_excl):\n ambiguous = eg_excl.mask & eg_incl.mask\n if ambiguous:\n all_ambiguous[(eg_incl, eg_excl)] = ambiguous\n\n if not ambiguous:\n include_masks |= eg_incl.mask\n include_masks &= ~eg_excl.mask\n\n _mc_included_envs_mask &= include_masks\n else:\n if include is not None:\n include_masks = 0b0\n for eg in include:\n include_masks |= eg.mask\n _mc_included_envs_mask &= include_masks\n\n # Clear resolved conflicts\n cleared = []\n\n for conflicting_egs, ambiguous in all_ambiguous.items():\n for eg in exclude or ():\n if eg.mask & ambiguous == eg.mask: # mask in or equal to ambiguous\n ambiguous ^= eg.mask & ambiguous\n if ambiguous:\n all_ambiguous[conflicting_egs] = ambiguous\n elif eg in conflicting_egs[0]:\n cleared.append(conflicting_egs)\n _mc_included_envs_mask &= ~eg.mask\n\n for eg in include or ():\n if eg.mask & ambiguous == eg.mask: # mask in or equal to ambiguous\n ambiguous ^= eg.mask & ambiguous\n if ambiguous:\n all_ambiguous[conflicting_egs] = ambiguous\n elif eg in conflicting_egs[1]:\n cleared.append(conflicting_egs)\n _mc_included_envs_mask |= eg.mask\n\n for conflicting_egs in cleared:\n del all_ambiguous[conflicting_egs]\n\n num_errors = 0\n\n # If we still have unresolved conflicts, it is an error\n if all_ambiguous:\n if not file_name:\n file_name, line_num = caller_file_line(3)\n # Reorder to generate one error per ambiguous env\n all_ambiguous_by_envs = {}\n root_conf = object.__getattribute__(contained_in, '_mc_root_conf')\n env_factory = object.__getattribute__(root_conf, '_mc_env_factory')\n for conflicting_egs, ambiguous in all_ambiguous.items():\n for env in env_factory.envs_from_mask(ambiguous):\n all_ambiguous_by_envs.setdefault(env, set()).update(conflicting_egs)\n\n for env, conflicting_egs in sorted(all_ambiguous_by_envs.items()):\n msg = \"Env \" + repr(env.name) + \" is specified in both include and exclude, with no single most specific group or direct env:\"\n for eg in sorted(conflicting_egs):\n msg += \"\\n from: \" + repr(eg)\n num_errors = _error_msg(num_errors, msg, file_name=file_name, line_num=line_num)\n\n if include is not None and _mc_included_envs_mask & contained_in_included_envs_mask != _mc_included_envs_mask:\n re_included = _mc_included_envs_mask & contained_in_included_envs_mask ^ _mc_included_envs_mask\n if not file_name:\n file_name, line_num = caller_file_line(3)\n root_conf = object.__getattribute__(contained_in, '_mc_root_conf')\n env_factory = object.__getattribute__(root_conf, '_mc_env_factory')\n for env in env_factory.envs_from_mask(re_included):\n msg = \"Env \" + repr(env.name) + \" is excluded at an outer level\"\n num_errors = _error_msg(num_errors, msg, file_name=file_name, line_num=line_num)\n\n if num_errors:\n raise ConfigException(\"There were \" + repr(num_errors) + \" errors when defining item: \" + repr(self))\n\n if not (self.env.mask & _mc_included_envs_mask) or contained_in._mc_is_excluded:\n self._mc_is_excluded = True\n attributes = object.__getattribute__(self, '_mc_attributes')\n for _key, item in attributes.items():\n item._mc_is_excluded = True\n self._mc_included_envs_mask = _mc_included_envs_mask & contained_in_included_envs_mask\n\n def mc_select_envs(self, include=None, exclude=None, mc_caller_file_name=None, mc_caller_line_num=None):\n \"\"\"Skip with block if item is excluded\"\"\"\n if not self._mc_is_excluded:\n self._mc_select_envs(include=include, exclude=exclude, file_name=mc_caller_file_name, line_num=mc_caller_line_num)\n if self._mc_is_excluded:\n contained_in = object.__getattribute__(self, '_mc_contained_in')\n contained_in_attributes, _ = contained_in._mc_get_attributes_where()\n if self.__class__._mc_deco_repeatable:\n # Remove repeatable item\n del contained_in_attributes[self.named_as()][self._mc_repeatable_item_key]\n else:\n contained_in_attributes[self.named_as()] = Excluded(self)\n\n if self._mc_is_excluded:\n raise _McExcludedException()\n\n def _error_msg_not_repeatable_in_container(self, key, containing_class):\n return repr(key) + ': ' + repr(self) + ' is defined as repeatable, but this is not defined as a repeatable item in the containing class: ' + \\\n repr(containing_class.named_as())\n\n def __bool__(self):\n return not object.__getattribute__(self, '_mc_is_excluded')\n\n # Python2 compatibility\n __nonzero__ = __bool__\n\n\nclass _ConfigBuilder(ConfigItem):\n _num = 0\n\n def __init__(self, mc_json_filter=None, mc_json_fallback=None, mc_include=None, mc_exclude=None, **attr):\n super(_ConfigBuilder, self).__init__(mc_json_filter=mc_json_filter, mc_json_fallback=mc_json_fallback,\n mc_include=mc_include, mc_exclude=mc_exclude, **attr)\n self._mc_build_attributes = Repeatable()\n _ConfigBuilder._num += 1\n\n def setattr(self, name, mc_caller_file_name=None, mc_caller_line_num=None, **kwargs):\n if not mc_caller_file_name:\n mc_caller_file_name, mc_caller_line_num = caller_file_line()\n\n try:\n attribute, name = new_attribute(name)\n attributes, where = self._mc_get_attributes_where()\n attribute = attributes.setdefault(name, attribute)\n self._mc_setattr_common(name, attribute, where, mc_caller_file_name, mc_caller_line_num, **kwargs)\n except ConfigBaseException as ex:\n if _debug_exc:\n raise\n raise ex\n\n def override(self, name, value):\n \"\"\"Set attributes with environment specific values\"\"\"\n mc_caller_file_name, mc_caller_line_num = caller_file_line()\n\n attributes, where = self._mc_get_attributes_where()\n try:\n self._mc_override_common(name, attributes, where, mc_caller_file_name, mc_caller_line_num, value)\n except ConfigBaseException as ex:\n if _debug_exc:\n raise\n raise ex\n\n def _mc_post_build_update(self):\n root_conf = object.__getattribute__(self, '_mc_root_conf')\n selected_env = object.__getattribute__(root_conf, '_mc_selected_env')\n attributes = object.__getattribute__(self, '_mc_attributes')\n\n override_attribute_errors = OrderedDict()\n\n def set_my_attributes_on_item_from_build(item_from_build, clone):\n for override_key, override_value in attributes.items():\n if override_value._mc_value() == None:\n continue\n\n if isinstance(override_value, Repeatable):\n for rep_override_key, rep_override_value in override_value.items():\n if override_key not in item_from_build.__class__._mc_deco_nested_repeatables:\n raise ConfigException(rep_override_value._error_msg_not_repeatable_in_container(override_key, item_from_build))\n ov = copy.copy(rep_override_value) if clone else rep_override_value\n ov._mc_contained_in = item_from_build\n\n item_from_build._mc_attributes[override_key][rep_override_key] = ov\n continue\n\n if isinstance(override_value, ConfigItem):\n ov = copy.copy(override_value) if clone else override_value\n ov._mc_contained_in = item_from_build\n item_from_build._mc_attributes[override_key] = ov\n continue\n\n # override_value is an Attribute\n name = override_value.name\n err_msg, value = self._mc_check_override_common(item_from_build, override_value)\n if err_msg:\n if name not in override_attribute_errors:\n override_attribute_errors[name] = (err_msg, value)\n else:\n override_attribute_errors[name] = False\n\n existing_attr = item_from_build._mc_attributes.get(override_key)\n if existing_attr:\n item_from_build._mc_attributes[override_key] = existing_attr.override(override_value, selected_env)\n continue\n\n item_from_build._mc_attributes[override_key] = override_value\n\n def from_build_to_parent(build_key, build_value, clone):\n \"\"\"Copy/Merge all items/attributes defined in 'build' into parent object\"\"\"\n parent = self._mc_contained_in\n parent_attributes, _ = parent._mc_get_attributes_where()\n\n # Merge repeatable items into parent\n if isinstance(build_value, Repeatable):\n for rep_key, rep_value in build_value.items():\n rep_value._mc_contained_in = parent\n set_my_attributes_on_item_from_build(rep_value, clone=clone)\n\n if isinstance(parent, _ConfigBuilder):\n ur = UserRepeatable()\n ur.contained_in = self\n parent_attributes.setdefault(build_key, ur)\n elif build_key not in parent.__class__._mc_deco_nested_repeatables:\n raise ConfigException(rep_value._error_msg_not_repeatable_in_container(build_key, parent))\n\n if rep_key in parent_attributes[build_key]:\n # TODO: Silently skip insert instead (optional warning)?\n raise ConfigException(\"Nested repeatable from 'build', key: \" + repr(rep_key) + \", value: \" + repr(rep_value) +\n \" overwrites existing entry in parent: \" + repr(parent))\n\n parent_attributes[build_key][rep_key] = rep_value\n\n parent_attributes[build_key]._mc_is_excluded |= self._mc_is_excluded\n return\n\n if isinstance(build_value, ConfigItem):\n build_value._mc_contained_in = parent\n set_my_attributes_on_item_from_build(build_value, clone=clone)\n\n # Set non-repeatable items on parent\n # TODO validation\n parent_attributes[build_key] = build_value if not self._mc_is_excluded else Excluded(build_value)\n\n def move_items_around():\n # Loop over attributes created in build\n # Items and attributes created in 'build' goes into parent\n # Attributes/Items on builder are copied to items created in build\n clone = False\n for build_key, build_value in self._mc_build_attributes.items():\n from_build_to_parent(build_key, build_value, clone)\n clone = True\n\n move_items_around()\n\n errors = [(name, err_value) for name, err_value in override_attribute_errors.items() if err_value]\n errors = [err % dict(name=name, value=value) for name, (err, value) in errors]\n if errors:\n raise ConfigException('The following errors were found when setting values on items from build()\\n ' + '\\n '.join(errors))\n\n def what_built(self):\n return OrderedDict([(key, attr._mc_value()) for key, attr in self._mc_build_attributes.items()])\n\n def named_as(self):\n return super(_ConfigBuilder, self).named_as() + '.builder.' + repr(_ConfigBuilder._num)\n","sub_path":"multiconf.py","file_name":"multiconf.py","file_ext":"py","file_size_in_byte":56119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"343798485","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport datetime\nimport pandas as pd\nfrom scipy import stats\nimport numpy as np\nimport pickle\n\n\n# In[2]:\n\n\n# Function to compute the frequency of the dpd for a customer\ndef frequencyOfDPD(arr):\n value = []\n count=0\n for index, x in np.ndenumerate(arr):\n dpdlist=[]\n x = x.strip('\"\"\"')\n f = [x[i:i+3] for i in range(0,len(x),3)]\n for each in f:\n try:\n dpdlist.append(int(each))\n continue\n except(ValueError, Exception) as e:\n continue\n if dpdlist:\n value.append(len(dpdlist))\n else:\n value.append(0)\n return value\n\n\n# In[3]:\n\n\n# Return n recent dpd from payment history. If none then return the sum of all dpd for one history.\ndef latestNdpd(arr,freq=None):\n value = []\n for index, x in np.ndenumerate(arr):\n dpdlist=[]\n count=0\n x = x.strip('\"\"\"')\n f = [x[i:i+3] for i in range(0,len(x),3)]\n for each in f:\n try:\n dpdlist.append(int(each))\n continue\n except(ValueError, Exception) as e:\n dpdlist.append(0)\n continue\n if dpdlist:\n if freq==None:\n for dpd in dpdlist:\n count+=dpd\n value.append(count)\n else:\n try:\n if dpdlist[freq-1]!=0:\n value.append(1)\n continue\n else:\n value.append(0)\n except(IndexError) as e:\n value.append(0)\n continue\n else:\n value.append(0)\n return value\n\n\n# In[4]:\n\n\ndef countCredit(x):\n count=0\n for index, item in np.ndenumerate(x.values):\n if item in [10,35,14,31]:\n count+=1\n return count/len(x)\n\n\n# In[5]:\n\n\ndef countAccount(x):\n count=0\n for index, item in np.ndenumerate(x.values):\n if item in [1,2,3,4,5,6,7,8,9,13,15,17,32,33,34,41,41,42,51,54,59,60]:\n count+=1\n return count/len(x)\n\n\n# In[6]:\n\n\ndef paymthistorylength(x):\n count=0\n for index, str in np.ndenumerate(x):\n str = str.strip('\"\"\"')\n count+=len(str)\n return count/len(x)\n\n\n# In[7]:\n\n\ndef findMode(arr):\n return (stats.mode(arr)).mode\n\n\n# In[8]:\n\n\ndf_data = pd.read_csv(r'C:\\Users\\Dell\\Desktop\\raw_data_70_new.csv',engine='python')\ndf_account = pd.read_csv(r'C:\\Users\\Dell\\Desktop\\raw_account_70_new.csv',engine='python', parse_dates = ['dt_opened','upload_dt', 'opened_dt', 'paymt_str_dt', 'paymt_end_dt','last_paymt_dt','closed_dt','reporting_dt'])\ndf_enquiry = pd.read_csv(r'C:\\Users\\Dell\\Desktop\\raw_enquiry_70_new.csv',engine='python', parse_dates = ['dt_opened','upload_dt', 'enquiry_dt'])\n\n\n# In[9]:\n\n\n# df_data.isnull().sum(axis=0)\n\n\n# In[10]:\n\n\n# df_enquiry.isnull().sum(axis=0)\n\n\n# In[11]:\n\n\nnewdf = df_account\nnewdf1 = df_enquiry\n\n\n# In[12]:\n\n\n# Assuming current date for null last_paymt_dt.\nnewdf.last_paymt_dt.fillna(datetime.datetime.now(),inplace=True)\n\n\n# In[13]:\n\n\n# Assuming value of 0.0001 for null high_credit_amt and then high_credit_amt is assumed for null creditlimit.\n# newdf.high_credit_amt.fillna(0.0001, inplace=True)\n# newdf.creditlimit.fillna(newdf.high_credit_amt, inplace=True)\n\n\n# In[14]:\n\n\nnewdf['diff_opened_lastPaymt_dt'] = newdf['opened_dt'].sub(newdf['last_paymt_dt'], axis=0)\nnewdf['diff_opened_lastPaymt_dt'] = newdf['diff_opened_lastPaymt_dt'] / np.timedelta64(1, 'D')\n# newdf.isnull().sum(axis=0)\n\n\n# In[15]:\n\n\n# ----------------------------------------------------Deriving Account Features--------------------------------------------------------\nnewdf['highcr-creditlimt'] = newdf['high_credit_amt'] - newdf['creditlimit']\nnewdf['currBal-highcr'] = newdf['cur_balance_amt'] - newdf['high_credit_amt']\nnewdf['currbal-creditlimit'] = newdf['cur_balance_amt'] - newdf['creditlimit']\n# newdf.isnull().sum(axis=0)\n\n\n# In[16]:\n\n\nnewdf['1DPDReported'] = latestNdpd(newdf['paymenthistory1'].values, freq=1)\nnewdf['2DPDReported'] = newdf['1DPDReported'] | latestNdpd(newdf['paymenthistory1'].values, freq=2)\nnewdf['3DPDReported'] = newdf['2DPDReported'] | latestNdpd(newdf['paymenthistory1'].values, freq=3)\nnewdf['totalDPD'] = latestNdpd(newdf['paymenthistory1'].values)\nnewdf['frequencyofDPDreported'] = frequencyOfDPD(newdf['paymenthistory1'].values)\n# newdf.isnull().sum(axis=0)\n\n\n# In[17]:\n\n\ngroup1 = newdf.groupby('customer_no', as_index=False).agg({'acct_type': ['count'],'diff_opened_lastPaymt_dt': ['mean','sum'],'highcr-creditlimt': ['mean','sum'],'currBal-highcr': ['mean','sum'], 'currbal-creditlimit': ['mean','sum'], '1DPDReported': ['mean','sum'], '2DPDReported': ['mean','sum'], '3DPDReported': ['mean','sum'], 'totalDPD': ['mean','sum'], 'frequencyofDPDreported': ['mean','sum'], 'cur_balance_amt': ['mean','sum','std','count'], 'creditlimit': ['mean','sum','std'], 'high_credit_amt': ['mean','sum','std']})\n# group1.columns.values\n\n\n# In[18]:\n\n\ndf_derived = pd.DataFrame()\ndf_derived['customer_no'] = group1['customer_no']\n\n\n# In[19]:\n\n\ndf_derived['diff_opened_lastPaymt_dt_sum'] = group1[('diff_opened_lastPaymt_dt','sum')]\n# df_derived['diff_highcr_creditlim_sum'] = d1[('highcr-creditlimt','sum')]\ndf_derived['diff_highcr_creditlim_mean'] = group1[('highcr-creditlimt','mean')]\n# df_derived['diff_highcr_currbal_sum'] = d3[('highcr-currBal','sum')]\ndf_derived['1DPDReported_mean'] = group1[('1DPDReported','mean')]\ndf_derived['2DPDReported_mean'] = group1[('2DPDReported','mean')]\ndf_derived['3DPDReported_mean'] = group1[('3DPDReported','mean')]\ndf_derived['totalDPD_sum'] = group1[('3DPDReported','sum')]\ndf_derived['frequencyofDPDreported_mean'] = group1[('frequencyofDPDreported','mean')]\n\ndf_derived['ratio_totalCurrbal_totalcrlim'] = group1[('cur_balance_amt','sum')]/group1[('creditlimit','sum')]\ndf_derived['ratio_totalCurrbal_totalhighCr'] = group1[('cur_balance_amt','sum')]/group1[('high_credit_amt','sum')]\ndf_derived['ratio_totalhighcr_totalcrlim'] = group1[('high_credit_amt','sum')]/group1[('creditlimit','sum')]\n# df_derived.isnull().sum(axis=0)\n\n\n# In[20]:\n\n\nd1 = newdf.groupby('customer_no',as_index=False)['acct_type'].apply(countCredit).reset_index(name='creditcount')\ndf_derived['avg_creditcount'] = d1.creditcount\n\n\n# In[21]:\n\n\nd1 = newdf.groupby('customer_no',as_index=False)['acct_type'].apply(countAccount).reset_index(name='loancount')\ndf_derived['avg_loancount'] = d1.loancount/group1[('acct_type','count')]\n\n\n# In[22]:\n\n\nd1 = newdf.groupby('customer_no',as_index=False)['paymenthistory1'].apply(paymthistorylength).reset_index(name='historylength')\ndf_derived['avg_payhistlength'] = d1.historylength\n\n\n# In[23]:\n\n\nd_1 = newdf[newdf['high_credit_amt'] > newdf['creditlimit']]\ng_1 = d_1.groupby('customer_no').size().reset_index(name='count')\ng_2 = newdf.groupby('customer_no').size().reset_index(name='count')\nl = (g_2[~g_2['customer_no'].isin(g_1['customer_no'])==True].customer_no).tolist()\nd = pd.DataFrame()\nd['customer_no'] = l\nd['count'] = [0 for i in range(len(d))]\nd1 = pd.concat([g_1, d], ignore_index=True)\nd1.sort_values('customer_no',inplace=True)\nd1.reset_index(drop=True,inplace=True)\nd1['meancount'] = d1['count']/group1[('acct_type','count')]\ndf_derived['meanAcctWithHighCrGreaterThanCreditLim'] = d1['meancount']\n\n\n# In[24]:\n\n\nd_1 = newdf[newdf['cur_balance_amt'] == 0]\ng_1 = d_1.groupby('customer_no').size().reset_index(name='count')\ng_2 = newdf.groupby('customer_no').size().reset_index(name='count')\nl = (g_2[~g_2['customer_no'].isin(g_1['customer_no'])==True].customer_no).tolist()\nd = pd.DataFrame()\nd['customer_no'] = l\nd['count'] = [0 for i in range(len(d))]\nd1 = pd.concat([g_1, d], ignore_index=True)\nd1.sort_values('customer_no',inplace=True)\nd1.reset_index(drop=True,inplace=True)\nd1['meancount'] = d1['count']/group1[('acct_type','count')]\n# df_derived['meanAcctWithCurrBalEqualsZero'] = d1['meancount']\ndf_derived['meanAcctWithCurrBalEqualsZero'] = d1['count']\n\n\n# In[25]:\n\n\n#--------------------------------------------Deriving Enquiry Features-----------------------------------------------------------\nd1 = newdf1.enquiry_dt.values\nd2 = d1[1:]\nd2 = np.append(d2,d1[-1])\nd = (d2-d1)/np.timedelta64(1, 'D')\nnewdf1['GapEnquiryDates'] = abs(d)\n\n\n# In[26]:\n\n\ngroup2 = newdf1.groupby('customer_no', as_index=False).agg({'dt_opened': ['count'],'upload_dt': ['count'],'enquiry_dt': ['count'],'enq_purpose': ['count'], 'enq_amt': ['count'],'enq_purpose': findMode,'GapEnquiryDates': ['mean','sum']})\n\n\n# In[27]:\n\n\ndf_derived['meanGapEnquiryDates'] = group2[('GapEnquiryDates','mean')]\n\n\n# In[28]:\n\n\ndf_derived['mostFrequentEnquiryPorpose'] = group2[('enq_purpose','findMode')]\n\n\n# In[29]:\n\n\nvalues = []\nfor i in group2.customer_no:\n values.append(newdf1[newdf1.customer_no==i].enq_purpose.values[0])\ndf_derived['mostRecentEnquiryPorpose'] = values\n\n\n# In[30]:\n\n\nnewdf2 = df_data.select_dtypes(['float64', 'int64', 'float32','int32'])\nfor col in newdf2.columns.values.tolist():\n df_derived[col] = newdf2[col]\n\n\n# In[31]:\n\n# df_derived.replace(np.nan,NaN,inplace=True)\ndf_derived.replace(np.inf,np.nan,inplace=True)\ndf_derived.replace(-np.inf,np.nan,inplace=True)\ndf_derived.to_csv(r'C:\\Users\\Dell\\Desktop\\Train.csv')\n\n\n# In[32]:\n\n\n# df_derived.isnull().sum(axis=0)\n\n\n# In[33]:\n\n\n# len(df_derived.columns.values)\n\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":9366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"613142898","text":"import numpy as np\nfrom keras.layers import (\n Conv2D, BatchNormalization, Dense, \n ZeroPadding2D, Activation, GlobalAveragePooling2D,\n Reshape, multiply, AveragePooling2D,\n UpSampling2D, Concatenate, Add, Lambda, Multiply\n)\nfrom keras.models import Model\nfrom keras.layers import Input\nimport keras.backend as K\nfrom keras.layers import DepthwiseConv2D, PReLU\nfrom keras.regularizers import l2\n\nIMG_HEIGHT = 224\nIMG_WIDTH = 224\nIMG_CHANNEL = 3\nCLASSES = [\"Background\", \"Person\"]\nN_CLASSES = 2\nIMAGE_DATA_FORMAT = K.image_data_format()\n\n\nclass SiNet:\n def __init__(self, img_height, img_width, img_channel, n_classes, reg=1e-4):\n self.img_height = img_height\n self.img_width = img_width\n self.img_channel = img_channel\n self.n_classes = n_classes\n self.reg = reg\n self.channel_axis = 1 if K.image_data_format() == \"channels_first\" else -1\n self.alpha = 1.0\n self.image_val = 0.017\n self.mean_substraction = [103.94, 116.78, 123.68]\n \n def relu6(self, x):\n return K.relu(x, max_value=6)\n \n def _conv_block(self, inputs, filters, alpha, strides=(1,1), kernel=(3,3), block_id=1, padding=\"valid\"):\n \"\"\"\"\"\"\n filters = int(filters * alpha)\n \n if padding==\"same\":\n x = inputs\n else:\n x = ZeroPadding2D((1, 1), data_format=IMAGE_DATA_FORMAT, \n name=\"conv_%s_pad\" % block_id)(inputs) \n \n x = Conv2D(filters, kernel, data_format=IMAGE_DATA_FORMAT, \n padding=padding, use_bias=False, strides=strides, \n kernel_initializer=\"he_normal\", kernel_regularizer=l2(self.reg), \n name=\"conv_%s\" % block_id)(x)\n x = BatchNormalization(axis=self.channel_axis, name=\"conv_%s_bn\" % block_id)(x)\n x = Activation(\"relu\", name=\"conv_%s_act\" % block_id)(x)\n \n return x\n \n def _pointwise_conv_block(self, inputs, pointwise_conv_filters, alpha, \n strides=(1, 1), block_id=1):\n x = Conv2D(pointwise_conv_filters, \n (1, 1),\n data_format=IMAGE_DATA_FORMAT,\n padding=\"same\",\n use_bias=False,\n strides=(1, 1),\n kernel_initializer=\"he_normal\",\n kernel_regularizer=l2(self.reg),\n name=\"conv_pw_%s\" % block_id)(inputs)\n x = BatchNormalization(axis=self.channel_axis,\n name=\"conv_pw_%s_bn\" % block_id)(x)\n x = Activation(\"relu\", name=\"conv_pw_%s_relu\" % block_id)(x)\n \n return x\n \n def _depthwise_conv_block(self, inputs, pointwise_conv_filters, alpha, \n depth_multiplier=1, strides=(1, 1), block_id=1, \n kernel=(3,3), padding_size=(1, 1)):\n \"\"\"\"\"\"\n pointwise_conv_filters = int(pointwise_conv_filters * alpha)\n \n x = ZeroPadding2D(padding_size, \n data_format=IMAGE_DATA_FORMAT,\n name=\"conv_pad_%s\" % block_id)(inputs)\n x = DepthwiseConv2D(kernel_size=kernel,\n data_format=IMAGE_DATA_FORMAT,\n depth_multiplier=depth_multiplier,\n strides=strides,\n use_bias=False,\n depthwise_regularizer=l2(self.reg),\n name=\"conv_dw_%s\" % block_id)(x)\n x = BatchNormalization(axis=self.channel_axis,\n name=\"conv_dw_%s_bn\" % block_id)(x)\n # x = Activation(\"PReLu\", name=\"conv_dw_%d_Prelu\" % block_id)(x)\n x = PReLU(name=\"conv_dw_%s_Prelu\" % block_id)(x)\n \n x = self._pointwise_conv_block(x, pointwise_conv_filters, self.alpha, block_id=block_id)\n \n return x\n \n def _squeeze_excite_block(self, inputs, ratio=16, block_id=1):\n filters = inputs.shape[self.channel_axis]\n se_shape = (1, 1, filters) if self.channel_axis == -1 else (filters, 1, 1)\n \n se = GlobalAveragePooling2D(name=\"squeeze_glo_avg_%s\" % block_id)(inputs)\n se = Dense(filters // ratio, activation=\"relu\", \n kernel_initializer=\"he_normal\",\n kernel_regularizer=l2(self.reg),\n use_bias=False, name=\"squeeze_squ_%s\" % block_id)(se)\n se = Dense(filters, activation=\"relu\", \n kernel_initializer=\"he_normal\",\n kernel_regularizer=l2(self.reg),\n use_bias=False, \n name=\"squeeze_exci_%s\" % block_id)(se)\n se = multiply([inputs, se], name=\"squeeze_scale_%s\" % block_id)\n \n return se\n \n def _depthwise_conv_se_block(self, inputs, pointwise_conv_filters, alpha, \n depth_multiplier=1, strides=(2, 2), block_id=1,\n kernel=(3, 3), ratio=16):\n \"\"\"\n DS-Conv + SE\n \"\"\"\n x = self._depthwise_conv_block(inputs, pointwise_conv_filters, alpha, \n block_id=block_id, strides=strides)\n # x = Activation(\"relu\")(x)\n x = self._squeeze_excite_block(x, ratio=ratio, block_id=block_id)\n x = Activation(\"relu\")(x)\n \n return x\n \n def _s2_block(self, inputs, pointwise_conv_filters, alpha, \n depth_multiplier=1, strides=(1, 1), block_id=1,\n kernel=(3,3), pool_size=(1,1), padding_size=(1, 1)):\n x = AveragePooling2D(pool_size=pool_size, strides=(2, 2), \n data_format=IMAGE_DATA_FORMAT, padding=\"same\")(inputs)\n x = Activation(\"relu\")(x)\n x = self._depthwise_conv_block(x, pointwise_conv_filters, alpha, \n block_id=block_id, kernel=kernel, \n padding_size=padding_size)\n x = UpSampling2D(size=(2, 2), interpolation=\"bilinear\", name=\"s2_block_%s\" % block_id)(x)\n x = BatchNormalization(axis=self.channel_axis)(x)\n x = Activation(\"relu\")(x)\n \n return x\n \n def _s2_module(self, inputs, pointwise_conv_filters, alpha,\n depth_multiplier=1, strides=(1, 1), block_id=1,\n kernel_conv=(3, 3), kernel_ds_1=(3, 3), \n kernel_ds_2=(3, 3), pad_ds_1=(1, 1), pad_ds_2=(1, 1),\n pool_block_1=(1, 1), pool_block_2=(1, 1)):\n \"\"\"\n The function to build S2 block\n \"\"\"\n x = self._conv_block(inputs, pointwise_conv_filters, alpha, \n kernel=(1, 1), block_id=block_id, padding=\"same\")\n x1 = self._s2_block(x, pointwise_conv_filters, alpha, depth_multiplier=depth_multiplier,\n strides=strides, kernel=kernel_ds_1, block_id=str(block_id) + \"_1\",\n padding_size=pad_ds_1, pool_size=pool_block_1)\n \n x2 = self._s2_block(x, pointwise_conv_filters, alpha, depth_multiplier=depth_multiplier,\n strides=strides, kernel=kernel_ds_2, block_id=str(block_id) + \"_2\", \n padding_size=pad_ds_2, pool_size=pool_block_2)\n \n x = Concatenate(axis=self.channel_axis)([x1, x2])\n x = Add()([inputs, x])\n # x = BatchNormalization(axis=self.channel_axis)(x)\n x = PReLU()(x)\n \n return x\n \n def build_encoder(self):\n \"\"\"\n Build encoder function\n \"\"\"\n \n input_shape = (IMG_HEIGHT, IMG_WIDTH, IMG_CHANNEL)\n \n if IMAGE_DATA_FORMAT == \"channels_first\":\n input_shape = (IMG_CHANNEL, IMG_HEIGHT, IMG_WIDTH)\n \n inputs = Input(shape=input_shape)\n \n x = Lambda(lambda z: z[...,::-1], output_shape=input_shape, \n name=\"swap_color_channel\")(inputs)\n \n if self.mean_substraction:\n x = Lambda(lambda z: (z - np.array(self.mean_substraction))*self.image_val,\n output_shape=input_shape,\n name=\"mean_substraction_inputs\")(x)\n # x = inputs\n\n x1 = self._conv_block(x, 12, self.alpha, strides=(2, 2), block_id=1)\n x2 = self._depthwise_conv_se_block(x1, 16, self.alpha, block_id=2)\n x3 = self._depthwise_conv_se_block(x2, 48, self.alpha, block_id=3, strides=(1, 1))\n x4 = self._s2_module(x3, 24, self.alpha, block_id=4, kernel_ds_2=(5, 5), pad_ds_2=(2, 2))\n x5 = self._s2_module(x4, 24, self.alpha, block_id=5)\n \n x6 = Concatenate(axis=self.channel_axis, name=\"concat_2_5\")([x2, x5])\n \n x7 = self._depthwise_conv_se_block(x6, 48, self.alpha, block_id=6)\n x8 = self._depthwise_conv_se_block(x7, 96, self.alpha, block_id=7, strides=(1, 1))\n x9 = self._s2_module(x8, 48, self.alpha, block_id=8, kernel_ds_2=(5, 5), pad_ds_2=(2, 2))\n x10 = self._s2_module(x9, 48, self.alpha, block_id=9)\n x11 = self._s2_module(x10, 48, self.alpha, block_id=10, \n kernel_ds_1=(5, 5), pad_ds_1=(2, 2),\n kernel_ds_2=(3, 3), pool_block_2=(2, 2))\n x12 = self._s2_module(x11, 48, self.alpha, block_id=11,\n kernel_ds_1=(5, 5), pad_ds_1=(2, 2),\n kernel_ds_2=(3, 3), pool_block_2=(4, 4))\n x13 = self._s2_module(x12, 48, self.alpha, block_id=12)\n x14 = self._s2_module(x13, 48, self.alpha, block_id=13,\n kernel_ds_1=(5, 5), pad_ds_1=(2, 2),\n kernel_ds_2=(5, 5), pad_ds_2=(2, 2))\n x15 = self._s2_module(x14, 48, self.alpha, block_id=14,\n kernel_ds_1=(3, 3), pool_block_1=(2, 2),\n kernel_ds_2=(3, 3), pool_block_2=(4, 4))\n x16 = self._s2_module(x15, 48, self.alpha, block_id=15,\n kernel_ds_1=(3, 3), pool_block_1=(1, 1),\n kernel_ds_2=(5, 5), pad_ds_2=(2, 2), pool_block_2=(2, 2))\n \n x17 = Concatenate(axis=self.channel_axis, name=\"concat_16_7\")([x16, x7])\n x17 = Activation(\"relu\")(x17)\n \n x = self._pointwise_conv_block(x17, N_CLASSES, self.alpha, block_id=16)\n # x8_pws = self._pointwise_conv_block(x8, N_CLASSES, self.alpha, block_id=17)\n # x = Add(name=\"x8_xlast_adding\")([x8_pws, x])\n x = Activation(\"relu\")(x)\n # x = Activation(\"relu\")(x)\n \n # x = Reshape((-1, self.n_classes))(x)\n\n # x = Activation(\"softmax\")(x)\n \n # model = Model(inputs=inputs, outputs=x)\n \n return inputs, x, x8, x5, x1\n \n def build_decoder(self):\n inputs, x, x8, x5, x1 = self.build_encoder()\n \n x = UpSampling2D((2, 2), data_format=IMAGE_DATA_FORMAT, interpolation=\"bilinear\")(x)\n x = BatchNormalization(axis=self.channel_axis)(x)\n x_ac = Activation(\"softmax\")(x)\n \n x_blocking = K.max(x_ac, axis=-1, keepdims=True)\n \n x_blocking = Lambda(lambda x: 1 - x, name=\"information_blocking_decoder\")(x_blocking)\n \n x5_pws = self._pointwise_conv_block(x5, self.n_classes, self.alpha, block_id=18)\n \n x_mul = Multiply()([x5_pws, x_blocking])\n x = Activation(\"relu\")(x)\n x = Add()([x_mul, x])\n x = Activation(\"relu\")(x)\n x = UpSampling2D((2, 2), interpolation=\"bilinear\")(x)\n x = BatchNormalization(axis=self.channel_axis)(x)\n x = Activation(\"relu\")(x)\n x = self._conv_block(x, self.n_classes, self.alpha, kernel=(1, 1), padding=\"same\", block_id=19)\n # x1_pws = self._pointwise_conv_block(x1, self.n_classes, self.alpha, block_id=20, strides=(1, 1))\n # x = Add()([x1_pws, x])\n # x = Activation(\"relu\")(x)\n x = UpSampling2D((2, 2), interpolation=\"bilinear\")(x)\n x = BatchNormalization(axis=self.channel_axis)(x)\n x = Activation(\"relu\")(x)\n x = Reshape((-1, self.n_classes))(x)\n x = Activation(\"softmax\")(x)\n \n model = Model(inputs=inputs, outputs=x)\n \n return model\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"580459833","text":"\"\"\" Implement deck of cards, with type hinting, using classes.\n Inspired by realpython\n https://realpython.com/python-type-checking/#playing-with-python-types-part-2 \"\"\"\nimport random\nimport sys\nfrom typing import List, Optional\n\nclass Card:\n \"\"\" Create Card. Uses Unicode character for the suit. \"\"\"\n\n SUITS = \"♠ ♡ ♢ ♣\".split()\n RANKS = \"2 3 4 5 6 7 8 9 10 J Q K A\".split()\n\n def __init__(self, suit: str, rank: str) -> None:\n \"\"\" Initialize Card with a suit and rank. \"\"\"\n self.suit = suit\n self.rank = rank\n\n def __repr__(self) -> str:\n return f\"{self.suit}{self.rank}\"\n\nclass Deck:\n \"\"\" Deck of cards. Depends on class Card.\n .create() is a class method to create the Deck.\n .deal() is a method to deal the Deck to all players and create hands. \"\"\"\n\n def __init__(self, cards: List[Card]) -> None:\n \"\"\" Initialize Deck with a list of cards. \"\"\"\n self.cards = cards\n\n @classmethod\n def create(cls, shuffle: bool = False) -> \"Deck\":\n \"\"\" Create a new deck of 52 cards.\n This should be done for the whole deck, not for each hand. Therefore classmethod.\n Need to use \"Deck\" in type hint since Deck class is being defined. \"\"\"\n\n cards = [Card(suit, rank)\n for rank in Card.RANKS\n for suit in Card.SUITS\n ]\n\n if shuffle:\n random.shuffle(cards) # Shuffles a list of Card\n\n # Take the list of Card and convert into the class Deck?\n return cls(cards)\n\n def deal(self, num_hands: int):\n \"\"\"Deal the cards in the deck into a number of hands. \"\"\"\n # Get and define the class of the object. save in local cls\n cls = self.__class__\n\n # Create num_hands decks from the deck by starting at i and skipping num_hands\n return tuple(cls(self.cards[i::num_hands])\n for i in range(num_hands))\n\nclass Player:\n \"\"\" Create a Player class.\n .play_card() gives a random card from Players hand and then removes it. \"\"\"\n\n def __init__(self, name: str, hand: Deck) -> None:\n \"\"\" Initialize Player with a name and a hand. \"\"\"\n self.name = name\n self.hand = hand\n\n def play_card(self) -> Card:\n \"\"\"Play a card from the player's hand. \"\"\"\n # Get a random card inside the hand. cards is an attribute of Deck.\n card = random.choice(self.hand.cards)\n self.hand.cards.remove(card)\n\n # !r is to call the __repr__ and <3 is left aligned with 3 spaces\n print(f\"{self.name}: {card!r:<3} \", end=\"\")\n return card\n\nclass Game:\n \"\"\" Runs the game. two instance variables: deck and hands\n .play() sets-up the game and then plays all Players cards.\n .player_order() creates a list of Players to play the hands. \"\"\"\n\n def __init__(self, *names: str) -> None:\n \"\"\" Set up the Deck and deal cards to 4 players.\n When type hinting on a *xxx only gives type but not List[type]. \"\"\"\n deck = Deck.create(shuffle=True)\n\n # In original solution. Not sure why so complicated. Changed it.\n # self.names = (list(names) + \"P1 P2 P3 P4\".split())[:4]\n self.names = \"P1 P2 P3 P4\".split()\n\n # Create all hands. zip will combine the list of names with the list of hands (Decks).\n # The dictionary comprehension will assign name with a Player intialization\n self.hands = {\n n: Player(n, h)\n for n, h in zip(self.names, deck.deal(4))\n }\n\n def play(self) -> None:\n \"\"\"Play a card game. \"\"\"\n start_player = random.choice(self.names)\n turn_order = self.player_order(start=start_player)\n\n # Play cards from each player's hand until start_player hand empty\n # Note that hands is an attribute/dictionary of the class.\n # Then pick the hand of the Player instance. Then the cards of the Deck attribute.\n while self.hands[start_player].hand.cards:\n # For each Player, play_card() to offer/remove/print a card\n for name in turn_order:\n self.hands[name].play_card()\n print()\n\n def player_order(self, start: Optional[str] = None) -> List[str]:\n \"\"\" Rotate player order so that start goes first. \"\"\"\n if start is None:\n start = random.choice(self.names)\n\n # Get location of the 1st name in the list of names\n start_idx = self.names.index(start)\n\n # Create the list of names by rotating through the list\n return self.names[start_idx:] + self.names[:start_idx]\n\nif __name__ == \"__main__\":\n # Read player names from command line\n player_names = sys.argv[1:]\n game = Game(*player_names) # Initialize the game\n game.play()\n","sub_path":"Classes/playing_cards_class.py","file_name":"playing_cards_class.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"240908401","text":"# /bin/usr/env python\n# -*- coding: utf-8 -*-\n\n\nfrom core.school import *\nfrom core import login\n\n\nclass People:\n \"\"\"\n 学校人员类\n \"\"\"\n\n def __init__(self, name, age, sex):\n self.name = name\n self.age = age\n self.sex = sex\n\n\nclass Admin(People):\n \"\"\"\n 管理员类\n \"\"\"\n role = 'admin'\n school = True\n group = True\n\n def __init__(self, name, age, sex):\n super(Admin, self).__init__(name, age, sex)\n\n def create_school(self):\n print('Create a School >>>')\n name = input('input school name >>:').strip()\n location = input('input school location >>:').strip()\n if name not in DataCtrl().get_schools():\n school = School(name, location)\n DataCtrl().set_info('school', school)\n log.info('[%s] 用户创建了学校 [%s]' % (self.name, school.name))\n return DataCtrl().get_school(name)\n\n def create_course(self):\n school_name = None\n while school_name not in DataCtrl().get_schools().keys():\n self.show_school()\n school_name = input('选择你要增加课程的学校 >>: ').strip()\n if school_name in DataCtrl().get_schools().keys():\n school = DataCtrl().get_school(school_name)\n else:\n print('input school error, try again')\n course = school.create_course()\n return course\n\n def create_group(self):\n course_name = None\n while course_name not in DataCtrl().get_courses().keys():\n self.show_course()\n course_name = input('选择你要创建班级的课程 >>:').strip()\n if course_name in DataCtrl().get_courses():\n course = DataCtrl().get_course(course_name)\n else:\n print('choose course error, try again.')\n group = course.create_group()\n return group\n\n def create_user(self):\n print('Create a User >>>')\n name = input('input user name >>:').strip()\n password = input('input user password >>:').strip()\n age = input('input user age >>:').strip()\n sex = input('input user sex >>:').strip()\n roles = ('admin', 'student', 'teacher')\n role = None\n while role not in roles:\n if role:\n print('角色输入有误,请重新输入')\n role = input('请输入用户角色类型(admin/student/teacher): ').strip()\n login.create_account(name, password, role)\n if role == 'admin':\n account = Admin(name, age, sex)\n elif role == 'student':\n account = Student(name, age, sex)\n elif role == 'teacher':\n account = Teacher(name, age, sex)\n assert account\n DataCtrl().set_info('people', account)\n log.info('[%s] 用户实例化 [%s]-[%s]成功' % (self.name, role, name))\n\n @staticmethod\n def show_school():\n print('学校列表'.center(20, \"=\"))\n obj = DataCtrl().get_schools()\n if obj:\n for n in obj.keys():\n print(n)\n\n @staticmethod\n def show_course():\n print('课程列表'.center(20, \"=\"))\n obj = DataCtrl().get_courses()\n if obj:\n for n in obj.keys():\n print(n)\n\n @staticmethod\n def show_group():\n obj = DataCtrl().get_groups()\n print('班级列表'.center(20, \"=\"))\n if obj:\n for n in obj.keys():\n print(n)\n\n @staticmethod\n def show_teacher():\n obj = DataCtrl().get_users()\n print('教师列表'.center(20, \"=\"))\n if obj:\n for key, value in obj.items():\n if value.role == 'teacher':\n print(key)\n\n @staticmethod\n def show_student():\n obj = DataCtrl().get_users()\n print('学生列表'.center(20, \"=\"))\n if obj:\n for key, value in obj.items():\n if value.role == 'student':\n print(key)\n\n @staticmethod\n def bind_school():\n obj = DataCtrl().get_users()\n print('待关联学校成员'.center(20, \"=\"))\n if obj:\n n = 0\n for key, value in obj.items():\n if not value.school:\n n += 1\n print(key)\n if n == 0:\n print('没有需要关联的成员')\n return True\n name = None\n while name not in DataCtrl().get_users().keys():\n name = input('选择你要关联学校的成员 >>:').strip()\n if name in DataCtrl().get_users():\n user = DataCtrl().get_user(name)\n user.join_school()\n else:\n print('choose course error, try again.')\n\n @staticmethod\n def bind_group():\n obj = DataCtrl().get_users()\n print('待关联班级的成员'.center(20, \"=\"))\n if obj:\n n = 0\n for key, value in obj.items():\n if not value.group:\n print(key)\n n += 1\n if n == 0:\n print('没有需要关联的成员')\n return True\n name = None\n while name not in DataCtrl().get_users().keys():\n name = input('选择你要关联班级的成员 >>:').strip()\n if name in DataCtrl().get_users():\n user = DataCtrl().get_user(name)\n user.join_group()\n else:\n print('choose course error, try again.')\n\n\nclass Teacher(People):\n \"\"\"\n 教师类\n \"\"\"\n role = 'teacher'\n\n def __init__(self, name, age, sex):\n super(Teacher, self).__init__(name, age, sex)\n self.group = {}\n self.school = None\n\n def join_school(self):\n school = None\n if self.school:\n print('已关联学校,不用重复关联')\n return True\n while school not in DataCtrl().get_schools():\n if school:\n print('学校输入有误,请重新输入')\n Admin.show_school()\n school = input('请输入学校: ').strip()\n self.school = DataCtrl().get_school(school)\n self.school.teacher.append(self.name)\n log.info('[%s] 校区增加了老师 [%s]' % (self.school.name, self.name))\n print('[%s] 校区增加了老师 [%s]' % (self.school.name, self.name))\n DataCtrl().save()\n\n def join_group(self):\n group = None\n while group not in DataCtrl().get_groups():\n if group:\n print('班级输入有误,请重新输入')\n obj = DataCtrl().get_groups()\n print('班级列表'.center(20, \"=\"))\n if obj:\n if len(self.group) < len(obj):\n for key in obj.keys():\n if key not in self.group:\n print(key)\n else:\n print('没有可管理的班级')\n return True\n group = input('请输入管理的班级: ').strip()\n if group not in self.group.keys():\n self.group[group] = {'status': True}\n else:\n print('管理班级已存在')\n if self.name not in DataCtrl().get_group(group).teacher:\n DataCtrl().get_group(group).teacher.append(self.name)\n log.info('[%s] 老师管理班级 [%s]' % (self.name, group))\n print('[%s] 老师管理班级 [%s]' % (self.name, group))\n DataCtrl().save()\n\n def show_group_list(self):\n \"\"\"\n 展示管理的班级\n :return:\n \"\"\"\n print('管理的班级列表'.center(20, \"=\"))\n if self.group:\n for group in self.group.keys():\n print(group)\n else:\n print('没有管理数据')\n\n def show_group_student(self):\n \"\"\"\n 展示班级的学生\n :param group:\n :return:\n \"\"\"\n group = None\n while group not in self.group.keys():\n if group:\n print('班级输入有误,请重新输入')\n # print('班级列表'.center(20, \"=\"))\n self.show_group_list()\n group = input('请输入管理的班级: ').strip()\n obj = DataCtrl().get_group(group)\n print('[%s]成员列表'.center(20, \"=\") % group)\n if obj.student:\n for student in obj.student:\n print(student)\n else:\n print('班级没有学生')\n\n\nclass Student(People):\n \"\"\"\n 学生类\n \"\"\"\n role = 'student'\n\n def __init__(self, name, age, sex):\n super(Student, self).__init__(name, age, sex)\n self.group = {}\n self.school = None\n\n def join_school(self):\n if self.school:\n print('已关联学校,不用重复关联')\n return True\n school = None\n while school not in DataCtrl().get_schools():\n if school:\n print('学校输入有误,请重新输入')\n Admin.show_school()\n school = input('请输入学校: ').strip()\n self.school = DataCtrl().get_school(school)\n self.school.student.append(self.name)\n log.info('[%s] 校区增加了学员 [%s]' % (self.school.name, self.name))\n print('[%s] 校区增加了学员 [%s]' % (self.school.name, self.name))\n DataCtrl().save()\n\n def join_group(self):\n group = None\n while group not in DataCtrl().get_groups():\n if group:\n print('班级输入有误,请重新输入')\n obj = DataCtrl().get_groups()\n print('班级列表'.center(20, \"=\"))\n if obj:\n if len(self.group) < len(obj):\n for key in obj.keys():\n if key not in self.group:\n print(key)\n else:\n print('没有可可学习的班级')\n return True\n group = input('请输入想学习的班级: ').strip()\n if group not in self.group.keys():\n self.group[group] = {'pay': False,\n 'status': False,\n }\n else:\n print('学习班级已存在')\n if self.name not in DataCtrl().get_group(group).student:\n DataCtrl().get_group(group).teacher.append(self.name)\n log.info('[%s] 学生参加了班级 [%s]' % (self.name, group))\n print('[%s] 学生参加了班级 [%s]' % (self.name, group))\n DataCtrl().save()\n\n def show_group_list(self):\n \"\"\"\n 展示学习的班级\n :return:\n \"\"\"\n print('学习的班级列表'.center(20, \"=\"))\n if self.group:\n for group in self.group.keys():\n print(group)\n else:\n print('没有学习数据')\n\n def pay_cost(self):\n for group_name, value in self.group.items():\n if not value['pay']:\n group = DataCtrl().get_group(group_name)\n if group:\n course = group.course\n price = course.price\n print('你的课程[%s]待支付费用[%s]' % (group_name, price))\n input('按任意键支付').strip()\n print('你支付了[%s]课程的费用 [%s]' % (group_name, price))\n self.group[group_name]['pay'] = True\n self.group[group_name]['status'] = True\n else:\n print('[%s] 课程已支付' % group_name)\n","sub_path":"Practice/modules3/class_system/core/people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":11629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"496790101","text":"# -*-coding:utf-8 -*-\n#Reference:**********************************************\n# @Time    : 2020-01-15 19:51\n# @Author  : Fabrice LI\n# @File    : 20200115_669_coin_change.py\n# @User    : liyihao\n# @Software : PyCharm\n# @Description: You are given coins of different denominations and a total amount of money amount.\n# Write a function to compute the fewest number of coins that you need to make up that amount.\n# If that amount of money cannot be made up by any combination of the coins, return -1.\n#Reference:**********************************************\n\"\"\"\nInput:\n[1, 2, 5]\n11\nOutput: 3\nExplanation: 11 = 5 + 5 + 1\n\nInput:\n[2]\n3\nOutput: -1\n\"\"\"\nfrom typing import List\n\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n MAX = float('inf')\n dp = [MAX for _ in range(amount + 1)]\n dp[0] = 0\n\n for i in range(amount + 1):\n for coin in coins:\n if i >= coin:\n dp[i] = min(dp[i], dp[i - coin] + 1)\n if dp[amount] == MAX:\n return -1\n return int(dp[amount])\n\n\nif __name__ == '__main__':\n s = Solution()\n coins = [1, 2, 5]\n amount = 11\n print(s.coinChange(coins, amount))\n","sub_path":"LintCode/DynamicProgramming/20200115_669_coin_change.py","file_name":"20200115_669_coin_change.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"456430303","text":"\"\"\"\ncvanalyzer.py - ComputerVisionAnalyzer thread.\n\"\"\"\n__version__ = \"0.0.2\"\n__author__ = \"Thomas J. Daley, J.D.\"\n__date__ = \"13 SEP 2017\"\n\nimport logging\n#import numpy as np\nimport os\nfrom threading import Thread\n\nimport cv2\n\nfrom cloudlib.conf import Config\n\n#from cloudlib.queuedalert import QueuedAlert\n\nclass ComputerVisionAnalyzer(Thread):\n \"\"\"\n This class looks for objects (faces for now) in the captured frame\n and, if it recognizes any objects, it lists them.\n\n A future version of this thread may run as a separate process on\n another server. Once it finds an object, such as a face, it will\n search a trained model to see if it can put a name to the face.\n \"\"\"\n def __init__(self, queue, notification_queue):\n ''' Initialize this thread. '''\n Thread.__init__(self)\n self.queue = queue\n self.notification_queue = notification_queue\n self.logger = logging.getLogger(\"sb.cloud.cvT\")\n\n # Load cascade file for detecting faces\n self.face_cascade = cv2.CascadeClassifier( \\\n '.{0}cascades{0}haarcascade_frontalface_alt2.xml' \\\n .format(os.path.sep))\n\n # pylint: disable=R0204\n # I don't need pylint telling me I've reassigned scratch variable types. Here.\n # Parameters to adjust the face-recognition performance.\n variable = \"CV_SCALE_FACTOR\"\n default = 1.3\n value = Config.CV_SCALE_FACTOR\n if value:\n try:\n self.scale_factor = float(value)\n except ValueError:\n self.logger.info(\"%s must be a number > 1. Using %f.\", variable, default)\n self.scale_factor = default\n else:\n self.scale_factor = default\n\n variable = \"CV_MIN_NEIGHBORS\"\n default = 5\n value = Config.CV_MIN_NEIGHBORS\n if value:\n try:\n self.min_neighbors = int(value)\n except ValueError:\n self.logger.info(\"%s must be an integer > 0. Using %s.\", variable, default)\n self.min_neighbors = default\n else:\n self.min_neighbors = default\n\n def run(self):\n ''' Perform the work of the thread. '''\n while True:\n queued_alert = self.queue.get()\n self.logger.debug(\"Dequeued alert %d\", queued_alert.item_id)\n cv2_gray_image = cv2.imdecode(queued_alert.alert.numpy_image, cv2.IMREAD_GRAYSCALE)\n faces = self.face_cascade.detectMultiScale(\n cv2_gray_image,\n self.scale_factor,\n self.min_neighbors)\n\n if len(faces) > 0:\n queued_alert.sms_text = \"Detected {} faces.\".format(len(faces))\n queued_alert.mail_text = queued_alert.sms_text # For now\n self.notification_queue.put(queued_alert)\n\n self.queue.task_done()\n","sub_path":"cloudlib/cvanalyzer.py","file_name":"cvanalyzer.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"382012142","text":"import os\nimport re\nimport os.path as osp\n\n\nincluded_exts = set(['.c', '.cpp', '.py', '.jsp', '.java', '.cs'])\nexcluded_path = ['lib', 'migrations', 'Django_Projects', 'Native']\nexcluded_path_pat = re.compile(r'|'.join(excluded_path))\nexcluded_fnames = ['agents.py', 'workflow.py']\nexcluded_fnames_pat = re.compile(r'|'.join(excluded_fnames))\n\nlines = 0\n\nlogs = []\nexts = set()\n\nfor base, dirs, files in os.walk('.'):\n if excluded_path_pat.search(base):\n continue\n for f in files:\n if excluded_fnames_pat.search(f):\n continue\n fname, ext = osp.splitext(f)\n if ext not in exts:\n exts.add(ext)\n if ext in included_exts:\n path = osp.join(base, f)\n with open(path, 'rb') as fp:\n line_count = len(fp.readlines())\n logs.append((path, line_count))\n lines += line_count\n\nlogs.sort(key=lambda x: x[1], reverse=True)\nprint(logs[:50])\nprint(lines)\n","sub_path":"snippets/line_counter.py","file_name":"line_counter.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"555316772","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 10 03:24:39 2017\r\n\r\n@author: Family\r\n\"\"\"\r\n\r\n#*****************************************************************************/\r\n# @file mlp_gaussian.c \r\n# @author Majid Nasiri 95340651\r\n# @version V1.0.0\r\n# @date 18 April 2017\r\n# @brief \r\n#*****************************************************************************/\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n#from scipy import spatial\r\nimport Kmeans\r\n\r\nfor i in range(50): print(' ') \r\nplt.close(\"all\")\r\n\r\n#define Macros\r\nCLASS_NUM=2\r\nSAMPLE_PER_CLASS=1000\r\n\r\nsamples_class0=np.random.multivariate_normal([4, 0],[[2, 0],[0, 2]],SAMPLE_PER_CLASS)\r\nsamples_class1=np.random.multivariate_normal([0, 4],[[2, 0],[0, 2]],SAMPLE_PER_CLASS)\r\n\r\nX = np.concatenate((samples_class0, samples_class1)).T\r\nt = np.concatenate((np.zeros([SAMPLE_PER_CLASS,1]), np.ones([SAMPLE_PER_CLASS,1]))).T\r\n\r\nmaxEpoch=20 # minimum 2 epoch\r\nK = 2\r\nvar_threshold = 0.01\r\ndist_threshold = 0.01\r\n\r\ncluster, centers, iterration = Kmeans.kmeans(X, K, var_threshold, dist_threshold, maxEpoch)\r\n\r\nprint('centers=\\n', centers[:,:,iterration])\r\nprint(iterration)\r\n\r\ncenter_displacement = np.diff(centers[:,:,:], axis = 2)\r\n\r\n\r\nplt.figure(1)\r\nfor i in range(centers.shape[0]):\r\n for j in range(centers.shape[1]):\r\n plt.plot(np.arange(0,iterration), center_displacement[i,j,:iterration])\r\nplt.xlabel('Epoch')\r\nplt.ylabel('Displacement Of centers')\r\nplt.show()\r\nplt.grid()\r\nplt.savefig('..\\images\\iris_kmeans.jpg')\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"machine_learning/clustering/Kmeans_gaussian.py","file_name":"Kmeans_gaussian.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"496390391","text":"from selenium import webdriver\nimport requests\n\n\ndef get_links(url):\n \"\"\"Find all links on page at the given url.\n Return a list of all link addresses, as strings.\n \"\"\"\n from webdriver_manager.chrome import ChromeDriverManager\n\n links = []\n browser = webdriver.Chrome(executable_path='/Users/supakorn/Downloads/chromedriver')\n browser.get(url)\n elements = browser.find_elements_by_tag_name(\"a\")\n for a in elements:\n links.append(a.get_attribute('href'))\n browser.close()\n return links\n\ndef invalid_urls(urllist):\n invalidlist = []\n for url in urllist:\n r = requests.head(url)\n if r.status_code == 404:\n invalidlist.append(url)\n return invalidlist \n\n\nif __name__ == \"__main__\":\n hreflist = get_links(\"https://cpske.github.io/ISP/\")\n for href in hreflist:\n print(\"Valid: \" + href)\n invalidurl = invalid_urls(hreflist) \n for invalid in invalidurl:\n print(\"Broken: \" + invalid)\n\n\n\n\n","sub_path":"polls/tests/link_invalid_url_test.py","file_name":"link_invalid_url_test.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"619151101","text":"'''Top bar styling\r\n'''\r\nfrom djpcms.media.style import *\r\n\r\nfrom . import classes\r\n\r\n# Control the size\r\ncssv.topbar.height = px(40)\r\ncssv.topbar.padding = spacing(px(10), px(10))\r\ncssv.topbar.margin_horizontal = px(10)\r\ncssv.topbar.secondary_width = px(160)\r\ncssv.topbar.shadow = '0 4px 8px rgba(0, 0, 0, 0.2)'\r\ncssv.topbar.radius = 0\r\n\r\n# Main navigation\r\n# Color\r\ncssv.topbar.default.background = ('v', '#333', '#222')\r\ncssv.topbar.default.color = '#BFBFBF'\r\ncssv.topbar.default.text_decoration = 'none'\r\ncssv.topbar.default.text_shadow = '0 1px 0 rgba(0, 0, 0, 0.5)'\r\n# hover\r\ncssv.topbar.hover.background = color('333')\r\ncssv.topbar.hover.color = color('fff')\r\ncssv.topbar.hover.text_decoration = cssv.topbar.default.text_decoration\r\ncssv.topbar.hover.text_shadow = cssv.topbar.default.text_shadow\r\n# active\r\ncssv.topbar.active.background = cssv.color.black\r\ncssv.topbar.active.color = cssv.color.white\r\ncssv.topbar.active.text_decoration = cssv.topbar.hover.text_decoration\r\ncssv.topbar.active.text_shadow = cssv.topbar.hover.text_shadow\r\n\r\n# Subnavigation\r\n#Color\r\ncssv.topbar.secondary_default.background = cssv.topbar.hover.background\r\ncssv.topbar.secondary_default.color = '#BFBFBF'\r\ncssv.topbar.secondary_default.text_decoration = 'none'\r\ncssv.topbar.secondary_default.text_shadow = '0 1px 0 rgba(0, 0, 0, 0.5)'\r\n# hover\r\ncssv.topbar.secondary_hover.background = color('222')\r\ncssv.topbar.secondary_hover.color = color('fff')\r\ncssv.topbar.secondary_hover.text_decoration = cssv.topbar.secondary_default.text_decoration\r\ncssv.topbar.secondary_hover.text_shadow = cssv.topbar.secondary_default.text_shadow\r\n# active\r\ncssv.topbar.secondary_active.background = cssv.color.black\r\ncssv.topbar.secondary_active.color = cssv.color.white\r\ncssv.topbar.secondary_active.text_decoration = cssv.topbar.secondary_hover.text_decoration\r\ncssv.topbar.secondary_active.text_shadow = cssv.topbar.secondary_hover.text_shadow\r\n# brand\r\ncssv.topbar.brand.color = '#ffffff'\r\ncssv.topbar.brand.font_size = px(20)\r\ncssv.topbar.brand.font_weight = None\r\ncssv.topbar.brand.font_family = None\r\ncssv.topbar.brand.padding = px(20)\r\ncssv.topbar.brand.width = None\r\n\r\n# BREADCRUMBS\r\ncssv.breadcrumbs.font_weight_start = None\r\ncssv.breadcrumbs.font_weight_step = None\r\ncssv.breadcrumbs.font_size = pc(130)\r\ncssv.breadcrumbs.font_weight = 'bold'\r\ncssv.breadcrumbs.line_height = None\r\ncssv.breadcrumbs.color = None\r\ncssv.breadcrumbs.text_decoration = 'none'\r\n\r\nclass topbar(mixin):\r\n\r\n def __call__(self, elem):\r\n tb = cssv.topbar\r\n height = tb.height\r\n elem['height'] = height\r\n elem['z_index'] = 10000\r\n elem['overflow'] = 'visible'\r\n elem['margin-top'] = 0\r\n elem['margin-bottom'] = 0\r\n elem['border'] = 'none'\r\n gradient(tb.default.background)(elem)\r\n\r\n css('.nav',\r\n horizontal_navigation(\r\n default=bcd(**tb.default.params()),\r\n active=bcd(**tb.active.params()),\r\n hover=bcd(**tb.hover.params()),\r\n secondary_default=bcd(**tb.secondary_default.params()),\r\n secondary_active=bcd(**tb.secondary_active.params()),\r\n secondary_hover=bcd(**tb.secondary_hover.params()),\r\n height=height,\r\n padding=tb.padding,\r\n margin=cssv.topbar.margin_horizontal,\r\n secondary_width=tb.secondary_width),\r\n cssa('.secondary-nav',\r\n horizontal_navigation(\r\n float='right',\r\n margin=cssv.topbar.margin_horizontal)),\r\n parent=elem)\r\n # branding\r\n brand = tb.brand\r\n padding = spacing(brand.padding)\r\n size = min(brand.font_size, height)\r\n space = height - size\r\n if space:\r\n padding1 = space // 2\r\n padding2 = space - padding1\r\n else:\r\n padding1 = 0\r\n padding2 = 0\r\n padding = spacing(padding1, padding.right, padding2, padding.left)\r\n css('a.brand',\r\n color = brand.color,\r\n display = 'block',\r\n width = brand.width,\r\n font_weight = brand.font_weight,\r\n font_family = brand.font_family,\r\n font_size = size,\r\n line_height = size,\r\n padding = padding,\r\n parent=elem)\r\n #\r\n # form\r\n #size += 2*(cssv.input.padding + cssv.input.border_size)\r\n #space = cssv.topbar_height - size\r\n #if space < 3:\r\n # raise ValueError('Top bar to narrow to include the form')\r\n #spaceh = (space // 2)\r\n #space = space - spaceh\r\n #if space == spaceh:\r\n # space += 1\r\n #yield css('form',\r\n # parent = elem,\r\n # margin = '{0}px 0 0 0'.format(space))\r\n\r\n\r\ncss('.'+classes.topbar, topbar())\r\ncss('.'+classes.topbar_container,\r\n gradient(cssv.topbar.default.background))\r\ncss('div.'+classes.topbar_fixed,\r\n fixtop())\r\ncssa('.editable',\r\n css('.topbar-fixed', unfixtop()))\r\n\r\n\r\ncss('.'+classes.breadcrumbs,\r\n css('ul, ul li', list_style='none', display='inline'),\r\n css('a',\r\n bcd(**cssv.breadcrumbs.params()),\r\n font_weight=cssv.breadcrumbs.font_weight),\r\n css('.divider', padding=spacing(0,px(5))),\r\n font_size=cssv.breadcrumbs.font_size,\r\n font_weight=cssv.breadcrumbs.font_weight,\r\n line_height=cssv.breadcrumbs.line_height)\r\n","sub_path":"djpcms/apps/nav/style.py","file_name":"style.py","file_ext":"py","file_size_in_byte":5432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"318107522","text":"import os\n\nfrom modelos.tecal import Tecal\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, ParseMode\n\nfrom telegram.ext import Updater, CallbackQueryHandler\nfrom telegram.ext import CommandHandler, ConversationHandler, MessageHandler, Filters\nimport constantes\nfrom utils import error_letra\n\nCHOOSING, VOCABULARIO, MORFOLOGIA, SINTAXIS, TOTAL = range(5)\n\n\n\nedades_tecal = [\n ['3 - 3.11 años'],\n ['4 - 4.11 años'],\n ['5 - 5.11 años'],\n ['6 - 6.11 años'],\n ['Volver']\n]\n\nmarkup_edad = ReplyKeyboardMarkup(edades_tecal, one_time_keyboard=True)\n\ndef set_vocabulario(update, context):\n text = update.message.text\n context.user_data['vocabulario'] = text\n update.message.reply_text(\n 'Ha establecido el puntaje de vocabulario: {}. Ahora ingrese la *puntuación de morfologia*.'.format(text.lower()),\n parse_mode=ParseMode.MARKDOWN)\n return MORFOLOGIA\n\n\ndef set_morfologia(update, context):\n text = update.message.text\n context.user_data['morfologia'] = text\n update.message.reply_text(\n 'Ha establecido el puntaje de morfología: {}. Ahora ingrese la *puntuación de sintaxis*.'.format(text.lower()),\n parse_mode=ParseMode.MARKDOWN)\n return SINTAXIS\n\ndef set_sintaxis(update, context):\n text = update.message.text\n context.user_data['sintaxis'] = text\n update.message.reply_text(\n 'Ha establecido el puntaje de sintaxis: {}. Ahora ingrese la *puntuación total*'.format(text.lower()),\n parse_mode=ParseMode.MARKDOWN)\n return TOTAL\n\ndef set_total(update, context):\n text = update.message.text\n context.user_data['total'] = text\n ud = context.user_data\n edad = ud['edad']\n individuo = Tecal(edad[0], ud['vocabulario'], ud['morfologia'], ud['sintaxis'], ud['total'])\n\n update.message.reply_text(\n 'Ha establecido el puntaje de sintaxis: {}.\\nEl resultado es el siguiente:\\n\\n{}'.format(text.lower(), individuo),\n reply_markup=markup_edad)\n return CHOOSING\n\ndef set_edad(update, context):\n text = update.message.text\n context.user_data['edad'] = text\n update.message.reply_text(\n f\"Edad es {text}. Escriba la puntuación de vocabulario.\")\n\n return VOCABULARIO\n\ndef done(update, context):\n user_data = context.user_data\n if 'choice' in user_data:\n del user_data['choice']\n update.message.reply_text(constantes.TEXTO_PRINCIPAL)\n user_data.clear()\n return ConversationHandler.END\n\ndef start_tecal(update, context):\n update.message.reply_text(\n 'Para el cálculo de TECAL primero debe definir la edad: ',\n reply_markup=markup_edad)\n\n return CHOOSING\n\n\ndef tecal_conversation_handler():\n return ConversationHandler(\n entry_points=[CommandHandler('tecal', start_tecal)],\n\n states={\n CHOOSING: [\n MessageHandler(\n Filters.regex('^(3 - 3.11 años|4 - 4.11 años|5 - 5.11 años|6 - 6.11 años)$'),\n set_edad\n )\n ],\n VOCABULARIO: [MessageHandler(\n Filters.regex(constantes.REGEX_ONLY_NUMBERS),\n set_vocabulario\n ),\n MessageHandler(\n Filters.regex(constantes.REGEX_ONLY_STRINGS),\n error_letra\n )\n ],\n MORFOLOGIA: [MessageHandler(\n Filters.regex(constantes.REGEX_ONLY_NUMBERS),\n set_morfologia\n ),\n MessageHandler(\n Filters.regex(constantes.REGEX_ONLY_STRINGS),\n error_letra\n )\n ],\n SINTAXIS: [MessageHandler(\n Filters.regex(constantes.REGEX_ONLY_NUMBERS),\n set_sintaxis\n ),\n MessageHandler(\n Filters.regex(constantes.REGEX_ONLY_STRINGS),\n error_letra\n )],\n TOTAL: [MessageHandler(\n Filters.regex(constantes.REGEX_ONLY_NUMBERS),\n set_total\n ),\n MessageHandler(\n Filters.regex(constantes.REGEX_ONLY_STRINGS),\n error_letra\n )],\n },\n\n fallbacks=[MessageHandler(Filters.regex('^Volver$'), done)]\n )\n\n\n\nif __name__ == '__main__':\n import logging\n\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\n logger = logging.getLogger(__name__)\n BOT_KEY = os.environ['BOT_KEY']\n\n updater = Updater(token=BOT_KEY, use_context=True)\n dispatcher = updater.dispatcher\n # dispatcher.add_handler(CommandHandler('start', edna))\n dispatcher.add_handler(tecal_conversation_handler())\n\n updater.start_polling()\n","sub_path":"tecal.py","file_name":"tecal.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"544025255","text":"__author__ = \"\"\n__copyright__ = \"Licensed under GPLv2 or later.\"\n\nfrom dataStore.lepdClient.LepdClient import LepdClient\nfrom dataStore.influxDbUtil.dbUtil import MyInfluxDbClient\n\nimport time\n\n'''\nfetch data related to GetProcStat from lepd by lepdClient and \nstore the returned data into the influxDB by influxDBClient.\n'''\ndef pullAndStoreGetProcStat(lepdClient, influxDbClient):\n res = lepdClient.sendRequest('GetProcStat')\n # print(res)\n # str1 = res[\"result\"].split(\"\\n\")\n # for x in str1:\n # print(x)\n json_body = [\n {\n \"measurement\": \"GetProcStat\",\n \"tags\": {\n # the address of lepd\n \"server\": lepdClient.server\n },\n # \"time\": \"2017-03-12T22:00:00Z\",\n \"fields\": {\n \"procstat\": res[\"result\"]\n\n }\n }\n ]\n\n influxDbClient.write_points(json_body)\n\nif (__name__ == '__main__'):\n lepdClient = LepdClient('localhost')\n influxDbClient = MyInfluxDbClient('localhost')\n for i in range(1):\n pullAndStoreGetProcStat(lepdClient, influxDbClient)\n time.sleep(1)\n","sub_path":"dataStore/modules/raw/pullAndStoreGetProcStat.py","file_name":"pullAndStoreGetProcStat.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"30218887","text":"class Meta:\n\n def __getattr__(self, attr):\n print(attr)\n\n def __setattr__(self, attr, i):\n print(attr, i)\n \n\nif __name__ == '__main__':\n\n a = Meta()\n a.x\n a.y\n a.z = 1\n a + 2\n \n","sub_path":"Learinig_Python_4th_Lutz/EX/6_4_meta.py","file_name":"6_4_meta.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"591832586","text":"from __future__ import print_function\n\nimport sys\nimport os\nimport time\n\nimport numpy as np\n# np.random.seed(1234) \nimport theano\nimport theano.tensor as T\nimport lasagne\n\nimport cPickle as pickle\nimport gzip\n\nimport ipdb\nimport lab\n\nfrom pylearn2.datasets.zca_dataset import ZCA_Dataset \nfrom pylearn2.utils import serial\n\nfrom collections import OrderedDict\nfrom argparse import ArgumentParser\n\n\n######################################### load dataset ###########################################\ndef load_dataset():\n\ttrain_set_size = 45000\n\tprint(\"train_set_size = \"+str(train_set_size))\n\t\n\tprint('Loading CIFAR-10 dataset...')\n\t\n\tpreprocessor = serial.load(\"/home/eric/Desktop/powerLaw/power-law/expt3/cnn/cifar10/pylearn2_gcn_whitened/preprocessor.pkl\")\n\ttrain_set = ZCA_Dataset(\n\t\tpreprocessed_dataset=serial.load(\"/home/eric/Desktop/powerLaw/power-law/expt3/cnn/cifar10/pylearn2_gcn_whitened/train.pkl\"),\n\t\tpreprocessor = preprocessor,\n\t\tstart=0, stop = train_set_size)\n\tvalid_set = ZCA_Dataset(\n\t\tpreprocessed_dataset= serial.load(\"/home/eric/Desktop/powerLaw/power-law/expt3/cnn/cifar10/pylearn2_gcn_whitened/train.pkl\"),\n\t\tpreprocessor = preprocessor,\n\t\tstart=45000, stop = 50000) \n\ttest_set = ZCA_Dataset(\n\t\tpreprocessed_dataset= serial.load(\"/home/eric/Desktop/powerLaw/power-law/expt3/cnn/cifar10/pylearn2_gcn_whitened/test.pkl\"),\n\t\tpreprocessor = preprocessor)\n\t# bc01 format\n\tX_train = train_set.X.reshape(-1,3,32,32)\n\tX_val = valid_set.X.reshape(-1,3,32,32)\n\tX_test = test_set.X.reshape(-1,3,32,32)\n\t\n\t# flatten targets\n\ty_train = train_set.y.flatten()\n\ty_val = valid_set.y.flatten()\n\ty_test = test_set.y.flatten()\n\t\n\treturn X_train, y_train, X_val, y_val, X_test, y_test\n\n\ndef build_sparse_cnn(mask, input_var=None):\n\t# Input layer, as usual:\n\t### one may also add dropout layer according to the icml 2017 paper\n\tnetwork = lasagne.layers.InputLayer(shape=(None, 3, 32, 32), input_var=input_var)\n\tnetwork = lab.Conv2DLayer(mask[0], network, num_filters=32, filter_size=(3, 3), pad=1)\n\tnetwork = lab.Conv2DLayer(mask[2], network, num_filters=32, filter_size=(3, 3),pad=1)\n\tnetwork = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2))\n\t# network = lasagne.layers.DropoutLayer(network, p=0.25)\n\tnetwork = lab.Conv2DLayer(mask[4], network, num_filters=64, filter_size=(3, 3), pad=1)\t\t\t\n\tnetwork = lab.Conv2DLayer(mask[6], network, num_filters=64, filter_size=(3, 3), pad=1)\n\tnetwork = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) \n\t# network = lasagne.layers.DropoutLayer(network, p=0.25)\t \n\tnetwork = lab.DenseLayer(mask[8], network, num_units=512, nonlinearity=lasagne.nonlinearities.rectify) \n\t# network = lasagne.layers.DropoutLayer(network, p=0.5) \n\tnetwork = lab.DenseLayer(mask[10], network, num_units=10, nonlinearity=lasagne.nonlinearities.softmax) \n\n\treturn network\n\n############################### Batch iterator ###############################\ndef iterate_minibatches(inputs, targets, batchsize, shuffle=True):\n\tassert len(inputs) == len(targets)\n\tif shuffle:\n\t\tindices = np.arange(len(inputs))\n\t\tnp.random.shuffle(indices)\n\tfor start_idx in range(0, len(inputs) - batchsize + 1, batchsize):\n\t\tif shuffle:\n\t\t\texcerpt = indices[start_idx:start_idx + batchsize]\n\t\telse:\n\t\t\texcerpt = slice(start_idx, start_idx + batchsize)\n\t\tyield inputs[excerpt], targets[excerpt]\n\n\n# ############################## Main program ################################\n\ndef main(prune_fraction, num_epochs=500):\n\t# Load the dataset\n\tprint(\"Loading data...\")\n\tX_train, y_train, X_val, y_val, X_test, y_test = load_dataset()\n\t# Prepare Theano variables for inputs and targets\n\tinput_var = T.tensor4('inputs')\n\t# input_var = T.fmatrix('inputs')\n\ttarget_var = T.ivector('targets')\n\n\n\twith np.load('cifar/model/dense_cnn.npz') as f:\n\t param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n\n############################### thresholding the weights ##########################\n\n\tprune_fraction = prune_fraction\n\tthres = []\n\tmask = []\n\tfor i in range(len(param_values)):\n\t\tdata_current = np.abs(param_values[i])\n\t\tif len(param_values[i].shape)>1:\n\t\t\tvec_data = data_current.flatten()\n\t\t\ta = int(prune_fraction*data_current.size)\n\t\t\tthres_current = np.sort(vec_data)[a]\n\t\telse:\n\t\t\tthres_current = np.float32(0.0)\n\n\t\tmask_current = (data_current>thres_current).astype('int16') \n\t\t### int32 multiplied with flot32 gives float32, float32 multiplied with int32 gives float64\n\t\tparam_values[i] *= mask_current \n\n\t\tthres.append(thres_current)\n\t\tmask.append(mask_current)\n\n\tprint(thres)\n################################### rebuild sparse model ############################\n\tnetwork_s = build_sparse_cnn(mask, input_var)\t\n\n\t# Create a loss expression for training\n\tprediction = lasagne.layers.get_output(network_s)\n\tloss = lasagne.objectives.categorical_crossentropy(prediction, target_var)\n\tloss = loss.mean()\n\n\t# Create update expressions for training\n\tparams = lasagne.layers.get_all_params(network_s, trainable=True)\n\t# import ipdb; ipdb.set_trace()\n\tW_grads = lab.compute_grads1(loss, network_s, mask)\n\t# updates = lasagne.updates.nesterov_momentum(\n\t\t\t# loss_or_grads=W_grads, params=params, learning_rate=0.01, momentum=0.9)\n\tupdates = lasagne.updates.rmsprop(W_grads, params, learning_rate=0.0001)\n\n\ttest_prediction = lasagne.layers.get_output(network_s, deterministic=True)\n\ttest_loss = lasagne.objectives.categorical_crossentropy(test_prediction,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttarget_var)\n\ttest_loss = test_loss.mean()\n\ttest_acc = T.mean(T.eq(T.argmax(test_prediction, axis=1), target_var),\n\t\t\t\t\t dtype=theano.config.floatX)\n\n\n\ttrain_fn = theano.function([input_var, target_var], [loss, W_grads[0], W_grads[2], W_grads[4]], updates=updates)\n\tval_fn = theano.function([input_var, target_var], [test_loss, test_acc])\n\n\tlasagne.layers.set_all_param_values(network_s, param_values)\n############################### retraining ########################################\n\n\n\tprint(\"Starting retraining...\")\n\tbest_val_acc = 0\n\tbest_epoch = 0\n\t# We iterate over epochs:\n\tfor epoch in range(num_epochs):\n\t\t# In each epoch, we do a full pass over the training data:\n\t\ttrain_loss = 0\n\t\ttrain_batches = 0\n\t\tstart_time = time.time()\n\t\tfor batch in iterate_minibatches(X_train, y_train, 50, shuffle=True):\n\t\t\tinputs, targets = batch\n\t\t\ttmp, g1, g2, g3 = train_fn(inputs, targets)\n\t\t\t# import ipdb; ipdb.set_trace()\n\t\t\ttrain_loss += tmp\n\t\t\ttrain_batches += 1\n\n\t\ttrain_loss = train_loss / train_batches\n\n\t\t# And a full pass over the validation data:\n\t\tval_loss = 0\n\t\tval_acc = 0\n\t\tval_batches = 0\n\t\tfor batch in iterate_minibatches(X_val, y_val, 50, shuffle=False):\n\t\t\tinputs, targets = batch\n\t\t\tloss, acc = val_fn(inputs, targets)\n\t\t\tval_loss += loss\n\t\t\tval_acc += acc\n\t\t\tval_batches += 1\n\n\t\tval_loss = val_loss / val_batches\n\t\tval_acc = val_acc / val_batches * 100\n\t\t# Then we print the results for this epoch:\n\n\t\tif val_acc > best_val_acc:\n\t\t\tbest_val_acc = val_acc\n\t\t\tbest_epoch = epoch\t\t\t\n\t\t\t# After training, we compute and print the test error:\n\t\t\ttest_loss = 0\n\t\t\ttest_acc = 0\n\t\t\ttest_batches = 0\n\t\t\tfor batch in iterate_minibatches(X_test, y_test, 50, shuffle=False):\n\t\t\t\tinputs, targets = batch\n\t\t\t\tloss, acc = val_fn(inputs, targets)\n\t\t\t\ttest_loss += loss\n\t\t\t\ttest_acc += acc\n\t\t\t\ttest_batches += 1\n\t\t\ttest_loss = test_loss / test_batches\n\t\t\ttest_acc = test_acc / test_batches * 100\n\n\t\t\tnp.savez('cifar/model/sparse_cnn_{0}.npz'.format(prune_fraction), *lasagne.layers.get_all_param_values(network_s))\n\n\t\tprint(\"Epoch {} of {} took {:.3f}s\".format(\n\t\t\tepoch + 1, num_epochs, time.time() - start_time))\n\t\tprint(\" training loss:\\t\\t{:.6f}\".format(train_loss))\n\t\tprint(\" validation loss:\\t\\t{:.6f}\".format(val_loss))\n\t\tprint(\" validation accuracy:\\t\\t{:.2f} %\".format(val_acc))\n\t\tprint(\" test loss:\\t\\t\\t{:.6f}\".format(test_loss))\n\t\tprint(\" test accuracy:\\t\\t{:.2f} %\".format(test_acc))\n\t\t\n\t\twith open(\"cifar/model/sparse_cnn_{0}.txt\".format(prune_fraction), \"a\") as myfile:\n\t\t\tmyfile.write(\"{0} {1:.3f} {2:.3f} {3:.3f} {4:.3f} {5:.3f}\\n\".format(epoch, train_loss, val_loss, val_acc, test_loss, test_acc))\n\n\n\nif __name__ == \"__main__\":\n\tparser = ArgumentParser()\n\t# parser.add_argument(\"--model\", type=str, dest=\"model\",\n\t# \t\t\tdefault='cnn')\t\n\tparser.add_argument(\"--num_epochs\", type=int, dest=\"num_epochs\",\n\t\t\t\tdefault=100, help=\"number of epochs\") \n\tparser.add_argument(\"--prune_fraction\", type=float, dest=\"prune_fraction\",\n\t\t\t\tdefault=0.7, help=\"fraction of weights pruned away\") \n\targs = parser.parse_args()\n\n\tmain(**vars(args))\n","sub_path":"expt3/cnn/cifar_sparse.py","file_name":"cifar_sparse.py","file_ext":"py","file_size_in_byte":8476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"450179331","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThis file is to demonstrate HW2 for MATH optimization technique\r\n\r\nrosenbrock function: f(x) = 100*(x_2 - x_1^2)^2 + (1-x_1)^2\r\ngrad(f(x)) = [-400*x1*x2 + 400*x1^3 + 2*x1 - 2;\r\n 200*x2 - 200*x1^2]\r\nHess(f(x)) = [-400*x2 + 1200*x1^2 + 2, -400*x1;\r\n -400*x1, 200]\r\n \r\nCreated on Sat Feb 2 15:21:36 2019\r\n\r\n@author: jiryi\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\n# rosenbrock function\r\ndef rosenbrock_funcval(x):\r\n fval_x = 100*(x[1] - x[0]**2)**2 + (1-x[0])**2\r\n return fval_x\r\n\r\n# gradient calculation\r\ndef rosenbrock_gradval(x):\r\n pgrad_1 = - 400*x[0]*x[1] + 400*x[0]**3 + 2*x[0] - 2\r\n pgrad_2 = 200*x[1] - 200*(x[0]**2)\r\n grad = np.array([pgrad_1,pgrad_2]).reshape((2,1))\r\n return grad\r\n \r\n# Hessian calculation\r\ndef rosenbrock_hessval(x):\r\n pgrad_11 = -400*x[1] + 1200*x[0]**2 + 2\r\n pgrad_12 = -400*x[0]\r\n pgrad_22 = 200\r\n hess = np.array([[pgrad_11, pgrad_12],[pgrad_12, pgrad_22]])\r\n return hess\r\n\r\n# function surface and contour\r\ndef rosenbrock_vis():\r\n resolution = 0.01\r\n x0 = np.arange(-6.0,6.0,resolution)\r\n x1 = np.arange(-2.0,2.0,resolution)\r\n X0,X1 = np.meshgrid(x0,x1)\r\n funcval = 100*(X0 - X1**2)**2 + (1-X0)**2\r\n \r\n plt.figure()\r\n plt.contour(X0,X1,funcval,10)\r\n plt.title('Contour of Rosenbrock function')\r\n plt.xlabel('x1'); plt.ylabel('x2'); \r\n \r\n plt.figure()\r\n ax = plt.axes(projection='3d')\r\n ax.plot_surface(X0,X1,funcval)\r\n ax.scatter(1,1,0,c='r',marker='+',s=8*20)\r\n plt.title('Function surface')\r\n plt.xlabel('x1'); plt.ylabel('x2');\r\n # plt.axis('equal')\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n # test, function value, gradient, hessian at [1,1]\r\n x = np.array([2,1])\r\n func = rosenbrock_funcval(x)\r\n grad = rosenbrock_gradval(x)\r\n hess = rosenbrock_hessval(x)\r\n print('At point {}'.format(x))\r\n print('the function value is {}\\n'.format(func))\r\n print('the gradient is\\n {}'.format(grad))\r\n print('the Hessian is\\n {}'.format(hess))\r\n rosenbrock_vis()\r\n ","sub_path":"rosenbrock.py","file_name":"rosenbrock.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"627669821","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:\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return [] # edge case is not null but []\n\n \n frontier = [root]\n rst = []\n rst.append([root.val])\n \n while frontier:\n next = []\n next_rst = []\n for u in frontier:\n for v in [u.left,u.right]:\n if v:\n next_rst.append(v.val)\n next.append(v) # should be the object but not the simple values\n frontier = next\n if len(next_rst)>0: # should exlude the final level which is empty\n rst.append(next_rst)\n\n \n return rst\n \nnode0=TreeNode(3)\nnode1=TreeNode(9)\nnode2=TreeNode(20)\nnode3=TreeNode(15)\nnode4=TreeNode(7)\n\nnode0.left = node1\nnode0.right = node2\nnode2.left = node3\nnode2.right = node4\n\nx=Solution()\nx.levelOrder(node0)\nnode_null = None\nx.levelOrder(node_null)","sub_path":"leetcode/102_levelOrder.py","file_name":"102_levelOrder.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"448214459","text":"import pickle\nimport tensorflow as tf\nfrom posenet2kinect.model import Pose2KinectModel\n\n\nclass Pose2KinectEstimator:\n def __init__(self, pose2kinect_config, model_path=None):\n self._config = pose2kinect_config\n self._model_path = model_path or self._config.model.path\n self._ml_model = Pose2KinectModel(self._config)\n self._ml_model.compile()\n self._session = tf.Session()\n self._session.run(tf.global_variables_initializer())\n self._ml_model.load(self._model_path)\n self._feature_processor = self._load_feature_processor()\n self._label_processor = self._load_label_processor()\n\n def predict(self, input_features):\n input_features = self._feature_processor.transform(input_features)\n predictions = self._ml_model.predict(input_features)\n predictions = self._label_processor.inverse_transform(predictions)\n return predictions\n\n def _load_feature_processor(self):\n with open(self._config.model.feature_processor_path, \"rb\") as f:\n processor = pickle.load(f)\n return processor\n\n def _load_label_processor(self):\n with open(self._config.model.label_processor_path, \"rb\") as f:\n processor = pickle.load(f)\n return processor\n","sub_path":"posenet2kinect/estimator.py","file_name":"estimator.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"409986830","text":"APP_NAME = 'aandete.config.middleware:make_app'\nAPP_ARGS = ({},)\nAPP_KWARGS = dict()\nAPP_KWARGS.update({'beaker.session.type': 'google',\n 'beaker.session.table_name': 'beaker_session',\n 'beaker.session.key': 'pylonstestapp',\n 'beaker.session.secret': 'secret',\n 'beaker.cache.type': 'google',\n 'beaker.cache.table_name': 'beaker_cache'})\n# You can overwrite these separately for different dev/live settings:\nDEV_APP_ARGS = APP_ARGS\nDEV_APP_KWARGS = APP_KWARGS\nREMOVE_SYSTEM_LIBRARIES = ['webob']\n","sub_path":"app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"115133592","text":"from ParvisLib import MainID, MainWord\r\n\r\nsub_television = ['텔레비전','티브이','티이브이','티-브이','티부이','티비','텔레비젼','테레비전','테레비젼','태레비젼','태레비전','텔레비','테레비',\r\n '텔리비죤','텔레비죤','영상표기장치','방송수신기','방송수신장치','영상수신장치','영상수신기']\r\neng_television = ['tv','tv set','television','catv','broadcast','broadcast','televi']\r\n\r\nsub_surround = ['이웃','테두리','근처','가장자리','주위','인접','외부','환경','저면','후면','에지','이면','배면','양면']\r\neng_surround =[\r\n 'context','edge','surround','outline','circumstance','background','peripheral region','outdoor','inside',\r\n 'natural','outskirt','end','periph','periphery','boundar','perimeter','circumst','ends','boundary',\r\n 'interpos','around','peripheral','border','circumference','neighboring','rear side','periphera','last','external']\r\n\r\nsub_device = [\t'머신','수단','설치','설비','노드','장비','디바이스','기계','유닛','로봇','회로','방법','도구','구조','이큅먼트','인스톨리제이션',\r\n '기','시스템','인스톨래이션','모듈','단말','보조장치','기구','엘러먼트','기기']\r\neng_device = ['setup','device','instrument','part','accessory','apparatus','system','arrangement','attachment','supplementary device',\r\n 'assembly','contrivance','equipment','component','element','unit','plant','installation','auxiliary device','package','accessories',\r\n 'auxiliaries','instrum','machin','facility']\r\nsub_remocon = ['리모트컨트롤','리모트 컨트롤러','리모컨','리모트','원격제어기','원격제어기','리모트 콘트롤러','컨트롤러','콘트롤러']\r\neng_remocon = ['controler','remo','remote controller','remotecontrol','remote controler','remote','remotcontrol','remocon']\r\nsub_speaker = ['스피카','음향변환','음성','스피이카','메거폰','음향 변환기','확성기','고성기','스삐카','매가폰','라우드스피커','스피이커','사운드',\r\n '전기 음향 변환기','앰프','트랜스듀서','스피크']\r\neng_speaker = ['spica','megaphone','loud-speaker','speak','speaker','loudspeaker']\r\ntelevision = MainID(15)\r\nsurround = MainID(16)\r\ndevice = MainID(17)\r\nremcon = MainID(18)\r\nspeaker = MainID(19)\r\n\r\n\r\nspeaker.insert_sub(['스피커'])\r\nsurround.insert_sub(['주변'])\r\ndevice.insert_sub(['장치'])\r\nremcon.insert_sub(['리모콘'])\r\n","sub_path":"parvlib_test.py","file_name":"parvlib_test.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"569966456","text":"from pwn import *\nimport numpy as np\nimport scipy.cluster.hierarchy as hcluster\n\nKERNEL_BIN = \"./vmlinuz\"\nROOTFS = \"./rootfs.img\"\nKERNEL_ELF = \"./vmlinux\"\n\nelf = ELF(KERNEL_ELF)\n\ngadgets = []\n\ndef launch():\n log.info(\"Launching QEMU...\")\n cmd = ['qemu-system-x86_64', '-m', '1G', '-cpu', 'host', '--enable-kvm', '-initrd', ROOTFS, '-kernel', KERNEL_BIN, '-nographic', '-monitor', '/dev/null', '-append', '\"console=ttyS0 kaslr quiet panic=1\"']\n r = process(cmd)\n output = r.recvregex(b\"/ (\\$|#) \", timeout=10)\n prompt = output.splitlines()[-1]\n assert b'#' in prompt, \"you must be root to use this script!\"\n return r\n\ndef parse_kallsyms(r):\n log.info(\"Trying to grab and parse kallsyms...\")\n\n # grab raw kallsyms output first\n r.sendline(b\"cat /proc/kallsyms\")\n output = r.recvuntil(b\"#\")\n\n # grab kernel text entries\n entries = [x.split() for x in output.splitlines() if len(x.split()) == 3]\n text_entries = [x for x in entries if x[1].lower() == b't']\n\n # calculate function offsets\n base = [x for x in text_entries if x[2] == b'_stext'][0][0]\n base = int(base, 16)\n d = {x[2]: int(x[0], 16)-base for x in text_entries}\n\n return d\n\ndef get_fresh_offsets():\n r = launch()\n sym = parse_kallsyms(r)\n r.close()\n return sym\n\ndef get_func_size():\n log.info(\"Trying to grab function size...\")\n d = {}\n for x in elf.sections:\n if not x.name.startswith(\".text.\"):\n continue\n func_size = len(x.data())\n func_name = x.name[6:]\n d[func_name] = func_size\n return d\n\ndef get_invariant_func_offsets():\n log.info(\"Trying to identify invariant function offsets\")\n off1 = get_fresh_offsets()\n off2 = get_fresh_offsets()\n off3 = get_fresh_offsets()\n \n offsets = {x:off1[x] for x in off1 if x in off1 and x in off2 and x in off3 and off1[x] == off2[x] and off2[x] == off3[x]}\n\n # be careful, we only grab functions from .text section, not .init stuff\n offsets = {x:offsets[x] for x in offsets if offsets[x] < 0xc00000}\n\n log.success(f\"Identified {len(offsets)} invariant functions!\")\n return offsets\n\ndef virt_to_phys(offset):\n return elf.vaddr_to_offset(elf.address+offset)\n\ndef do_gadget_search(min_offset, max_offset):\n \"\"\"\n translate virtual address and file offset back and forth so that fking ROPgadget won't eat up the memory of my computer\n \"\"\"\n min_phys_off = virt_to_phys(min_offset)\n max_phys_off = virt_to_phys(max_offset)\n\n cmd = b\"ROPgadget --binary ./vmlinux --rawArch=x86 --rawMode=64 --range %#x-%#x\" % (min_phys_off, max_phys_off)\n output = subprocess.getoutput(cmd)\n\n for line in output.splitlines():\n if not line.startswith(\"0x\"):\n continue\n elem = line.split(' : ')\n phys_off = int(elem[0], 16)\n vaddr = elf.offset_to_vaddr(phys_off)\n\n gadgets.append((vaddr, elem[1]))\n\ndef clean_gadgets():\n # de-duplicate gadgets\n seen = set()\n new_gadgets = []\n for gadget in gadgets:\n if gadget[1] in seen:\n continue\n new_gadgets.append(gadget)\n seen.add(gadget[1])\n\n # sort gadgets\n new_gadgets.sort(key = lambda x: x[1])\n return new_gadgets\n\ndef show_gadgets():\n for gadget in gadgets:\n line = \"%#x : %s\" % (gadget[0], gadget[1])\n print(line)\n\nif __name__ == '__main__':\n import argparse\n\n # parse arguments\n parser = argparse.ArgumentParser(description='Scripts to find gadgets in position-invariant region in linux kernel compiled with FG-KASLR',\n usage=\"%(prog)s [options] -b -e -i \")\n parser.add_argument('-b', '--bin', type=str,\n help=\"specify path to bzImage/vmlinuz\", required=True)\n parser.add_argument('-e', '--elf', type=str,\n help=\"specify path to vmlinux\", required=True)\n parser.add_argument('-i', '--initrd', type=str,\n help=\"specify path to initramfs\", required=True)\n args = parser.parse_args()\n\n KERNEL_BIN = args.bin\n ROOTFS = args.initrd\n KERNEL_ELF = args.elf\n\n offset_dict = get_invariant_func_offsets()\n\n data = np.array(list(offset_dict.values()))\n data = data.reshape(data.shape[0], 1)\n clusters = hcluster.fclusterdata(data, 0x200, criterion=\"distance\")\n\n for cid in range(1, clusters.max()+1):\n region = data[clusters == cid]\n do_gadget_search(int(region.min()), int(region.max()))\n\n gadgets = clean_gadgets()\n show_gadgets()\n","sub_path":"linux-kernel/fgkaslr_gadgets.py","file_name":"fgkaslr_gadgets.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"128042180","text":"\"\"\"\nThis python file holds all the functions used in the projects.\nCurrently holds the function for calculating the time evolution of\na single junction and for a single time step of a junction both based\non Euler's method\n\"\"\"\nimport numpy as np\n\ndef junction(t_0, t_f, num, damp, i):\n \"\"\"\n Calculates the phase and change in phase as a function\n of time from initial time, t0, to final time, tf, in [num] steps\n with parameters i (current) and damp (damping)\n \"\"\"\n t_s = (t_f - t_0) / num\n t_span = np.arange(t_0, t_f + t_s, t_s) # time span\n\n phi = np.zeros_like(t_span)\n phi_dot = np.zeros_like(t_span)\n # Initial Conditions\n phi[0] = 0\n phi_dot[0] = 0\n\n for j in range(1, num + 1):\n phi[j] = phi[j - 1] + phi_dot[j - 1] * t_s\n phi_dot[j] = phi_dot[j - 1] + (i - np.sin(phi[j - 1]) - damp * phi_dot[j - 1]) * t_s\n return phi, phi_dot, t_span\n\ndef junction_step(p_0, pd_0, dt, damp, i):\n \"\"\"\n Calculates a single timestep of phase and change in phase given the\n current values p0 and v0, length of time ts, and parameters i\n (current) and damp (damping) with Newton's method\n \"\"\"\n phi = p_0 + pd_0 * dt\n phi_dot = pd_0 + (i - np.sin(p_0) - damp * pd_0) * dt\n\n return phi, phi_dot\n\ndef currents(lmda,phi_p,phi_c,lmda_s,i,lmda_p,i_b,eta):\n \"\"\"\n Calculate the pulse and control current inside a junction\n \"\"\"\n i_p = -lmda*(phi_c + phi_p) + lmda_s*i + (1-lmda_p)*i_b\n i_c = (-lmda*(phi_c + phi_p) + lmda_s*i - lmda_p*i_b)/eta\n \n return i_p, i_c\n\ndef change_weights(A,B,tau,t1,t0):\n \"\"\"\n Implements basic Hebbian learning to changing weights with\n positive learning rate A, negative rate B, timescale tau,\n output fire time t1, and input firetime t0\n \"\"\"\n x = t1 - t0\n if x > 0:\n dw = A*np.exp(-x/tau)\n else:\n dw = -B*np.exp(x/tau)\n return dw\n \n\ndef synapse_step(v_0, vd_0, i_0, id_0, v1p, v2p, v2c, gamma, omega, Q, lmda, lmda_syn, r12, dt):\n \"\"\"\n Calculates a single timestep of output voltage and current given the\n outputs of the previous neuron\n \n \"\"\"\n v = v_0 + vd_0 * dt\n v_dot = vd_0 + omega ** 2 * (v1p - Q*omega*lmda_syn/lmda * i_0\n - lmda_syn/lmda * id_0 - v_0 - Q/omega * vd_0)*dt\n \n i = i_0 + id_0 * dt\n i_dot = (v_0 - lmda_syn*(v2c + v2p) - r12/gamma*i_0) * lmda/(lmda_syn*(1-lmda_syn))\n \n return v, v_dot, i, i_dot\n","sub_path":"Nueron Model/jj.py","file_name":"jj.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"138525752","text":"\"\"\"\nAuthor: Nooruddin Imad\n\"\"\"\n\nfrom numpy import random\nfrom copy import deepcopy\nfrom itertools import combinations\n\nclass CardDeck(object):\n \"\"\"\n A class for the deck of cards.\n \n Attributes\n ----------\n _card_names : list\n Contains the unique card names.\n _card_numbers : list\n Contains the number of cards for each type.\n _cards : list\n Contains the names of all 98 cards.\n ----------\n\n \"\"\"\n def __init__(self):\n self._card_names = ['Tempura', 'Sashimi', 'Dumpling', 'DoubleMaki', 'TripleMaki', 'SingleMaki', 'SalmonNigiri', 'SquidNigiri', 'EggNigiri', 'Wasabi', 'Chopsticks']\n self._card_numbers = [14, 14, 14, 12, 8, 6, 10, 5, 5, 6, 4]\n self._cards = [self._card_names[i] for i in range(len(self._card_names)) for j in range(self._card_numbers[i])]\n\n def dealCards(self, n):\n \"\"\"\n Deals cards randomly to players' hands.\n\n Parameters\n ----------\n n : int\n Number of cards required.\n ----------\n\n Return\n ------\n list1, list2 : list, list\n Returns 2 lists containing n number of cards.\n ------\n \"\"\"\n random.shuffle(self._cards)\n return self._cards[0:n], self._cards[n:2*n] \n\nclass GameState(object):\n \"\"\"\n Attributes\n ----------\n _p1_hand : list\n\n _p2_hand : list\n\n _p1_table : list\n\n _p2_table : list\n\n _p1_total_score : int\n\n _p2_total_score : int\n\n ----------\n\n \"\"\"\n def __init__(self):\n cardDeck = CardDeck()\n self._p1_hand, self._p2_hand = cardDeck.dealCards(6)\n self._p1_table, self._p2_table = [], []\n self._p1_total_score, self._p2_total_score = 0, 0\n\n def getTotalScores(self):\n \"\"\"\n Getter function for the players' scores.\n\n Return\n ------\n (_p1_total_score, _p2_total_score) : tuple\n The tuple contating the score of the two players. \n ------\n \"\"\"\n return self._p1_total_score, self._p2_total_score\n\n\n def getWinningStatement(self, winstr):\n \"\"\"\n Returns a random quirky winning sentence.\n\n Parameters\n ----------\n winstr : str\n String containing the name of the winning player.\n ----------\n\n Return\n ------\n winning statement : str\n The quirky winning statement.\n ------\n\n \"\"\"\n statements = [\" is deemed worthy of the champion cup.\", \" jumps to the sky joyfully.\", \" is pronounced as the winner.\", \" wins and the crowd goes bonkers.\", \" is the chosen one.\", \" gets chicken dinner.\", \" W I N N E R \"]\n random.shuffle(statements)\n return winstr + statements[random.randint(0, len(statements))]\n\n def getVanillaWinningStatement(self, winstr):\n \"\"\"\n Returns a simple win statement.\n\n Parameters\n ----------\n winstr : str\n String containing the winner's name\n ----------\n\n Return\n ------\n winning statement : str\n The winning statement.\n ------\n\n \"\"\"\n return winstr + \"wins this round.\"\n\n def getTables(self):\n \"\"\"\n Getter function for players tables.\n \n Return\n ------\n (_p1_table, _p2_table) : tuple\n Tuple containing the two tables of the players.\n ------\n\n \"\"\"\n return self._p1_table, self._p2_table\n \n def getHands(self):\n \"\"\"\n Getter function for players hands.\n\n Return\n ------\n (_p1_hand, _p2_hand) : tuple\n Tuple containing the two hands of the players.\n ------\n\n \"\"\"\n return self._p1_hand, self._p2_hand\n\n def _swap(self):\n \"\"\"\n Swaps the players hands.\n\n Return\n ------\n (_p1_hand, _p2_hand) : tuple\n Returns the swapped hands. Notice that no assignment is necessary as swapping is done in-place.\n \"\"\"\n self._p1_hand, self._p2_hand = self._p2_hand, self._p1_hand\n return self._p1_hand, self._p2_hand\n\n def play(self, p1_move, p2_move):\n \"\"\"\n Plays the two moves the players played.\n\n Parameters\n ----------\n p1_move : str\n The card selected by player 1.\n p2_move : str\n The card selected by player 2.\n ----------\n\n Local Variables\n ---------------\n p1_valid : bool -> default(False)\n Flag for a valid player 1 move. Set after checking is done to verify a valid p1 move.\n p2_valid : bool -> default(False)\n Flag for a valid player 2 move. Set after checking is done to verify a valid p2 move.\n p1_spoon : bool -> default(False)\n Flag for a valid player 1 spoon swap. Set after checking is done to verify a valid p1 spoon swap.\n p2_spoon : bool -> default(False)\n Flag for a valid player 2 spoon swap. Set after checking is done to verify a valid p2 spoon swap.\n card : str\n Temporary variables for holding played card in current move.\n ---------------\n \"\"\"\n p1_valid, p2_valid = False, False\n p1_spoon, p2_spoon = False, False\n\n #check if the the move of p1 is valid\n #There can be two moves -> 0 means normal put in table, 1 means spoon swap\n if p1_move[0] == 0 and p1_move[1] in self._p1_hand:\n p1_valid = True\n elif p1_move[0] == 1 and 'Chopsticks' in self._p1_table and p1_move[1][0] in self._p1_hand and p1_move[1][1] in self._p1_hand:\n p1_valid, p1_spoon = True, True\n\n #check the validity of p2_move\n if p2_move[0] == 0 and p2_move[1] in self._p2_hand:\n p2_valid = True\n elif p2_move[0] == 1 and 'Chopsticks' in self._p2_table and p2_move[1][0] in self._p2_hand and p2_move[1][1] in self._p2_hand:\n p2_valid, p2_spoon = True, True\n\n if p1_valid and p2_valid:\n if p1_spoon:\n\n #perform a chopstick swap\n #remove chopstick from p1 table\n self._removeFromP1Table('Chopsticks')\n\n #add chopstick to p1 hand\n self._addToP1Hand('Chopsticks')\n\n #remove the two cards from p1 hand\n card1 = p1_move[1][0]\n card2 = p1_move[1][1]\n\n self._removeFromP1Hand(card1)\n self._removeFromP1Hand(card2)\n\n #add two cards into p1 table\n self._addToP1Table(card1)\n self._addToP1Table(card2)\n\n else:\n #normal card play\n #remove card from p1 hand\n card1 = p1_move[1]\n\n self._removeFromP1Hand(card1)\n\n #add card to p1 table\n self._addToP1Table(card1)\n \n if p2_spoon:\n self._removeFromP2Table('Chopsticks')\n\n self._addToP2Hand('Chopsticks')\n\n card1 = p2_move[1][0]\n card2 = p2_move[1][1]\n\n self._removeFromP2Hand(card1)\n self._removeFromP2Hand(card2)\n\n self._addToP2Table(card1)\n self._addToP2Table(card2)\n \n else:\n card1 = p2_move[1]\n\n self._removeFromP2Hand(card1)\n self._addToP2Table(card1)\n\n #perform swap to swap the hands\n self._swap()\n\n else:\n print(\"[ ERROR : play() -> invalid play. ]\")\n\n def printP1Hand(self):\n \"\"\"\n Prints player 1 hand.\n \"\"\"\n print(\"P1 Hand: \", end=\"\")\n print(self._p1_hand)\n\n def printP2Hand(self):\n \"\"\"\n Prints player 2 hand\n \"\"\"\n print(\"P2 Hand: \", end=\"\")\n print(self._p2_hand)\n\n def printHands(self):\n \"\"\"\n Prints 2 players hands.\n \"\"\"\n self.printP1Hand()\n self.printP2Hand()\n \n def printP1Table(self):\n \"\"\"\n Prints player 1's table.\n \"\"\"\n print(\"P1 Table: \", end=\"\")\n print(self._p1_table)\n\n def printP2Table(self):\n \"\"\"\n Prints player 2's table.\n \"\"\"\n print(\"P2 Table: \", end=\"\")\n print(self._p2_table)\n\n def printTable(self):\n \"\"\"\n Prints 2 players tables.\n \"\"\"\n print(\"P1 Table: \", end=\"\")\n print(self._p1_table)\n print(\"P2 Table: \", end=\"\")\n print(self._p2_table)\n\n def _addToP1Table(self, card):\n \"\"\"\n Adds card to player 1's table.\n\n Parameters\n ----------\n card : str\n The card to be added to the player 1's table.\n ----------\n \"\"\"\n if self._p1_table.count('Wasabi') > 0 and 'Nigiri' in card:\n self._p1_table.remove('Wasabi')\n self._p1_table.append(card + 'Wasabi')\n else:\n self._p1_table.append(card)\n\n def _addToP2Table(self, card):\n \"\"\"\n Adds card to player 2's table.\n\n Parameters\n ----------\n card : str\n The card to be added to the player 2's table.\n ----------\n \"\"\"\n if self._p2_table.count('Wasabi') > 0 and 'Nigiri' in card:\n self._p2_table.remove('Wasabi')\n self._p2_table.append(card + 'Wasabi')\n else:\n self._p2_table.append(card)\n\n def _addToP1Hand(self, card):\n \"\"\"\n Adds card to player 1's hand.\n\n Parameters\n ----------\n card : str\n The card to be added to the player 1's hand.\n ---------- \n \"\"\"\n self._p1_hand.append(card)\n\n def _addToP2Hand(self, card):\n \"\"\"\n Adds card to player 2's hand.\n\n Parameters\n ----------\n card : str\n The card to be added to the player 2's hand.\n ----------\n \"\"\"\n self._p2_hand.append(card)\n \n def _removeFromP1Hand(self, card):\n \"\"\"\n Removes card from player 1's hand.\n\n Parameters\n ----------\n card : str\n The card to be removed from player 1's hand.\n ----------\n \"\"\"\n self._p1_hand.remove(card)\n \n def _removeFromP2Hand(self, card):\n \"\"\"\n Removes card from player 2's hand.\n\n Parameters\n ----------\n card : str\n The card to be removed from player 2's hand.\n ----------\n \"\"\"\n self._p2_hand.remove(card)\n\n def _removeFromP1Table(self, card):\n \"\"\"\n Removes card from player 1's table.\n\n Parameters\n ----------\n card : str\n The card to be removed from player 1's table.\n ----------\n \"\"\"\n self._p1_table.remove(card)\n \n def _removeFromP2Table(self, card):\n \"\"\"\n Removes card from player 2's table.\n\n Parameters\n ----------\n card : str\n The card to be removed from player 2's table.\n ----------\n \"\"\"\n self._p2_table.remove(card)\n\n def _evalScores(self):\n \"\"\"\n Calculates the scores of both players based on their tables.\n \"\"\"\n p1_total, p1_maki = 0, 0\n p2_total, p2_maki = 0, 0\n p1_table, p2_table = self._p1_table, self._p2_table\n\n p1_total += 5 * (p1_table.count('Tempura') / 2)\n p1_total += 10 * (p1_table.count('Sashimi') / 3)\n p1_total += (p1_table.count('Dumpling') * (p1_table.count('Dumpling') + 1)) / 2\n p1_maki += p1_table.count('SingleMaki') + 2 * p1_table.count('DoubleMaki') + 3 * p1_table.count('TripleMaki')\n p1_total += p1_table.count('EggNigiri')\n p1_total += 2 * p1_table.count('SalmonNigiri')\n p1_total += 3 * p1_table.count('SquidNigiri')\n p1_total += 3 * p1_table.count('EggNigiriWasabi')\n p1_total += 6 * p1_table.count('SalmonNigiriWasabi')\n p1_total += 9 * p1_table.count('SquidNigiriWasabi')\n \n\n p2_total += 5 * (p2_table.count('Tempura') / 2)\n p2_total += 10 * (p2_table.count('Sashimi') / 3)\n p2_total += (p2_table.count('Dumpling') * (p2_table.count('Dumpling') + 1)) / 2\n p2_maki += p2_table.count('SingleMaki') + 2 * p2_table.count('DoubleMaki') + 3 * p2_table.count('TripleMaki')\n p2_total += p2_table.count('EggNigiri')\n p2_total += 2 * p2_table.count('SalmonNigiri')\n p2_total += 3 * p2_table.count('SquidNigiri')\n p2_total += 3 * p2_table.count('EggNigiriWasabi')\n p2_total += 6 * p2_table.count('SalmonNigiriWasabi')\n p2_total += 9 * p2_table.count('SquidNigiriWasabi')\n\n \"\"\"\n if p1_maki > p2_maki:\n p1_total += 6\n p2_total += 3\n elif p1_maki < p2_maki:\n p1_total += 3\n p2_total += 6\n else:\n p1_total += 3\n p2_total += 3\n \"\"\"\n maki_diff = 0\n\n if p1_maki > p2_maki:\n maki_diff = 6\n if p2_maki > 0:\n maki_diff = 3\n if p2_maki > p1_maki:\n maki_diff = -6\n if p1_maki > 0:\n maki_diff = -3\n\n self._p1_total_score = p1_total + maki_diff\n self._p2_total_score = p2_total\n\n #return p1_total if p1_total > p2_total else p2_total\n return p1_total - p2_total + maki_diff\n\n def finished(self):\n return len(self._p1_hand) == 0 and len(self._p2_hand) == 0\n\n\ndef findP2BestMove(G, alpha, beta):\n \"\"\"\n Finds the best move for player 2(computer).\n\n Parameters\n ----------\n G : GameState obj\n The current GameState object.\n alpha : int\n The value of alpha for minmax with alpha-beta pruning.\n beta : int\n The value of beta for minmax with alpha-beta pruning.\n ----------\n \n \"\"\"\n p1_hand, p2_hand = G.getHands()\n p1_table, p2_table = G.getTables()\n\n #If there is only one card to play, play it.\n if len(p2_hand) == 1:\n #get a copy of the gamestate\n H = deepcopy(G)\n #play the only remaining card\n H.play([0,p1_hand[0]],[0,p2_hand[0]])\n return [0,p2_hand[0]], H._evalScores()\n\n #Collect all possible moves for p1. Moves are cards in hand or chopstick swaps.\n p1_moves = [[0,c] for c in set(p1_hand)]\n if 'Chopsticks' in p1_table:\n p1_swaps_set = set(combinations(p1_hand,2))\n p1_swaps = [[1,list(s)] for s in p1_swaps_set]\n\n #Allow chopstick swaps for wasabi and nigiri in either order, so that\n #wasabi can either be applied immediately or saved for later.\n wasabi_swap_reorders = []\n for s in p1_swaps:\n if 'Wasabi' in s[1] and ('Nigiri' in s[1][0] or 'Nigiri' in s[1][1]):\n wasabi_swap_reorders.append([1,[s[1][1],s[1][0]]])\n\n p1_swaps += wasabi_swap_reorders\n p1_moves += p1_swaps\n\n #Collect all possible moves for p2. Moves are cards in hand or chopstick swaps.\n p2_moves = [[0,c] for c in set(p2_hand)]\n if 'Chopsticks' in p2_table:\n p2_swaps_set = set(combinations(p2_hand,2))\n p2_swaps = [[1,list(s)] for s in p2_swaps_set]\n\n #Allow chopstick swaps for wasabi and nigiri in either order, so that\n #wasabi can either be applied immediately or saved for later.\n wasabi_swap_reorders = []\n for s in p2_swaps:\n if 'Wasabi' in s[1] and ('Nigiri' in s[1][0] or 'Nigiri' in s[1][1]):\n wasabi_swap_reorders.append([1,[s[1][1],s[1][0]]])\n\n p2_swaps += wasabi_swap_reorders\n p2_moves += p2_swaps\n\n #Minimax it up with alpha-beta pruning, p2 is the minimizing player.\n ev_p2 = 1000\n for p2_move in p2_moves:\n ev_p1 = -1000\n\n for p1_move in p1_moves:\n H = deepcopy(G)\n H.play(p1_move, p2_move)\n\n #Hold onto the best outcome for p1 from this node, pass the best outcomes\n #seen so far for each player down the call stack.\n ev_p1 = max(ev_p1, findP2BestMove(H, ev_p1, ev_p2)[1])\n\n #If we already know p2 can force a better outcome from an earlier move than\n #p1 can force from this one, no need to explore any more children of this node.\n if beta < ev_p1:\n break\n\n #Hold onto the best outcome and best move for p2 from this node. The value\n #of a p2 move is the value of the p1 move that would follow it when p1 plays\n #using minimax, i.e. ev_p1.\n if ev_p1 < ev_p2:\n p2_best_move = p2_move\n ev_p2 = min(ev_p1, ev_p2)\n\n #If we already know p1 can force a better outcome from an earlier move than\n #p2 can force from this one, no need to explore any more children of this node.\n if alpha > ev_p2:\n break\n\n return p2_best_move, ev_p2\n\n \n\n\n \n\n\n\n \n","sub_path":"sushigo_modules.py","file_name":"sushigo_modules.py","file_ext":"py","file_size_in_byte":17752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"11021388","text":"print(\"Directions\")\nprint(\"\\tGiven at most 15 UniProt Protein Database access IDs.\")\nprint(\"\\tReturn for each protein possessing the N-glycosylation motif, output its given access ID followed by a list of locations in the protein string where the motif can be found.\")\nprint(\"Previous problems(s): PROT, SUBS\\n\")\n\nimport uniprot\nimport urllib\nimport re\n\nfor line in open(\"../files/rosalind_mprt.txt\"):\n\tfasta_id = line.strip()\n\n\tprotein_url=\"http://www.uniprot.org/uniprot/%s.fasta\" % fasta_id\n\tf=urllib.urlopen(protein_url)\n\tprotein_fasta=f.read()\n\tprotein_fasta=protein_fasta.split(\"\\n\")\n\tprotein_seq=\"\".join(protein_fasta[1:])\n\tmatches = [match.start()+1 for match in re.finditer(r\"(?=(N[^P][ST][^P]))\", protein_seq)]\n\tif (len(matches) > 0):\n\t\tprint(fasta_id)\n\t\tprint(\" \".join(map(str, matches)))\n","sub_path":"scripts/mprt.py","file_name":"mprt.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"633532169","text":"#!/usr/bin/python3\nimport CAN\nimport CANopen\nimport CCSDS\nfrom datetime import datetime\nimport errno\nfrom math import modf\nfrom select import select\nimport signal\nimport socket\nfrom struct import pack\nimport sys\nfrom time import time, mktime, sleep\n\nCAN_LISTEN_INTERFACES = [\"vcan0\", \"vcan1\"] # Must be a list\nCAN_SEND_INTERFACE = \"vcan0\"\nUDP_LOCAL_IP = \"localhost\"\nUDP_LOCAL_READ_PORT = 5084\nUDP_LOCAL_WRITE_PORT = 5082\nUDP_REMOTE_IP = \"10.10.5.29\" # Must be on same network as UDP_LISTEN_IP or OSError is thrown\nUDP_REMOTE_WRITE_PORT = 5083\nUDP_MAX_PACKET_SIZE = 1024 # Absolute maximum of 65535\n\nCCSDS_APP_ID = 0x3E\n\ndef sigterm_handler(signum, frame):\n sys.exit()\n\nsignal.signal(signal.SIGTERM, sigterm_handler)\n\nsockets = []\nfor interface in CAN_LISTEN_INTERFACES:\n can_socket = CAN.Bus(interface)\n sockets.append(can_socket)\nfor s in sockets:\n if s.getsockname()[0] == CAN_SEND_INTERFACE:\n can_socket = s\n break\n\nudp_write_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n#udp_write_socket.bind((UDP_LOCAL_IP, UDP_LOCAL_WRITE_PORT))\n\nudp_read_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nudp_read_socket.bind((UDP_LOCAL_IP, UDP_LOCAL_READ_PORT))\nsockets.append(udp_read_socket)\n#buffer = bytearray(15 * 8)\nbuffer = bytearray(1)\n\nwhile True:\n try:\n rlist, _, _ = select(sockets, [], [])\n for s in rlist:\n socket_type = s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)\n if isinstance(s, CAN.Bus):\n msg = s.recv()\n fc = (msg.arbitration_id >> CANopen.FUNCTION_CODE_BITNUM) & 0xF\n if fc == CANopen.FUNCTION_CODE_TPDO1:\n node_id = msg.arbitration_id & 0x3F\n #buffer[((node_id - 1) * 8):(((node_id - 1) * 8) + 7)] = bytes(msg.data).ljust(8, b'\\x00')\n buffer[0] = buffer[0] + 1\n elif fc == CANopen.FUNCTION_CODE_SYNC:\n (subseconds, seconds) = modf(time() - mktime((1980, 1, 1, 0, 0, 0, 1, 1, 0))) # Could use (int(diff/1),diff%1) instead of modf\n seconds += 5 * 3600 # Offset for Central Time\n ts = pack(\">IH\", int(seconds), int(subseconds * (2 ** 16)))\n packet = CCSDS.SpacePacket(CCSDS.SpacePacket.TYPE_TELEMETRY, CCSDS_APP_ID, bytes(buffer), sequence_flags=0x3, secondary_header=ts)\n packet = bytearray(bytes(packet))\n udp_write_socket.sendto(bytes(packet), (UDP_REMOTE_IP, UDP_REMOTE_WRITE_PORT))\n print(\"Sent CCSDS Space Packet with \" + str(int(buffer[0])) + \" operational modules\")\n #buffer = bytearray(15 * 8)\n buffer = bytearray(1)\n elif socket_type == socket.SOCK_DGRAM:\n data = s.recv(UDP_MAX_PACKET_SIZE)\n packet = CCSDS.SpacePacket.from_bytes(data)\n if packet.type == CCSDS.SpacePacket.TYPE_COMMAND and packet.app_id == CCSDS_APP_ID:\n can_socket.send(packet.data) # Need to parse and strip off secondary header\n except CAN.BusDown:\n sleep(1)\n","sub_path":"can-ccsds-spp-udp.py","file_name":"can-ccsds-spp-udp.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"361990357","text":"# methods for processing an OSM network obtained with functions from the load package\n# Imputes roadparameters from osm highway types. OSM does not always have information about\n# speeds and lane capacities. Code is modified from\n# https://github.com/ual/create-network-bpr/blob/master/edges-add-speed-capacity.ipynb\n\n\nfrom shapely.geometry import LineString\nimport pandas as pd\nimport numpy as np\nfrom igraph import OUT\nimport osmnx as ox\nimport statistics\nimport ast\n\n\nspeed_defaults = {'residential': {1: 20, 2: 20, 3: 20, 4: 20, -1: 20},\n 'living_street': {1: 20, 2: 20, 3: 20, 4: 20, -1: 20},\n 'tertiary': {1: 20, 2: 20, 3: 20, 4: 20, -1: 20},\n 'tertiary_link': {1: 20, 2: 20, 3: 20, 4: 20, -1: 20},\n 'secondary': {1: 25, 2: 25, 3: 25, 4: 25, -1: 25},\n 'secondary_link': {1: 25, 2: 25, 3: 25, 4: 25, -1: 25},\n 'primary': {1: 30, 2: 30, 3: 30, 4: 30, -1: 30},\n 'primary_link': {1: 30, 2: 30, 3: 30, 4: 30, -1: 30},\n 'trunk': {1: 45, 2: 45, 3: 45, 4: 45, -1: 45},\n 'trunk_link': {1: 45, 2: 45, 3: 45, 4: 45, -1: 45},\n 'motorway': {1: 50, 2: 50, 3: 65, 4: 65, -1: 57.5},\n 'motorway_link': {1: 50, 2: 50, 3: 65, 4: 65, -1: 57.5},\n 'unclassified': {1: 20, 2: 20, 3: 20, 4: 20, -1: 20},\n 'road': {1: 30, 2: 30, 3: 30, 4: 30, -1: 30}}\n\n# define per-lane capacity defaults for each hwy type and number of lanes, so we can infer when lacking data\ncapacity_defaults = {'residential': {1: 500, 2: 500, 3: 500, 4: 500, -1: 500},\n 'living_street': {1: 500, 2: 500, 3: 500, 4: 500, -1: 500},\n 'tertiary': {1: 900, 2: 900, 3: 900, 4: 900, -1: 900},\n 'tertiary_link': {1: 900, 2: 900, 3: 900, 4: 900, -1: 900},\n 'secondary': {1: 900, 2: 900, 3: 900, 4: 900, -1: 900},\n 'secondary_link': {1: 900, 2: 900, 3: 900, 4: 900, -1: 900},\n 'primary': {1: 1000, 2: 1000, 3: 1000, 4: 1000, -1: 1000},\n 'primary_link': {1: 1000, 2: 1000, 3: 1000, 4: 1000, -1: 1000},\n 'trunk': {1: 1900, 2: 2000, 3: 2000, 4: 2000, -1: 1975},\n 'trunk_link': {1: 1900, 2: 2000, 3: 2000, 4: 2000, -1: 1975},\n 'motorway': {1: 1900, 2: 2000, 3: 2000, 4: 2200, -1: 2025},\n 'motorway_link': {1: 1900, 2: 2000, 3: 2000, 4: 2200, -1: 2025},\n 'unclassified': {1: 800, 2: 800, 3: 800, 4: 800, -1: 800},\n 'road': {1: 900, 2: 900, 3: 900, 4: 900, -1: 900}}\n\n\n# note: -1 is the key for the null value\n# note: highway_links are given the same values as their highway types\n# note: 'road' is effectively an OSM null highway type\n# note: 'unclassified' is a highway type one step below tertiary in the OSM hierarchy\n\n\n# convert string representations of lists to lists# conve\ndef _convert_lists(value):\n if isinstance(value, str) and value.startswith('[') and value.endswith(']'):\n return ast.literal_eval(value) # parse str -> list\n else:\n return value\n\n\n# collapse multiple highway type values into a single value# colla\ndef _collapse_multiple_hwy_values(hwy):\n if isinstance(hwy, list):\n # if we find an item in our defaults dict, use that value\n # otherwise, just use the zeroth item in the list\n for item in hwy:\n if item in speed_defaults.keys():\n return item\n return hwy[0]\n else:\n return hwy\n\n\n# collapse multiple lane values into a single value# colla\ndef _collapse_multiple_lane_values(value):\n if isinstance(value, list):\n # return the mean of the values in the list\n numeric_values = [int(x) for x in value]\n return int(statistics.mean(numeric_values))\n else:\n return value\n\n\n# if this is a two-way street, there will be two edges, one uv and one vu\n# give each half the lanes\n# probably not right... review https://wiki.openstreetmap.org/wiki/Key:lanes#Assumptions\ndef _allocate_lanes(row):\n if row['oneway']:\n return row['lanes']\n else:\n return int(row['lanes'] / 2)\n\n\n# collapse multiple maxspeed values into a single value\ndef _collapse_multiple_maxspeed_values(value):\n if isinstance(value, list):\n try:\n # strip non-numeric \" mph\" from each value in the list then take the mean\n values = [int(x.replace(' mph', '')) for x in value]\n return statistics.mean(values)\n except:\n # if exception, return null (a few have multiple values like \"35 mph;40 mph\")\n return None\n else:\n return value\n\n\n# infer speed from defaults based on highway type classifier and number of lanes\ndef _infer_speed(row):\n hwy = row['highway']\n lanes = row['lanes_capped']\n return speed_defaults[hwy][lanes]\n\n\ndef _parse_speed_strings(value):\n if isinstance(value, str):\n # for all string maxspeed values, strip non-numeric \" mph\" from each value\n value = value.replace(' mph', '')\n # sometimes multiple speeds are semicolon-delimited -- collapse to a single value\n if ';' in value:\n # return the mean of the values if it has that semicolon\n values = [int(x) for x in value.split(';')]\n return statistics.mean(values)\n else:\n return int(value)\n else:\n return value\n\n\n# infer capacity per lane per hour from defaults based on highway type classifier and number of lanes\ndef _infer_capacity(row):\n hwy = row['highway']\n lanes = row['lanes_capped']\n return capacity_defaults[hwy][lanes]\n\n\ndef _nearest_neighbor(points, coord, nodes, latlon=True):\n # Finds the nearest point from the set of `points` to a coordinate.\n # This is used to connect origin and destination points to the road network.\n # private to this file\n if latlon:\n distances = haversine(coord, points)\n else:\n distances = np.sqrt((coord['Latitude']-points['Latitude'])**2 + (coord['Longitude']-points['Longitude'])**2)\n location = np.where(distances==np.min(distances))[0][0]\n return np.min(distances), nodes.iloc[location].osmid\n\n\ndef _draw_edges(u, v, length, nodes, buildings):\n # Creates edge links between sets `u` and `v`.\n # This is used to connect origin and destination points to the road network.\n # private to this file\n new_edges = pd.DataFrame([], columns=['u', 'v'])\n new_edges['u'] = u\n new_edges['v'] = v\n new_edges['osmid'] = new_edges[['u', 'v']].apply(lambda x: ''.join([str(i) for i in x]), axis=1)\n new_edges['length'] = length\n new_edges['geometry'] = buildings.apply(lambda x:\n LineString([x.geometry.centroid, nodes[nodes.osmid==x.nearest_id].geometry.values[0]]),\n axis=1)\n new_edges['oneway'] = True\n new_edges[\"speed\"] = 30\n new_edges[\"capacity_lane_hour\"] = 900\n new_edges['lanes'] = 1\n return new_edges\n\n\ndef merge_od_streets(origins, destinations, streets, filepath=None, latlon=False):\n # Combines `origin` and `destination` nodes to road network.\n # This is used to connect origin and destination points to the road network.\n nodes, edges = ox.save_load.graph_to_gdfs(streets)\n n = []\n for i, buildings in enumerate([origins, destinations]):\n buildings['Longitude'], buildings['Latitude'] = zip(*buildings.geometry.centroid.apply(lambda x: (x.x, x.y)))\n nodes['Longitude'], nodes['Latitude'] = nodes['x'].astype(float), nodes['y'].astype(float)\n buildings['nearest_length'], buildings['nearest_id'] = zip(*buildings[['Latitude', 'Longitude']].apply(\n lambda x: _nearest_neighbor(nodes[['Latitude', 'Longitude']], x, nodes, latlon=latlon), axis=1\n ))\n node_cols = ['highway', 'osmid', 'x', 'y', 'geometry']\n n.append(buildings[node_cols])\n\n ## need the ids as integers since NetworkX tracks nodes by integers\n if i==0:\n edges = edges.append(_draw_edges(buildings['osmid'].astype(int), buildings['nearest_id'].astype(int), buildings['nearest_length'], nodes, buildings))\n else:\n edges = edges.append(_draw_edges(buildings['nearest_id'].astype(int), buildings['osmid'].astype(int), buildings['nearest_length'], nodes, buildings))\n nodes2 = pd.concat([nodes, *n])\n nodes2.gdf_name = nodes.gdf_name\n edges.reset_index(drop=True)\n edges['id'] = range(edges.shape[0])\n edges = edges.set_index(edges.id.values)\n\n mdf = ox.save_load.gdfs_to_graph(nodes2, edges)\n ox.save_graphml(mdf, filepath)\n return mdf\n\n\ndef generate_paths(graph, ods, paths_per_od):\n # Generates `paths_per_od` shortest paths between each OD pair.\n # Used with static ta-solver/non-split ratio networks.\n graph.vs[\"Coordinates\"] = list(zip(graph.vs['x'], graph.vs['y']))\n\n # Generate the paths between the od pairs\n all_paths = {}\n for o in ods:\n #Find all paths between origin and destination that have at most max_length edges\n #start_time1 = timeit.default_timer()\n # Each iteration the weight of the shortest path is multiplied by power to allow to\n # find a new shortest path\n # Add edge weights to graph, we start will all edges with weight 1\n # graph.es[\"weight\"] = np.ones(graph.ecount())\n graph.es['weight'] = list(map(float, graph.es['length']))\n\n factor = 10\n paths = []\n for i in range(paths_per_od):\n path = graph.get_shortest_paths(o[0], o[1], weights=\"weight\", mode=OUT, output=\"epath\")\n if path[0] not in paths:\n paths.append(path[0])\n\n #change weight of edges in path in order to find new shortest path\n size_of_path = len(path[0])\n new_weights = np.multiply(factor**(i+1),np.ones(size_of_path))\n graph.es[path[0]][\"weight\"] = np.multiply(factor**(i+1), graph.es[path[0]][\"weight\"])\n #elapsed1 = timeit.default_timer() - start_time1\n\n #If we could not get paths_per_od paths between the od, double the max_length value\n #if len(paths) < paths_per_od:\n #paths = find_all_paths_len(graph,o[0],o[1],maxlen=max_length*2)\n\n #Sort paths by length so that the shortest are first\n #paths.sort(key=len)\n # print(\"Finding paths for od \", o[0], \" and dest \", o[1])\n #new_paths = translate_paths(graph, paths[0:paths_per_od])\n if len(paths) > 0:\n all_paths[o] = {\"paths\": paths, \"demand\": ods[o]}\n\n return all_paths\n\n\ndef add_speed_capacity(streets):\n nodes, edges = ox.graph_to_gdfs(streets)\n edges['highway'] = edges['highway'].map(_collapse_multiple_hwy_values)\n edges['highway'].fillna(value=\"unclassified\", inplace=True)\n edges['highway'].value_counts(dropna=False).sort_index()\n edges['lanes'] = edges['lanes'].map(_convert_lists)\n edges['lanes'] = edges['lanes'].map(lambda x: int(x) if type(x) == str else x) ## assure integer values\n\n edges['lanes'] = edges['lanes'].map(_collapse_multiple_lane_values)\n edges['lanes'].value_counts().sort_index()\n\n # calculate \"typical\" number of lanes per hwy type\n edges['lanes'] = edges['lanes'].astype(float)\n lane_defaults = edges.groupby('highway')['lanes'].median()\n lane_defaults = lane_defaults.fillna(value=2).to_dict() # 'road' type is null\n\n # impute number of lanes when data is missing# impute\n def impute_lanes(row):\n if pd.notnull(row['lanes']):\n return row['lanes']\n else:\n return lane_defaults[row['highway']]\n\n edges['lanes'] = edges.apply(impute_lanes, axis=1).astype(int)\n edges['lanes'] = edges.apply(_allocate_lanes, axis=1)\n\n # make 1 lanes the min (in case some edge says zero lanes)# make 1\n edges.loc[edges['lanes'] < 1, 'lanes'] = 1\n # make 4 lanes the capped value (for 4+ lanes dict lookup), but retain true lanes value in lanes column# make 4\n edges['lanes_capped'] = edges['lanes']\n edges.loc[edges['lanes_capped'] > 4, 'lanes_capped'] = 4\n edges['lanes_capped'].value_counts().sort_index()\n\n # convert string representation of multiple maxspeed values to a list# conver\n edges['maxspeed'] = edges['maxspeed'].map(_convert_lists)\n\n edges['maxspeed'] = edges['maxspeed'].map(_collapse_multiple_maxspeed_values)\n\n edges['maxspeed'] = edges['maxspeed'].map(_parse_speed_strings)\n edges['maxspeed'].value_counts(dropna=False).sort_index()\n\n # extract maxspeed from OSM data when it already exists\n known_speeds = edges[pd.notnull(edges['maxspeed'])]['maxspeed']\n known_speeds = known_speeds.astype(int)\n\n # infer speed on all other edges that lack maxspeed data# infer\n inferred_speeds = edges[pd.isnull(edges['maxspeed'])].apply(_infer_speed, axis=1)\n\n # merge known speeds with inferred speeds to get a free-flow speed for each edge\n edges['speed'] = known_speeds.append(inferred_speeds, ignore_index=False, verify_integrity=True)\n\n # infer per-lane capacity for each edge using capacity defaults# infer\n edges['capacity_lane_hour'] = edges.apply(_infer_capacity, axis=1)\n edges['jam_density'] = 5 * edges['capacity_lane_hour'] / edges['speed']\n return ox.gdfs_to_graph(nodes, edges)","sub_path":"osm2otm/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":13464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"620242530","text":"\"\"\"Entry points for the console scripts.\"\"\"\n\nimport os\nimport sys\nfrom threading import Timer\nimport webbrowser\n\nfrom . import __version__, app\nfrom .processing import find_files\n\n\ndef main(args=None):\n if args is None:\n args = sys.argv[1:]\n\n if len(args) < 1:\n print('usage: regression [run] [config] [path] [files] [version]')\n\n for command in args:\n if command in ['run', '-r', '--run']:\n Timer(1, webbrowser.open_new('http://localhost:8080/')).start()\n app.run(host='0.0.0.0', port=8080, debug=False)\n if command in ['config', '-c', '--config']:\n config_file = os.path.join(os.path.dirname(__file__), 'config.cfg')\n webbrowser.open(config_file)\n if command in ['path', '-p', '--path']:\n print(os.path.join(os.path.dirname(__file__)))\n if command in ['files', '-f', '--files']:\n print(list(find_files()))\n if command in ['version', '-v', '--version']:\n print(__version__)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":".venv/Lib/site-packages/regression/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"431825526","text":"#!/usr/bin/env python\n\n#This is a script that calculates collocates for a specific keyword by computing how often each word collocates with the keyword across a text corpus. A measure of the strength of association between the keyword and its collocates (MI) is calculated, and the results are saved as a single file containing the keyword, collocate, raw frequency, and the MI. \n\n\"\"\"\nCalculate collocates for specific keyword in text corpus\nParameters:\n path: str \nUsage:\n Assignment2_collocation.py -p \nExample:\n $ python Assignment2_collocation.py -p data/100_english_novels/corpus\n\"\"\"\n\n# IMPORT LIBRARIES #\nimport os\nimport sys \nsys.path.append(os.path.join(\"..\")) # enabling communication with home directory\nimport pandas as pd \nfrom pathlib import Path\nimport csv \nimport re\nimport string\nimport numpy as np\nimport argparse\n\n# DEFINE TOKENIZE() FUNTION # \n\n# First we need a tokenize() function that takes an input string and splits it into tokens (individual words) and then returns a list of the individual words\n\ndef tokenize(input_string):\n # Using the compile() function from the re module to search for all characters except for lowercase and uppercase letters and apostrophes.\n tokenizer = re.compile(r\"[^a-zA-Z']+\") \n # Create a list of tokens (words) by splitting the input string at the compiling pattern defined above\n token_list = tokenizer.split(input_string)\n # Return the list of tokens (individual words)\n return token_list\n\n# DEFINE MAIN FUNCTION # \n \n# Now we need a function that takes a path, a keyword, and a window size and calculates how often each word in the corpus collocates with the keyword across the corpus. It should then calculate the mutual information (MI) between the keyword and all collocates across the corpus. The MI is a measure of the strength of association between the keyword and the collocate in question. The function should return a dataframe with four columns: keyword, collocate, raw_frequency, and MI.\n\ndef main():\n \n # First I want to define the arguments that the function requires in order to be run from the command line \n # I do this using the argparse module\n \n # Define function arguments \n ap = argparse.ArgumentParser()\n # Argument 1: the first argument is the path to the corpus directory\n ap.add_argument(\"-p\", \"--path\", required = True, help= \"Path to directory of text corpus\")\n # Argument 2: the second argument is the keyword\n ap.add_argument(\"-k\", \"--keyword\", required = True, help= \"Key/target word in lowercase letters\")\n # Argument 3: the third argument is the window size\n ap.add_argument(\"-w\", \"--windowsize\", required = True, help= \"Window size in number of words\")\n # Create a variable containing the argument parameters defined above\n args = vars(ap.parse_args())\n \n # Define path to text corpus\n input_path = args[\"path\"]\n # Define keyword\n keyword = args[\"keyword\"]\n # Define window size\n window_size = int(args[\"windowsize\"])\n \n # Now we can move on to the actual function\n \n # Create empty list for all tokens across the corpus\n token_list_all = []\n #Create empty list of all collocates\n collocates_list = []\n # Create empty dataframe with the four columns\n data = pd.DataFrame(columns=[\"keyword\", \"collocate\", \"raw_frequency\", \"MI\"])\n # Create empty u (keyword) variable \n u = 0\n \n# Create a loop that goes through each file in the corpus and does the following: reads the file, tokenizes it using the tokenize() function defined previously, appends the list of all tokens across the corpus with the tokens from each individual file, makes a list of indices in which the particular positions (index) of the keyword in the token list is found, and calculates u (the number of occurrences of the keyword in the token_list)\n \n for filename in Path(path).glob(\"*.txt\"):\n with open (filename, \"r\", encoding = \"utf-8\") as file:\n text = file.read()\n # Create a list of tokens consisting of the tokens from each file\n token_list = tokenize(text.lower())\n # Create a list of all tokens from across the corpus by extending/appending the token list for each file\n token_list_all.extend(token_list)\n # Create a list of all occurrences of the keyword across the file\n indices = [index for index, x in enumerate(token_list) if x == keyword]\n # Calculate u which is the number of keyword occurrences, hence the length of the indices list\n u = u + len(indices)\n \n# Now a loop within the loop above is created. This loop goes through the list of keyword occurrences (indices) and finds the word(s) before and after the keyword based on the window_size parameter. \n for index in indices:\n # Define window_start\n window_start = max(0, index - window_size)\n # Define window_end\n window_end = index + window_size\n # Define the entire string: {word(s) before keyword} {keyword} {word(s) after keyword}\n keyword_string = token_list[window_start : window_end + 1] # + 1 is added to include the last index\n # Append the list of collocates with the keyword_string\n collocates_list.extend(keyword_string)\n # Remove the keyword so only the collocates appear in the list\n collocates_list.remove(keyword)\n \n# A new loop is now created. This loop goes through a list of the unique collocates (only one occurrence per collocate) and calculates v (how often the collocate occurs), the raw frequency aka. O11 (how often the collocate occurs in the same context as the keyword), O12 (how often the keyword occurs without the collocate), O21 (how often the collocate occurs without the keyword), R1 (O11 + O12), C1 (O11 + O21), N (total number of words), E11 (R1*C1/N), and MI (mutual information) which is the strength of association between the keyword and the collocate\n \n # Create empty list of the unique collocates using the set() function\n unique_collocates = set(collocates_list)\n \n for collocate in unique_collocates:\n # Calculate v (number of occurrences of the collocate across the entire corpus)\n v = token_list_all.count(collocate)\n # Calculate O11 (number of occurrences of the collocate) \n O11 = collocates_list.count(collocate)\n # Calculate O12 (how often the keyword occurs without the collocate)\n O12 = u - O11\n # Calculate O21 (how often the collocate occurs without the keyword)\n O21 = v - O11\n # Calculate R1 (the number of times the keyword occurs with any collocate within the window size)\n R1 = O11 + O12\n # Calculate C1 (the number of times the collocate appears across the whole corpus)\n C1 = O11 + O21\n # Calculate N (the total length of the corpus)\n N = len(token_list_all)\n # Calculate E11\n E11 = R1*C1/N\n # Calculate MI\n MI = np.log(O11/E11)\n \n # Append to the dataframe with the calculated parameters \n data = data.append({\"keyword\": keyword, \n \"collocate\": collocate, \n \"raw_frequency\": O11,\n \"MI\": MI}, ignore_index = True)\n \n # Sort by the MI values in descending order so the collocate with the highest MI appears at the top of the list\n data = data.sort_values(\"MI\", ascending = False) \n \n # Return the dataframe\n return data\n \n# Now we have a dataframe consisting of four columns: keyword, collocate, raw_frequency, and MI\n\n# APPLY THE FUNCTION TO THE 100 ENGLISH NOVELS CORPUS # \n\n# Now we can actually use the function on a text corpus consisting of 100 English novels\n\n# Define path\npath = os.path.join(\"..\", \"data\", \"100_english_novels\", \"corpus\")\n\n# Use the main() function with example keyword (\"sunshine\") and window size (2)\ncollocates_df = main(path, \"sunshine\", 2)\n\n# Save the dataframe as a csv-file\ncollocates_df.to_csv(\"Collocates.csv\", index = False)\n \n# Define behaviour when called from command line\nif __name__==\"__main__\":\n main()","sub_path":"assignments/assignment2_StringProcessing/Assignment2_collocation_au617836.py","file_name":"Assignment2_collocation_au617836.py","file_ext":"py","file_size_in_byte":8417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"10929749","text":"import jieba\nimport jieba.posseg\n\njieba.set_dictionary('./datas/dict.txt.big')\njieba.load_userdict('./datas/userdict.txt')\ncontent = open('./datas/lyrics.txt','rb').read()\nwords = jieba.cut(content, cut_all=False)\n\nfor word in words:\n\tprint(word, end=\", \")\n\nwords2 = jieba.posseg.cut(content)\nfor x in words2:\n\tprint(x.word,x.flag, end=\", \")\t\n\n","sub_path":"week5/nlp2/jiebaTest.py","file_name":"jiebaTest.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"411943754","text":"from random import randint\r\nimport os\r\n\r\ndef main():\r\n\r\n print(\"Welcome to Hangman!\\nYou have 6 guesses!\\nAfter 6 guesses, the game will end.\")\r\n\r\n word_bank = [\"learn\", \"speak\", \"something\", \"try\", \"enjoy\", \"because\", \"than\", \"before\", \"oneself\", \"understand\",\r\n \"become\", \"always\"]\r\n\r\n word_buffer = []\r\n # this keeps track of what the answer is\r\n\r\n blank_buffer = []\r\n # this is the list of blanks that changes with every guess\r\n\r\n word = randint(0, len(word_bank))\r\n # choosing a random word from the bank\r\n # the end point changes based on how many words there are\r\n\r\n word_buffer.extend(word_bank[word])\r\n # this puts the chosen word into the word buffer\r\n\r\n word_deux = []\r\n word_deux.extend(word_bank[word])\r\n # this is making a reference list to compare to to tell when to finish the game\r\n\r\n for x in word_buffer:\r\n blank_buffer.append(\"_ \")\r\n # this is populating the blank buffer with a number of blanks\r\n # equal to the letters in the chosen word\r\n\r\n\r\n for x in blank_buffer:\r\n print(x, end=\" \")\r\n # this prints out the blanks on screen neatly (initial blanks)\r\n\r\n user_prompt = \"\\nWhat is your guess? \\n> \"\r\n # this will store the guesses and be used to feed data into the func\r\n\r\n miss_box = []\r\n\r\n # keeps track of letters guessed and missed\r\n\r\n def placing_letters():\r\n guess = input(user_prompt)\r\n os.system('cls')\r\n # clears the screen so it doesn't get cluttered\r\n\r\n if guess.isalpha() == True and len(guess) == 1:\r\n\r\n if guess in word_buffer:\r\n print(\"There's a %s!\" % guess)\r\n\r\n while guess in word_buffer:\r\n guess_index = word_buffer.index(guess)\r\n # finding the index of the guess-letter in the blank buffer\r\n\r\n blank_buffer[guess_index] = guess\r\n # changing the blank at the guess's index to the guess\r\n\r\n word_buffer[guess_index] = 0\r\n \"\"\"This whole loop changes multiple letter entries in the manufactured list\r\n This solves the problem of retrieving indices of multiple entries in a list\"\"\"\r\n\r\n print(\" \".join(blank_buffer))\r\n # printing the new blank buffer with the replaced guess/index\r\n\r\n print(miss_box)\r\n \"\"\"if the guess is actually in the word, this will exchange\r\n a blank in for the letter\"\"\"\r\n\r\n elif guess in blank_buffer:\r\n print(\"You've already guessed %s!\" % guess)\r\n print(\" \".join(blank_buffer))\r\n # ~~without this, the blank buffer doesn't display~~\r\n\r\n print(miss_box)\r\n pass\r\n\r\n else:\r\n if guess not in miss_box:\r\n miss_box.append(guess)\r\n # this keeps the miss box from having multiple entries of the same value\r\n\r\n print(\"There's no %s.\" % guess)\r\n print(\" \".join(blank_buffer))\r\n # ~~without this, the blank buffer doesn't display~~\r\n\r\n print(miss_box)\r\n pass\r\n \"\"\"if the guess is not in the word, this will display\r\n the user's progress and pass\"\"\"\r\n\r\n else:\r\n print(\"That's not a correct guess.\")\r\n print(\" \".join(blank_buffer))\r\n # ~~without this, the blank buffer doesn't display~~\r\n\r\n if len(miss_box) > 0:\r\n print(miss_box)\r\n # this catches the multi-letter entries\r\n\r\n\r\n while word_buffer != blank_buffer:\r\n if blank_buffer != word_deux:\r\n placing_letters()\r\n # this keeps the game going as long as there are letters left to be guessed\r\n\r\n if len(miss_box) == 6:\r\n print(\"You've lost the game! Try again next time!\")\r\n print(\"The correct answer was %s\" % word_bank[word].upper())\r\n break\r\n # loss scenario, ends the game at the specified guess limit\r\n\r\n elif blank_buffer == word_deux:\r\n os.system('cls')\r\n print(\"Congratulations! You win!\")\r\n print(\" \".join(blank_buffer))\r\n # ~~without this, the blank buffer doesn't display~~\r\n\r\n print(miss_box)\r\n break\r\n\r\n \"\"\"This if loop is to finish the game when the value of the reference var (word_deux)\r\n equals the current blank buffer\"\"\"\r\n\r\n input()\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":4586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429553094","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nimport sqlite3\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-r', '--ratings', action='store', dest='ratings', help='Shows plot for ratings.')\nparser.add_argument('-t', '--typeComparisson', action='store', dest='frequencyTR', help='Shows comparisson between type and ratings.')\nparser.add_argument('-y', '--yearAdded', action='store', dest='yearAdded', help='Shows frequency of Movies and TV Shows released in years.')\nparser.add_argument('-s', '--releaseSort', action='store', dest='releaseSort', help='Shows count of Movies and TV Shows sorted acc. to release year.')\nparser.add_argument('-c', '--countrySort', action='store', dest='countrySort', help='Shows count of Movies and TV Shows sorted acc. to countries.')\nparser.add_argument('-l', '--listedSort', action='store', dest='listedSort', help='Shows count of Movies and TV Shows sorted acc. to the year of listing.')\n\nargs = parser.parse_args()\nrating = args.ratings\nfreqTRD = args.frequencyTR\nyear = args.yearAdded\nrelease = args.releaseSort\ncountry = args.countrySort\nlisted = args.listedSort\n\nif(rating):\n ratings()\nelif (freqTRD):\n freqTR()\nelif (year):\n yearAdded()\nelif(release):\n releaseSort()\nelif(country):\n countrySort()\nelif(listed):\n listedSort()\n\ndf = pd.read_csv(r'C:\\Users\\Dell\\Downloads\\archive\\netflix_titles.csv')\ncon = sqlite3.connect(\"netflix.db\")\nc=con.cursor()\ndf = pd.read_sql_query(\"SELECT * from MyTable\", con)\ndf=df.drop_duplicates(['title','country','type','release_year'])\ndf['date_added'] = pd.to_datetime(df['date_added'])\n\nfor i in df.index:\n if df.loc[i,'rating']=='UR':\n df.loc[i,'rating']='NR'\n\nreleaseSort = pd.read_sql('''select release_year,type,count(type) as count from MyTable group by release_year order by count DESC''', con)\nreleaseSort.to_sql(\"releaseSort\",con, if_exists = \"replace\")\n\ncountrySort = pd.read_sql('''select country, type, count(type) as count from MyTable group by country order by count DESC''',con)\ncountrySort.to_sql(\"countrySort\",con,if_exists = \"append\")\n\nlistedSort = pd.read_sql('''select listed_in, type, count(type) as count from MyTable group by listed_in''',con)\nlistedSort.to_sql(\"listedSort\",con,if_exists = \"append\")\n\ndef ratings():\n plt.figure(figsize=(8,6))\n df['rating'].value_counts(normalize=True).plot.bar()\n plt.title('Ratings')\n plt.xlabel('rating')\n plt.ylabel('relative frequency')\n plt.show()\n\ndef freqTR():\n plt.figure(figsize=(10,8))\n sns.countplot(x='rating',hue='type',data=df)\n plt.title('comparing frequency between type and rating')\n plt.show()\n\ndef yearAdded():\n df['year_added']=df['date_added'].dt.year\n yearSort = df.groupby('year_added')['type'].value_counts(normalize=True)*100\n\ndef releaseSort():\n df = pd.read_sql_query(\"SELECT * from releaseSort\", con)\n df.head()\n\ndef countrySort():\n df = pd.read_sql_query(\"SELECT * from countrySort\", con)\n df.head()\n\ndef listedSort():\n df = pd.read_sql_query(\"SELECT * from listedSort\", con)\n df.head()\n","sub_path":"proj.py","file_name":"proj.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"179521673","text":"\nimport time as pyTime\nimport os\nimport subprocess\nimport tornado.log\n\n\nclass Time:\n _isTZSet = False\n\n @staticmethod\n def discover_timezone():\n if Time._isTZSet:\n return\n\n if os.path.isfile('/etc/timezone'):\n handle = open('/etc/timezone', 'rb')\n os.environ['TZ'] = handle.read().decode('utf-8').strip()\n pyTime.tzset()\n\n handle.close()\n return\n\n output = subprocess.check_output('timedatectl|grep \"Time zone\"', shell=True).decode('utf-8')\n\n try:\n os.environ['TZ'] = output.split(': ')[1].split(' ')[0]\n pyTime.tzset()\n\n except KeyError:\n return\n\n @staticmethod\n def time():\n Time.discover_timezone()\n return pyTime.time()\n\n @staticmethod\n def sleep(secs):\n Time.discover_timezone()\n\n tornado.log.app_log.debug('Sleeping ' + str(secs) + ' seconds')\n return pyTime.sleep(secs)\n\n\ndef sleep(secs):\n Time.sleep(secs)\n\n\ndef time():\n return Time.time()\n","sub_path":"repairman/lib/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"327279088","text":"from unittest import TestCase\nimport extractor\n\n__author__ = 'Ondrej Galbavy'\n\n\nclass TestExtractor(TestCase):\n def test_ensure_id_non_exist(self):\n objects = {}\n extractor.Extractor.ensure_id('some_id', objects)\n self.assertIn('some_id', objects)\n\n def test_ensure_id_exist(self):\n objects = {}\n objects['some_id'] = {'id': id, 'name': 'Do not overwrite me', 'alias': [], 'type': []}\n extractor.Extractor.ensure_id('some_id', objects)\n self.assertEqual(objects['some_id']['name'], 'Do not overwrite me')\n\n def test_extract(self):\n triples_files = '../../data/sample_basic_objects.triples'\n f = open(triples_files, 'r')\n objects = extractor.Extractor.extract(f)\n f.close()\n\n # count of found objects\n self.assertEqual(len(objects), 3)\n\n # ids of objects\n self.assertListEqual(sorted(objects.keys()), sorted(['m.01dyhm', 'm.03x5qm', 'm.04pm6']))\n\n # exactly this object\n self.assertDictEqual(objects['m.03x5qm'], {'alias': ['Ubuntu Linux'], 'type': ['Software', 'Operating System', 'Topic', 'Brand', 'Speech topic', 'Literature Subject'], 'id': 'm.03x5qm', 'name': 'Ubuntu'})\n\n # check language filtering\n self.assertTrue(u'\\u0e44\\u0e1f\\u0e23\\u0e4c\\u0e1f\\u0e2d\\u0e01\\u0e0b\\u0e4c' not in objects['m.01dyhm']['alias'])\n","sub_path":"python/src/extractor/test_extractor.py","file_name":"test_extractor.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"547151076","text":"'''\n@Author : sean cheng\n@Email : aya234@163.com\n@CreateTime : 2018/9/10\n@Program : 使用turtle库的turtle.fd()函数和turtle.seth()函数绘制嵌套六角形,\n 六角形边长从1像素开始,第一条边从0度方向开始,\n 边长按照3个像素递增\n'''\n\nimport turtle\nedge = 6\nd = 0\nk = 1\nfor j in range(10):\n for i in range(edge):\n turtle.fd(k)\n d += 360/60\n turtle.seth(d)\n k += 3\nturtle.done()\n","sub_path":"python/考试练习题/turtle_star6.py","file_name":"turtle_star6.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"601291970","text":"import rospy\nimport tf\nimport numpy as np\n\nfrom geometry_msgs.msg import PoseStamped\n\nposes = [np.concatenate([np.identity(3), np.zeros((3, 1))], axis=-1).astype(np.float64)]\n\ndef pose_cb(pose):\n\n mat = tf.transformations.quaternion_matrix([pose.pose.orientation.x, pose.pose.orientation.y, pose.pose.orientation.z, pose.pose.orientation.w])\n mat[0, 3] = pose.pose.position.x\n mat[1, 3] = pose.pose.position.y\n mat[2, 3] = pose.pose.position.z\n poses.append(mat[:3])\n\n print(\"received pose #{}!\".format(len(poses)))\n\ndef save_poses():\n global poses\n poses = np.array(poses)\n print(\"Saving {} received poses...\".format(len(poses)))\n np.savetxt(\"poses.txt\", poses.reshape(len(poses), -1))\n\nrospy.init_node(\"viso2_pose_recorder\", disable_signals=True)\nrospy.Subscriber(\"/mono_odometer/pose\", PoseStamped, pose_cb)\n\nrospy.on_shutdown(save_poses)\n\nprint(\"ready to rumble!\")\n\nrospy.spin()\n","sub_path":"viso2_pose_extractor.py","file_name":"viso2_pose_extractor.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"175964872","text":"import math\nimport random \n\ndef merge_helper(lines, merge_group, check_merge_criteria):\n merged_lines = []\n\n if (len(lines) == 0):\n return []\n \n remaining_lines = lines[:]\n \n seed_idx = 0\n seed_line = lines[seed_idx]\n groups = [[seed_line]]\n to_remove_idxs = [0]\n current_group_idx = 0\n while (len(remaining_lines)>0):\n for i in xrange(1, len(remaining_lines)):\n growing_line = merge_group(groups[current_group_idx])\n line = remaining_lines[i]\n if (check_merge_criteria(growing_line, line)):\n groups[current_group_idx].append(line)\n to_remove_idxs.append(i)\n remaining_lines_copy = []\n for i in xrange(len(remaining_lines)):\n if i not in to_remove_idxs:\n remaining_lines_copy.append(remaining_lines[i][:])\n remaining_lines = remaining_lines_copy\n if (len(remaining_lines)>0):\n current_group_idx += 1\n next_seed = remaining_lines[0]\n groups.append([next_seed])\n to_remove_idxs = [0]\n\n for group in groups:\n merged_line = merge_group(group)\n merged_lines.append(merged_line)\n return merged_lines\n\ndef merge(lines, merge_group, check_merge_criteria):\n max_iter = 10\n count = 0\n num_lines = len(lines)\n merged_lines = lines\n done = False\n while not done:\n count += 1\n merged_lines = merge_helper(merged_lines, merge_group, check_merge_criteria)\n num_merged_lines = len(merged_lines)\n if (num_merged_lines == num_lines) or (count == max_iter):\n done = True\n else:\n num_lines = num_merged_lines\n\n return merged_lines\n \n","sub_path":"python/general_merge.py","file_name":"general_merge.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"388856175","text":"'''\r\nBase tasks for generic point-to-point reaching\r\n'''\r\n\r\nfrom __future__ import division\r\nimport numpy as np\r\nimport manualcontrolmultitasks\r\nfrom riglib.experiment import traits, Sequence\r\nimport tasks\r\nimport math\r\nimport traceback\r\n\r\n####### CONSTANTS\r\n\r\n\r\nsec_per_min = 60.0\r\nRED = (1,0,0,.5)\r\nGREEN = (0,1,0,0.5)\r\nmm_per_cm = 1./10\r\n\r\nclass ManualControlMulti_plusvar(manualcontrolmultitasks.ManualControlMulti):\r\n\r\n planar_hand = traits.Float(0, desc=\"0: For Standard Manual Control, 1: Kinarm style Manual Control\")\r\n hold_variance = traits.Float(100, desc = \"Variance of hold period for origin hold\")\r\n\r\n status = dict(\r\n wait = dict(start_trial=\"target\", stop=None),\r\n target = dict(enter_target=\"hold\", timeout=\"timeout_penalty\", stop=None),\r\n hold = dict(leave_early=\"hold_penalty\", hold_complete=\"targ_transition\"),\r\n targ_transition = dict(trial_complete=\"reward\",trial_abort=\"wait\", trial_incomplete=\"target\"),\r\n timeout_penalty = dict(timeout_penalty_end=\"targ_transition\"),\r\n hold_penalty = dict(hold_penalty_end=\"targ_transition\"),\r\n reward = dict(reward_end=\"wait\")\r\n )\r\n\r\n def __init__(self, *args, **kwargs):\r\n super(ManualControlMulti_plusvar, self).__init__(*args, **kwargs)\r\n self.hold_time_pls_var = self.hold_time + np.random.uniform(low=-1,high=1)*self.hold_variance\r\n \r\n def _start_hold(self):\r\n self.hold_time_pls_var = self.hold_time + np.random.uniform(low=-1,high=1)*self.hold_variance\r\n super(ManualControlMulti_plusvar, self)._start_hold()\r\n\r\n def _test_hold_complete(self, ts):\r\n return ts >= self.hold_time_pls_var\r\n\r\n def move_effector(self):\r\n ''' Sets the plant configuration based on motiontracker data. For manual control, uses\r\n motiontracker data. If no motiontracker data available, returns None. Changes configuration\r\n depending on self.planar_hand (whether to ignore y or z variable)'''\r\n #get data from motion tracker- take average of all data points since last poll\r\n pt = self.motiondata.get()\r\n if len(pt) > 0:\r\n pt = pt[:, self.marker_num, :]\r\n conds = pt[:, 3]\r\n inds = np.nonzero((conds>=0) & (conds!=4))[0]\r\n if len(inds) > 0:\r\n pt = pt[inds,:3]\r\n #scale actual movement to desired amount of screen movement\r\n pt = pt.mean(0) * self.scale_factor\r\n if self.planar_hand==0: #Set y coordinate to 0 for 2D tasks\r\n pt[1] = 0\r\n pt[1] = pt[1]*2 #From ManualControlMulti\r\n elif self.planar_hand==1:\r\n pt[2] = pt[1].copy()\r\n pt[1] = 0\r\n \r\n # Return cursor location\r\n self.no_data_count = 0\r\n pt = pt * mm_per_cm #self.convert_to_cm(pt)\r\n else: #if no usable data\r\n self.no_data_count += 1\r\n pt = None\r\n else: #if no new data\r\n self.no_data_count +=1\r\n pt = None\r\n\r\n # Set the plant's endpoint to the position determined by the motiontracker, unless there is no data available\r\n if pt is not None:\r\n #print pt\r\n self.plant.set_endpoint_pos(pt)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"tasks/manualcontrolmulti_COtasks.py","file_name":"manualcontrolmulti_COtasks.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"504841990","text":"import os\n\nfrom flask import Flask, render_template, request, redirect, url_for, session\nfrom spread_sheet import get_list\nfrom guest import Guest, Guests\n\napp = Flask(__name__)\nguests = Guests()\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\n\n@app.route('/result/', methods=['GET'])\ndef result(username):\n guests.update()\n registered = guests.is_exist(username)\n\n if registered:\n user = guests.get_guest(username)\n else:\n user = Guest(username, '')\n\n return render_template('result.html', registered=registered, user=user)\n\n\n@app.route('/user', methods=['POST'])\ndef user():\n username = request.form['name']\n return redirect(url_for('result', username=username))\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"241695784","text":"import flask\n\nimport bin\nimport views\n\n\ndef create_app():\n app = flask.Flask(__name__)\n app.config.from_object('config')\n app.config.update(\n SESSION_COOKIE_SECURE=True,\n SESSION_COOKIE_HTTPONLY=True,\n )\n app.register_blueprint(views.bp)\n app.register_blueprint(bin.bp)\n\n if 'SENTRY_DSN' in app.config:\n import sentry_sdk\n from sentry_sdk.integrations.flask import FlaskIntegration\n sentry_sdk.init(\n dsn=app.config['SENTRY_DSN'],\n integrations=[FlaskIntegration()],\n )\n\n return app\n\n\nif __name__ == '__main__':\n app = create_app()\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"287234407","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport datetime\r\nfrom datetime import timedelta\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\n\r\nsns.set(color_codes=True)\r\npd.set_option('display.max_columns',100)\r\n\r\n\r\n\r\n\r\n\r\ncustomers = pd.read_csv('ml_case_training_data.csv')\r\nchurn = pd.read_csv('ml_case_training_output.csv')\r\n\r\ndf = pd.merge(customers, churn, on='id')\r\n\r\n\r\n\r\n#### Percentage of missing values per feature\r\nprint(pd.DataFrame({'Missing values(%)' : df.isnull().sum()/len(df.index)*100}))\r\n\r\n\r\n\r\n################################ VIZ #####################################\r\n\r\n\r\nactivity = df [['id','activity_new','churn']]\r\nactivity = activity.groupby([activity['activity_new'],activity['churn']])['id'].count().unstack(level=1).sort_values(by=[0], ascending=False)\r\n\r\nactivity.plot(kind='bar', figsize=(18,10), width=2, stacked=True, title='SME activity')\r\nplt.ylabel('Number of Companies')\r\nplt.xlabel('Activity')\r\n\r\nplt.legend(['Retention','Churn'], loc='upper right')\r\nplt.xticks([]) #### !!! do not show names in the x-axis\r\nplt.show()\r\n\r\n\r\n\r\n\r\n### plotting electricity and gas consumption - need log-transform\r\nplt.figure(figsize=(12,8))\r\nplt.subplot(3,1,1); sns.distplot(customers['cons_12m'])\r\nplt.subplot(3,1,2); sns.distplot(customers['cons_gas_12m'])\r\nplt.subplot(3,1,3); sns.distplot(customers['cons_last_month'])\r\nplt.show()\r\n\r\n\r\nplt.figure(figsize=(12,8))\r\nplt.subplot(2,1,1); sns.distplot(customers['forecast_cons_12m'])\r\nplt.subplot(2,1,2); sns.distplot(customers['forecast_cons_year'])\r\nplt.show()\r\n\r\n\r\n##############################################################################\r\n\r\n\r\n\r\ndef plot_distribution(dataframe, column, ax, bins_=50):\r\n \r\n temp = pd.DataFrame({'Retention':dataframe[dataframe['churn']==0][column],\r\n 'Churn':dataframe[dataframe['churn']==0][column]})\r\n \r\n \r\n temp[['Retention','Churn']].plot(kind='hist',bins=bins_, ax=ax, stacked =True)\r\n ax.set_xlabel(column)\r\n ax.ticklabel_format(style = 'plain', axis='x')\r\n \r\n \r\n\r\nconsumption = df[['id','cons_12m','cons_gas_12m','cons_last_month','imp_cons','has_gas','churn']]\r\n \r\n \r\nfig, axs = plt.subplots(nrows=4, figsize=(18,25)) \r\n \r\nplot_distribution(consumption, 'cons_12m', axs[0])\r\nplot_distribution(consumption[consumption['has_gas']=='t'], 'cons_gas_12m', axs[1])\r\nplot_distribution(consumption, 'cons_last_month', axs[2])\r\nplot_distribution(consumption, 'imp_cons', axs[3])\r\n\r\n\r\n\r\n\r\n#############################################################################\r\ndates = df[['id','date_activ','date_end','date_modif_prod','date_renewal','churn']].copy()\r\n\r\n\r\ndates['date_activ'] = pd.to_datetime(dates['date_activ'], format = '%Y-%m-%d')\r\ndates['date_end'] = pd.to_datetime(dates['date_end'], format = '%Y-%m-%d')\r\ndates['date_modif_prod'] = pd.to_datetime(dates['date_modif_prod'], format = '%Y-%m-%d')\r\ndates['date_renewal'] = pd.to_datetime(dates['date_renewal'], format = '%Y-%m-%d')\r\n\r\n\r\ndef plot_dates(dataframe, column, fontsize_=12):\r\n \r\n temp = dataframe[[column, 'churn', 'id']].set_index(column).groupby([pd.Grouper(freq='M'), 'churn']).count().unstack(level=1)\r\n \r\n \r\n ax= temp.plot(kind='bar', stacked=True, figsize=(18,10), rot=0)\r\n ax.set_xticklabels(map(lambda x: line_format(x), temp.index))\r\n \r\n plt.xticks(fontsize = fontsize_)\r\n \r\n plt.ylabel('Number of Companies')\r\n plt.legend(['Retention','Churn'], loc = 'upper right')\r\n plt.show()\r\n \r\n \r\n \r\ndef line_format(label):\r\n\r\n month = label.month_name()[:1]\r\n if label.month_name() == 'January':\r\n month += f'\\n{label.year}'\r\n \r\n return month\r\n\r\n\r\n\r\n\r\n\r\nplot_dates(dates, 'date_activ', fontsize_=8) \r\nplot_dates(dates, 'date_end')\r\nplot_dates(dates,'date_modif_prod', fontsize_= 8)\r\nplot_dates(dates, 'date_renewal')\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":"EDA.py","file_name":"EDA.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"138620736","text":"# Major library imports\nimport numpy as np\nfrom numpy import arange, sort, compress, arange\nfrom numpy.random import random\nfrom enable.example_support import DemoFrame, demo_main\n# Enthought library imports\nfrom enable.api import Component, ComponentEditor, Window\n\nfrom traits.api import HasTraits, Instance, Array, Str, File, Any, on_trait_change\nfrom traitsui.api import Item, Group, View, Tabbed, VGroup, HGroup\n\n# Chaco imports\nfrom chaco.api import AbstractDataSource, ArrayPlotData, Plot, \\\n HPlotContainer, LassoOverlay\nfrom chaco.tools.api import LassoSelection, ScatterInspector\n\nfrom chaco.api import ArrayPlotData\nfrom chaco.tools.api import PanTool, ZoomTool\n\nimport tables as tb\n\nfrom views.hdf5_tree import _hdf5_tree, _hdf5_tree_editor, Hdf5FileNode\n\n### Display Scatter Plot ######################################################\n\ndef _fuel_cycle_plot_component(x, y, x_name, y_name):\n # Create some data\n\n # Create a plot data obect and give it this data\n pd = ArrayPlotData()\n pd.set_data(\"index\", x)\n pd.set_data(\"value\", y)\n # Create the plot\n plot = Plot(pd)\n plot.plot((\"index\", \"value\"),\n type=\"line\",\n marker=\"circle\",\n index_sort=\"ascending\",\n color=\"red\",\n marker_size=3,\n bgcolor=\"white\")\n # Tweak some of the plot properties\n plot.title = \"Fuel Cycle Plot\"\n plot.line_width = 0.5\n plot.padding = 100\n\n plot.x_axis.title = x_name\n plot.x_axis.title_font = \"Roman 16\"\n plot.x_axis.tick_label_font = \"Roman 12\"\n \n plot.y_axis.title = y_name\n plot.y_axis.title_font = \"Roman 16\"\n plot.y_axis.tick_label_font = \"Roman 12\"\n\n # Attach some tools to the plot\n plot.tools.append(PanTool(plot))\n zoom = ZoomTool(component=plot, tool_mode=\"box\", always_on=False)\n plot.overlays.append(zoom)\n \n return plot\n\nclass FuelCyclePlotView(HasTraits):\n plot = Instance(Component)\n\n file = File('fuel_cycle.h5')\n\n h5file = Any\n\n x_path = Str\n y_path = Str\n\n x_name = Str\n y_name = Str\n\n x = Array\n y = Array\n\n x_tree = Instance(Hdf5FileNode)\n y_tree = Instance(Hdf5FileNode)\n\n\n @on_trait_change('x, y, x_name, y_name') \n def update_plot(self):\n try:\n len(self.x)\n len(self.y)\n except:\n return \n\n if len(self.x) == len(self.y):\n x = self.x\n y = self.y\n\n elif len(self.x) < len(self.y):\n x = np.arange(len(self.y))\n y = self.y\n\n elif len(self.y) < len(self.x):\n x = self.x\n y = np.arange(len(self.x))\n \n fcpc = _fuel_cycle_plot_component(x, y, self.x_name, self.y_name)\n self.plot = fcpc\n\n# def update_x_path(self, node):\n# print node.path\n# self.x_path = node.path[1:].replace('/', '.')\n\n x_node = Any\n y_node = Any\n\n traits_view = View(\n HGroup(\n Item('x_tree', editor = _hdf5_tree_editor(selected='x_node'), resizable = True, show_label=False, width=0.15), \n Item('y_tree', editor = _hdf5_tree_editor(selected='y_node'), resizable = True, show_label=False, width=0.15), \n Item('plot', editor=ComponentEditor(size=(700, 700), bgcolor='lightgray'), show_label=False),\n ),\n resizable=True,\n )\n \n #\n # Trait Defaults \n #\n\n def _plot_default(self):\n fcpc = _fuel_cycle_plot_component(self.x, self.y, 'No Data', 'No Data')\n return fcpc\n\n def _h5file_default(self):\n h5file = tb.openFile(self.file, 'r')\n return h5file\n\n def _x_default(self):\n return np.array([])\n\n def _y_default(self):\n return np.array([])\n\n def _x_tree_default(self):\n x_tree = _hdf5_tree(self.file)\n return x_tree\n\n def _y_tree_default(self):\n y_tree = _hdf5_tree(self.file)\n return y_tree\n\n #\n # Trait Changed\n #\n\n def _x_node_changed(self):\n x_path = self.x_node.path[1:].replace('/', '.')\n self.x_path = x_path\n\n def _y_node_changed(self):\n y_path = self.y_node.path[1:].replace('/', '.')\n self.y_path = y_path\n\n def _x_path_changed(self):\n node_str = '.'.join(['self.h5file.root', self.x_path])\n try:\n x = eval(node_str)\n self.x = np.array(x)\n self.x_name = node_str.rpartition('.')[2]\n except:\n return\n\n def _y_path_changed(self):\n node_str = '.'.join(['self.h5file.root', self.y_path])\n try:\n y = eval(node_str)\n self.y = np.array(y)\n self.y_name = node_str.rpartition('.')[2]\n except:\n return \n \n\n# def __del__(self):\n# self.h5file.close()\n# del super(_fuel_cycle_plot_view, self)\n \ndef fuel_cycle_plot():\n return \n\nif __name__ == \"__main__\":\n \n \n _fcpview = FuelCyclePlotView ()\n _fcpview.configure_traits()\n","sub_path":"bright/gui/views/component_views/fuel_cycle_plot.py","file_name":"fuel_cycle_plot.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"518416043","text":"import os\nimport numpy as np\nimport glob\nimport cv2\nfrom collections import defaultdict\n\n\n# using opencv2 for loading images in grayscale. Can be substituted to any other loading method that keeps format\n# [image height, image width, channels]\ndef imread(path):\n return cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2GRAY)\n\n\ndef save_imgs_to_ndy(data_dir_path, dataset_part, binary_file_dir_path):\n \"\"\"\n saves images into numpy binary file. For consistency with original repository purposes. Keeping Omniglot formatting,\n as implemented in original repository - batcher.py. Our classes are load one after another, from class digit 0 to\n class digit 9.\n :param data_dir_path: path to folder with images to be converted\n :param dataset_part: test or train, to keep them separated\n :param binary_file_dir_path: path to dir\n \"\"\"\n # get all images in directory\n data_paths = glob.glob(os.path.join(data_dir_path, '*.png'))\n # get data shape from first image [img_count, img_h, img_w, channels]\n data_shape = (len(data_paths),) + imread(data_paths[0]).shape\n data_array = np.zeros(data_shape, dtype='uint8')\n\n for datum_index in range(len(data_paths)):\n # read all images and save them in data array\n data_array[datum_index] = imread(data_paths[datum_index])\n # save data array to binary numpy file\n np.save(os.path.join(binary_file_dir_path, dataset_part + '_data.npy'), data_array, allow_pickle=False)\n\n labels = defaultdict(int)\n for datum_index in range(len(data_paths)):\n # split path to image by path separator and then split image name by '-'. First substring contains label.\n label = data_paths[datum_index].split(os.path.sep)[-1].split('-')[0]\n # increase given label counter\n labels[label] += 1\n\n label_counts_array = np.zeros([len(labels.keys())], dtype='int32')\n # write dictionary to label_counts_array\n for key in labels.keys():\n label_counts_array[int(key)] = labels[key]\n\n # save label counts to binary numpy file\n np.save(os.path.join(binary_file_dir_path, dataset_part + '_sizes.npy'), label_counts_array, allow_pickle=False)\n # compute start of each class within array\n class_starts = np.cumsum(label_counts_array)\n class_starts = np.roll(class_starts, 1)\n class_starts[0] = 0\n # and save it to the binary numpy file\n np.save(os.path.join(binary_file_dir_path, dataset_part + '_starts.npy'), label_counts_array, allow_pickle=False)\n\n\nif __name__ == '__main__':\n # process training images# compute start of each class within array\n train_dataset_path = os.path.join('data', 'letters_learn_es_pp')\n save_imgs_to_ndy(train_dataset_path, 'train', 'data')\n # process training images# compute start of each class within array\n test_dataset_path = os.path.join('data', 'letters_recogn_es_pp')\n save_imgs_to_ndy(test_dataset_path, 'test', 'data')\n","sub_path":"process_images.py","file_name":"process_images.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"179174607","text":"# -*- coding: utf-8 -*-\nimport sys\nsys.path.append('../')\n\nfrom structured_data import index_excels_normalTable\n\nexcel = \"excels_hoteles/indicesdeocupacionporcategorias.xls\"\nsheet = 0\nname_index = \"index_indice_censal_por_categorias\"\ntype_index = \"structured\"\n\n\ntable_start_and_end = {\n \"start_row\": 0,\n \"start_col\": 0,\n \"end_row\": 525,\n \"end_col\": 9,\n \"start_value_row\": 1,\n \"start_value_col\": 0\n}\n\ntype_items = {\n \"year\" : int,\n \"month\" : int,\n \"type\" : str,\n \"value\" : float\n}\n\nattributes_to_fixed={\n \"place\": \"Tenerife\"\n}\n\npos_value_restrictions = [\n {\n 'name':'type',\n 'ini':2,\n 'end':9\n }\n]\n\nchange_months = 'month'\n\nname_items = [\"year\",\"month\",\"1 stars\", \"2 stars\", \"3 stars\", \"4 stars\", \"5 stars\", \"hoteliers\",\"non-hoteliers\",\"total\"]\n\nindex_excels_normalTable.main(excel, sheet, name_index, type_index, table_start_and_end, type_items, name_items, pos_value_restrictions = pos_value_restrictions, attributes_to_fixed =attributes_to_fixed, change_months=change_months)\n\n\n\n","sub_path":"airflow/data_analysis/classify_elastic/structured_data/index_hoteles/index_Indice_Censal_por_Categorias_tenerifedata.py","file_name":"index_Indice_Censal_por_Categorias_tenerifedata.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"455259874","text":"def ex1():\r\n salario=float(input())\r\n gasto=float(input())\r\n porcgasto=salario*0.3\r\n if (gaston2):\r\n print('1')\r\n else:\r\n print('0')\r\n if (n1==n2):\r\n print('1')\r\n else:\r\n print('0')\r\n if (n1=n2):\r\n print('1')\r\n else:\r\n print('0')\r\n if (n1<=n2):\r\n print('1')\r\n else:\r\n print('0')\r\n #----#\r\ndef doarsangue():\r\n idade=int(input())\r\n sexo=input()\r\n peso=float(input())\r\n ano=int(input())\r\n qtd=int(input())\r\n mes=int(input())\r\n\r\n if(idade>=16 and idade<=69):\r\n if(peso>=50):\r\n if(sexo=='m'):\r\n if(qtd<4):\r\n if((9-mes)>=2 ):\r\n print('Pode ser doador')\r\n else:\r\n print('Nao pode doar sangue')\r\n else:\r\n print('Nao pode doar sangue')\r\n elif(sexo=='f'):\r\n if(qtd<3):\r\n if((9-mes)>=3 ):\r\n print('Pode ser doadora')\r\n else:\r\n print('Nao pode doar sangue')\r\n else:\r\n print('Nao pode doar sangue')\r\n else:\r\n print('Nao pode doar sangue')\r\n else:\r\n print('Nao pode doar sangue')\r\n else:\r\n print('Nao pode doar sangue')\r\ndef dia():\r\n dia=int(input())\r\n if(dia==1):\r\n print('Domingo')\r\n elif (dia==2):\r\n print('Segunda')\r\n elif(dia==3):\r\n print('Terca')\r\n elif (dia==4):\r\n print('Quarta')\r\n elif (dia==5):\r\n print('Quinta')\r\n elif (dia==6):\r\n print('Sexta')\r\n elif (dia==7):\r\n print('Sabado')\r\n else:\r\n print('valor invalido')","sub_path":"1semestre/Python/04 10 trein 1.py","file_name":"04 10 trein 1.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"608230010","text":"# -*- coding: utf-8 -*-\n\"\"\"\n~~~~~~~~~~~~~~~~~~~~\nA simple GIF encoder\n~~~~~~~~~~~~~~~~~~~~\n\"\"\"\nfrom struct import pack\n\n\nclass DataBlock(object):\n \"\"\"Write bits into a bytearray and then pack this bytearray into data blocks.\n This class is used in the LZW algorithm when encoding maze into frames.\"\"\"\n\n def __init__(self):\n self._bitstream = bytearray() # write bits into this array.\n self._nbits = 0 # a counter holds how many bits have been written.\n\n def encode_bits(self, num, size):\n \"\"\"Given a number `num`, encode it as a binary string of length `size`,\n and pack it at the end of bitstream.\n Example: num = 3, size = 5. The binary string for 3 is '00011',\n here we padded extra zeros at the left to make its length to be 5.\n The tricky part is that in a gif file, the encoded binary data stream\n increase from lower (least significant) bits to higher\n (most significant) bits, so we have to reverse it as '11000' and pack\n this string at the end of bitstream!\n \"\"\"\n string = bin(num)[2:].zfill(size)\n for digit in reversed(string):\n if len(self._bitstream) * 8 == self._nbits:\n self._bitstream.append(0)\n if digit == '1':\n self._bitstream[-1] |= 1 << self._nbits % 8\n self._nbits += 1\n\n def dump_bytes(self):\n \"\"\"Pack the LZW encoded image data into blocks.\n Each block is of length <= 255 and is preceded by a byte\n in 0-255 that indicates the length of this block.\n \"\"\"\n bytestream = bytearray()\n while len(self._bitstream) > 255:\n bytestream += bytearray([255]) + self._bitstream[:255]\n self._bitstream = self._bitstream[255:]\n if len(self._bitstream) > 0:\n bytestream += bytearray([len(self._bitstream)]) + self._bitstream\n\n self._nbits = 0\n self._bitstream = bytearray()\n return bytestream\n\n\nstream = DataBlock()\n\n\nclass GIFWriter(object):\n \"\"\"\n Structure of a GIF file: (in the order they appear)\n 1. always begins with the logical screen descriptor.\n 2. then follows the global color table.\n 3. then follows the loop control block (specify the number of loops)\n 4. then follows the image data of the frames, each frame is further divided into:\n (i) a graphics control block that specify the delay and transparent color of this frame.\n (ii) the image descriptor.\n (iii) the LZW enconded data.\n 5. finally the trailor '0x3B'.\n \"\"\"\n\n def __init__(self, width, height, min_bits, palette, loop):\n \"\"\"Attributes are listed in the order they appear in the GIF file.\"\"\"\n # constants for LZW encoding.\n self._palette_bits = min_bits\n self._clear_code = 1 << min_bits\n self._end_code = (1 << min_bits) + 1\n self._max_codes = 4096\n\n packed_byte = 1 # the packed byte in the logical screen descriptor.\n packed_byte = packed_byte << 3 | (self._palette_bits - 1) # color resolution.\n packed_byte = packed_byte << 1 | 0 # sorted flag.\n packed_byte = packed_byte << 3 | (self._palette_bits - 1) # size of the global color table.\n self.logical_screen_descriptor = pack('<6s2H3B', b'GIF89a', width, height, packed_byte, 0, 0)\n\n valid_len = 3 * (1 << min_bits)\n if len(palette) > valid_len:\n palette = palette[:valid_len]\n if len(palette) < valid_len:\n palette += [0] * (valid_len - len(palette))\n self.global_color_table = bytearray(palette)\n\n self.loop_control = pack('<3B8s3s2BHB', 0x21, 0xFF, 11, b'NETSCAPE', b'2.0', 3, 1, loop, 0)\n self.data = bytearray()\n self.trailor = bytearray([0x3B])\n\n @staticmethod\n def graphics_control_block(delay, trans_index):\n \"\"\"This block specifies the delay and transparent color of a frame.\"\"\"\n return pack(\"<4BH2B\", 0x21, 0xF9, 4, 0b00000101, delay, trans_index, 0)\n\n @staticmethod\n def image_descriptor(left, top, width, height):\n \"\"\"This block specifies the position of a frame (relative to the window).\n The ending packed byte field is 0 since we do not need a local color table.\"\"\"\n return pack(' mid:\n ch |= bits[bit]\n lon_interval = (mid, lon_interval[1])\n else:\n lon_interval = (lon_interval[0], mid)\n else:\n mid = (lat_interval[0] + lat_interval[1]) / 2\n if latitude > mid:\n ch |= bits[bit]\n lat_interval = (mid, lat_interval[1])\n else:\n lat_interval = (lat_interval[0], mid)\n even = not even\n if bit < 4:\n bit += 1\n else:\n geohash += base32[ch]\n bit = 0\n ch = 0\n return ''.join(geohash)\n\n\n# 读取处理后的数据,并提取特征\ntrain = pd.read_csv('sub_features_new.csv')\n\n#合并正确的标签\ntrain_old = pd.read_csv('features.csv')\nlabel_true = pd.DataFrame({\n 'loadingOrder': train_old['loadingOrder'],\n 'label': train_old['label']\n})\ntrain = train.drop('label', axis=1)\ntrain = train.merge(label_true, on='loadingOrder', how='left')\n\n# 合并路由之类的数据\ntransport = pd.read_csv('transport_trace_fea.csv', index_col=0)\ntransport = transport.drop('id', axis=1)\ntrain = train.merge(transport, on='loadingOrder', how='left')\n\n#合并起点坐标\nzuobiao = pd.read_csv('first_zuobiao.csv', index_col=0)\nzuobiao = zuobiao.drop('id', axis=1)\ntrain = train.merge(zuobiao, on='loadingOrder', how='left')\n\n#合并终点坐标\nzuobiao = pd.read_csv('last_zuobiao.csv', index_col=0)\nzuobiao = zuobiao.drop('id', axis=1)\ntrain = train.merge(zuobiao, on='loadingOrder', how='left')\n\ndf = train.groupby('loadingOrder')[['first_longitude', 'first_latitude', 'last_longitude', 'last_latitude']].agg(lambda x: round(x[0:1])).reset_index()\n\nloadingOrder = df['loadingOrder'].tolist()\nfirst_longitude = df['first_longitude'].tolist()\nfirst_latitude = df['first_latitude'].tolist()\nfirst_xy = list(zip(first_longitude, first_latitude))\n\nlast_longitude = df['last_longitude'].tolist()\nlast_latitude = df['last_latitude'].tolist()\nlast_xy = list(zip(last_longitude, last_latitude))\n\nl_first = dict(zip(loadingOrder, first_xy))\nl_last = dict(zip(loadingOrder, last_xy))\n\ntrace_all = [x.replace(\" \", \"\").upper() for x in port_data['router'].tolist()]\nfinal_x = port_data['longitude'].tolist()\nfinal_y = port_data['latitude'].tolist()\nport_dict_x = dict(zip(trace_all, final_x))\nport_dict_y = dict(zip(trace_all, final_y))\n\nxy = [[final_x[i], final_y[i]] for i in range(len(final_x))]\nkd = spatial.KDTree(data=xy)\n\ndrop_far = pd.DataFrame(columns=['loadingOrder', 'drop_far'])\nthreshold = 3\nnum = 0\n\ntrain = pd.DataFrame(columns=['id', 'loadingOrder', 'TRANSPORT_TRACE_start', 'TRANSPORT_TRACE_final'])\n\nfor file in file_list:\n num += 1\n print(num)\n file_path = os.path.join(split_data_path, file)\n train_data_o = pd.read_csv(file_path, nrows=1, header=None)\n train_data_o.columns = ['id', 'loadingOrder', 'carrierName', 'timestamp', 'longitude',\n 'latitude', 'vesselMMSI', 'speed', 'direction', 'vesselNextport',\n 'vesselNextportETA', 'vesselStatus', 'vesselDatasource', 'TRANSPORT_TRACE']\n if train_data_o['loadingOrder'][0] not in l_first.keys(): continue\n if ('-' not in str(train_data_o['TRANSPORT_TRACE'][0])):\n #first\n x, y = l_first[train_data_o['loadingOrder'][0]]\n v, ii = kd.query([[x, y]])\n #print(v, ii)\n s1 = trace_all[ii[0]]\n # first\n x, y = l_last[train_data_o['loadingOrder'][0]]\n v, ii = kd.query([[x, y]])\n #print(v, ii)\n s2 = trace_all[ii[0]]\n train_o = pd.DataFrame({\n 'id': train_data_o['id'][0],\n 'loadingOrder': train_data_o['loadingOrder'][0],\n 'TRANSPORT_TRACE_start': [s1.replace(\" \", \"\").upper()],\n 'TRANSPORT_TRACE_final': [s2.replace(\" \", \"\").upper()]\n })\n #print(train_o)\n train = train.append(train_o, ignore_index=True)\n continue\n s = train_data_o['TRANSPORT_TRACE'][0].split('-')\n train_o = pd.DataFrame({\n 'id': train_data_o['id'][0],\n 'loadingOrder': train_data_o['loadingOrder'][0],\n 'TRANSPORT_TRACE_start': [s[0].replace(\" \", \"\").upper()],\n 'TRANSPORT_TRACE_final': [s[-1].replace(\" \", \"\").upper()]\n })\n train = train.append(train_o, ignore_index=True)\nprint(num, df.shape[0])\ntrain.to_csv('transport_trace_fea_fix.csv', index=True)","sub_path":"fix_trace.py","file_name":"fix_trace.py","file_ext":"py","file_size_in_byte":5549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"619135873","text":"print(\"Witaj w prostym kalkulatorze\")\r\na = int(input(\"Podaj pierwsza liczbe: \"))\r\nb = int(input(\"Podaj druga liczbe: \"))\r\nc = input(\"Wybierz rodzaj dzialania: 1 - dodawanie, 2 - odejmowanie, 3 - mnozenie, 4 - dzielenie\")\r\n\r\nif c == '1':\r\n wynik = a + b\r\nelif c == '2':\r\n wynik = a - b\r\nelif c == '3':\r\n wynik = a * b\r\nelif c == '4':\r\n wynik = a / b\r\nelse:\r\n print(\"Dokonales zlego wyboru\")\r\n print(\"Wynik dzialania to: \", wynik)\r\n","sub_path":"Zadania/Instrukcja_Warunkowa_if_1.py","file_name":"Instrukcja_Warunkowa_if_1.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"647964902","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n################################################################################\n# Phoseg Copyright (C) 2012 Suizokukan\n# Contact: suizokukan _A.T._ orange dot fr\n#\n# This file is part of Phoseg.\n# Phoseg is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Phoseg 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 Phoseg. If not, see .\n################################################################################\n\"\"\"\n ❏Phoseg❏ : phoseg/phonation.py\n\"\"\"\n\nfrom phoseg.basic.nomenclature import Nomenclature, NomenclatureData\nfrom phoseg.phonetic.phosegdescriptiveelement import PhoSegDescriptiveElement\n\nDATA_PHONATION = (\n (( 'nil phonation:silence', ) , (\"nil phonation\",)),\n\n (( 'nil phonation:glottal stop',), (\"voiceless glottal stop\",\n \"voiceless glottal plosive\",)),\n\n (( 'breath phonation', ) , (\"breath phonation\",\n \"voiceless\",\n \"breathed\")),\n (( 'whisper phonation', ) , (\"whisper phonation\",\n \"whispered\")),\n (( 'voiced phonation', ) , (\"voiced phonation\",\n \"voiced\")),\n (( 'creak phonation', ) , (\"creak phonation\",)),\n (( 'falsetto', ) , (\"falsetto\",)),\n\n (( 'whisper phonation',\n 'voiced phonation' ) , ('whispery voice',\n 'whispery voiced',\n 'whisper phonation voiced phonation',)),\n (( 'whisper phonation',\n 'falsetto' ) , ('whispery falsetto',\n 'whisper phonation falsetto')),\n (( 'whisper phonation',\n 'creak' ) , ('whispery creak',\n 'whisper phonation creak')),\n (( 'breath phonation',\n 'voiced phonation' ) , ('breathy voice',\n 'breathy voiced',\n 'breath phonation voiced phonation')),\n (( 'creak phonation',\n 'voiced phonation' ) , ('creaky voice',\n 'creaky voiced',\n 'creak phonation voiced phonation')),\n (( 'falsetto',\n 'voiced phonation' ) , ('creaky falsetto',\n 'falsetto voiced phonation')),\n (( 'whisper phonation',\n 'voiced phonation',\n 'creak phonation' ) , ('whispery creaky voice',\n 'whispery creaky voiced',\n 'whisper phonation voiced '\\\n 'phonation creak phonation')),\n (( 'whisper phonation',\n 'voiced phonation',\n 'falsetto' ) , ('whispery creaky falsetto',\n 'whisper phonation voiced phonation falsetto')),\n )\n\nPHONATION_NOMENCLATUREDATA = NomenclatureData(DATA_PHONATION)\n\n################################################################################\nclass Phonation(PhoSegDescriptiveElement):\n \"\"\"\n class Phonation\n \"\"\"\n\n #///////////////////////////////////////////////////////////////////////////\n def __init__(self,\n informations = None):\n \"\"\"\n Phonation.__init__\n\n informations : see initialization()\n \"\"\"\n phonation_object = Nomenclature( name = \"Phonation\",\n default_initialization = ( 'voiced phonation', ),\n data = PHONATION_NOMENCLATUREDATA)\n\n PhoSegDescriptiveElement.__init__(self,\n nomenclature = phonation_object,\n func_initialization = self.initialization,\n informations = informations)\n\n #///////////////////////////////////////////////////////////////////////////\n def is_breath_phonation(self):\n \"\"\"\n Phonation.is_breath_phonation\n\n RETURN VALUE: (boolean)\n \"\"\"\n return self.informations == ('breath phonation',)\n\n #///////////////////////////////////////////////////////////////////////////\n def is_breathed(self):\n \"\"\"\n Phonation.is_breathed\n\n RETURN VALUE: (boolean)\n \"\"\"\n return self.is_breath_phonation()\n\n #///////////////////////////////////////////////////////////////////////////\n def is_breathy_voiced(self):\n \"\"\"\n Phonation.is_breathy_voiced\n\n RETURN VALUE: (boolean)\n \"\"\"\n return self.informations == ( 'breath phonation',\n 'voiced phonation' )\n\n #///////////////////////////////////////////////////////////////////////////\n def is_glottal(self):\n \"\"\"\n Phonation.is_glottal\n\n RETURN VALUE: (boolean)\n \"\"\"\n return self.informations == ('nil phonation:glottal stop',)\n\n #///////////////////////////////////////////////////////////////////////////\n def is_voiced(self):\n \"\"\"\n Phonation.voiced phonation\n\n RETURN VALUE: (boolean)\n \"\"\"\n return 'voiced phonation' in self.informations\n","sub_path":"phoseg/phonetic/phonation.py","file_name":"phonation.py","file_ext":"py","file_size_in_byte":6329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"461076928","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 26 15:22:53 2020\r\n\r\n@author: Romain\r\n\r\nScore table for detecting words in texts\r\n\r\n\"\"\"\r\n\r\nwordList = ['the','are','is','we','they',\r\n 'it','for','one','two','three',\r\n 'end','and','then','why','will',\r\n 'was','were', 'them', 'now', 'his',\r\n 'her', 'mine', 'after', 'before',\r\n 'during', 'over', 'hand', 'arm',\r\n 'mouth', 'nose', 'head', 'eye', \r\n 'with', 'without', 'all', 'almost',\r\n 'far', 'near', 'close', 'open', 'good', \r\n 'bad', 'ok', 'speak', 'walk', 'talk',\r\n 'think', 'thing', 'able', 'lot', 'i',\r\n 'you', 'he', 'she', 'parent', 'child', \r\n 'children', 'family', 'police', 'had', \r\n 'have', 'got', 'get', 'come', 'way', 'sex', \r\n 'number', 'thought', 'come', 'become']\r\n\r\ndef word_appearence(string):\r\n score = 0\r\n for i in wordList:\r\n if i in string:\r\n score += 1\r\n \r\n return score\r\n\r\n","sub_path":"wordAppearence.py","file_name":"wordAppearence.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"529612252","text":"#!/usr/bin/env python2\n\"\"\" Module for ECEn 682R, HW3 \"\"\"\n__author__ = 'Rich Li'\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef hw_3e():\n \"\"\" Problem 3e, computer simulation\n\n This simulates X-ray intensity variation\n\n \"\"\"\n # Intensity of center\n I0 = 1e5\n\n # Slab parameters\n mu = 4 # in 1/cm\n L = 10 # in cm\n\n # Angle distribution\n theta = np.linspace(-30,30,100) # in degrees\n theta = np.deg2rad(theta) # now in radians\n\n # Intensity as a function of theta\n Ir = I0 * np.power(np.cos(theta), 3) * np.exp(-mu * L / np.cos(theta))\n\n # Draw plot\n plt.plot(np.rad2deg(theta), Ir/I0)\n plt.xlabel(r'$\\theta$', fontsize='xx-large')\n plt.ylabel('$I_r/I_0$', fontsize='xx-large')\n #plt.gca().axes.get_yaxis().set_ticks([])\n plt.title('X-ray intensity through a slab of L={}, $\\mu$={}'.format(L, mu))\n plt.savefig('hw3_3e.png')\n\n # Simulate an image\n\n # Uniform distribution of theta, phi\n N = 5e6 # number of simulated hits\n #d = 1 # distance between source and detector\n phi = 360 * np.random.random(N) # U(0,360) degrees\n theta = 60 * np.random.random(N) - 30 # U(-30,30) degrees\n phi = np.deg2rad(phi) # in radians\n theta = np.deg2rad(theta) # in radians\n\n # Intensity as a function of theta\n #Ir = I0 * np.power(np.cos(theta), 3) * np.exp(-mu * L / np.cos(theta))\n #x_hits = Ir * np.cos(phi)\n #y_hits = Ir * np.sin(phi)\n #H, xedges, yedges = np.histogram2d(x_hits, y_hits, 100)\n #extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]]\n #plt.figure()\n #plt.imshow(H, extent=extent, interpolation='nearest')\n #plt.colorbar()\n #plt.hot()\n\ndef main():\n hw_3e()\n plt.show()\n\nif __name__=='__main__':\n main()\n","sub_path":"682/hw3/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"498327016","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\" module where global constants are specified \"\"\"\n\nimport sgutils\n\n# application and version\nAPPNAME = \"g.static\"\nAPPVERSION = \"0.22\"\n\n# error showed when another script than sgrun.py is launched\nERROR_LAUNCHED_SCRIPT = \"You should run sgrun.py instead\"\n\n# this constant is about a capitalized title\nTITLE_CAP = 10\n\n# plugins system\nplugins_prev = []\t\t\t# at the begin of processing page \t\t\t\t\tsgprog.textget\nplugins_post = []\t\t\t# at the end of processing page\t\t\t\t\t\tsgprog.textget\nplugins_fnal = []\t\t\t# at the end of works, before copying to dest\n\n# about showmsg()\nMESSAGE_NORMAL = 0\nMESSAGE_ERROR = 1\nMESSAGE_LOG = 9\nMESSAGE_DEBUG = 99\n\nif __name__ == \"__main__\":\n\tsgutils.showmsg(ERROR_LAUNCHED_SCRIPT, MESSAGE_NORMAL)","sub_path":"sgglobals.py","file_name":"sgglobals.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"325846826","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSample Script for Streamlit Application for Kickstarter dataset\r\n\"\"\"\r\n\r\nimport streamlit as st\r\nimport pandas as pd\r\nimport pickle\r\nimport plotly.express as px\r\n\r\n@st.cache\r\ndef load_data(n_rows=3000):\r\n data = pd.read_csv('https://raw.githubusercontent.com/JonathanBechtel/dat-02-22/main/ClassMaterial/Unit3/data/ks2.csv', nrows=n_rows)\r\n return data\r\n\r\n@st.cache\r\ndef group_data(x_axis, y_axis):\r\n result = data.groupby(x_axis)[y_axis].mean()\r\n return result\r\n\r\n@st.cache\r\ndef load_model():\r\n with open('mod.pkl', 'rb') as mod:\r\n pipe = pickle.load(mod)\r\n \r\n return pipe\r\n\r\nst.title(\"Understanding Kickstarter Applications\")\r\n\r\nsection = st.sidebar.radio('Section', ['Data Explorer', 'Model Predictions'])\r\n\r\nn_rows = st.sidebar.number_input(\"Enter Number of Rows To Load\", min_value=1000, max_value=100000, step=1000)\r\ndata = load_data(n_rows)\r\nif section == 'Data Explorer':\r\n chart_type = st.sidebar.selectbox('Chart Type', ['Bar', 'Line', 'Strip'])\r\n \r\n st.write(data)\r\n \r\n x_axis = st.sidebar.selectbox('Choose Column for X-Axis', ['category', 'main_category', 'country'])\r\n y_axis = st.sidebar.selectbox('Choose Column for y-axis', ['state', 'goal'])\r\n \r\n st.header(f\"Average value for {y_axis} for column {x_axis}\")\r\n\r\n if chart_type == 'Bar':\r\n result = group_data(x_axis, y_axis)\r\n st.bar_chart(result)\r\n elif chart_type == 'Line':\r\n result = group_data(x_axis, y_axis)\r\n st.line_chart(result)\r\n else:\r\n result = data[[x_axis, y_axis]]\r\n st.plotly_chart(px.strip(result, x=x_axis, y=y_axis, color=x_axis))\r\n \r\nelif section == 'Model Predictions':\r\n with open('mod.pkl', 'rb') as mod:\r\n pipe = pickle.load(mod)\r\n print(pipe)\r\n category = st.sidebar.selectbox('Select A Category', data['category'].unique().tolist())\r\n main_category = st.sidebar.selectbox('Select a Main Category', data['main_category'].unique().tolist())\r\n funding_amount = st.sidebar.number_input('Enter Your Funding Amount', min_value=0, value=1000, step=500) \r\n \r\n sample = pd.DataFrame({\r\n 'category': [category],\r\n 'main_category': [main_category],\r\n 'funding_amount': [funding_amount]\r\n })\r\n \r\n \r\n prediction = pipe.predict_proba(sample)\r\n print(prediction)\r\n \r\n st.header(f\"Predicted Probability of Campaign Successs: {prediction[0][1]:.2%}\")","sub_path":"repo-GAclass/Unit 3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"133583209","text":"\"\"\"\nThe Delboeuf illusion.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport neuropsydia as n\n\n\n\n\ndef delboeuf_compute(difficulty=0, illusion=0, minimum_size=2.5, distance=5, distance_auto=True, background_color=\"white\"):\n \"\"\"\n Delboeuf Illusion\n\n Parameters\n ----------\n difficulty : float\n Size of right inner circle.\n illusion : float\n Size of outer circles.\n minimum_size : float\n Size of smaller inner circle.\n distance : float\n distance between circles.\n distance_auto : bool\n If true, distance is between edges (fixed spacing), if false, between centers (fixed location).\n background_color : str\n Background color.\n \"\"\"\n if difficulty > 0: # if right is smaller\n inner_size_right = minimum_size\n inner_size_left = inner_size_right + inner_size_right * abs(difficulty)\n outer_size_left = inner_size_left + (inner_size_left/10)\n outer_size_right = inner_size_right + (inner_size_right/10)\n\n if illusion > 0:\n illusion_type = \"Incongruent\"\n outer_size_left = outer_size_left + outer_size_left * abs(illusion)\n else:\n illusion_type = \"Congruent\"\n outer_size_right = outer_size_right + outer_size_right * abs(illusion)\n\n else:\n inner_size_left = minimum_size\n inner_size_right = inner_size_left + inner_size_left * abs(difficulty)\n outer_size_left = inner_size_left + (inner_size_left/10)\n outer_size_right = inner_size_right + (inner_size_right/10)\n\n if illusion > 0:\n illusion_type = \"Incongruent\"\n outer_size_right = outer_size_right + outer_size_right * abs(illusion)\n else:\n illusion_type = \"Congruent\"\n outer_size_left = outer_size_left + outer_size_left * abs(illusion)\n\n\n inner_size_smaller = min([inner_size_left, inner_size_right])\n inner_size_larger = max([inner_size_left, inner_size_right])\n outer_size_smaller = min([outer_size_left, outer_size_right])\n outer_size_larger = max([outer_size_left, outer_size_right])\n\n\n\n\n\n if distance_auto is False:\n distance_centers = distance\n position_left = 0 - distance_centers/2\n position_right = 0 + distance_centers/2\n distance_edges_inner = distance_centers - (inner_size_left/2 + inner_size_right/2)\n distance_edges_outer = distance_centers - (outer_size_left/2 + outer_size_right/2)\n else:\n distance_edges_outer = distance\n distance_centers = distance_edges_outer + (inner_size_left/2 + inner_size_right/2)\n distance_edges_inner = distance_centers - (outer_size_left/2 + outer_size_right/2)\n position_left = 0-distance_centers/2\n position_right = 0+distance_centers/2\n\n\n\n parameters = {\"Illusion\": illusion,\n \"Illusion_Absolute\": abs(illusion),\n \"Illusion_Type\": illusion_type,\n \"Difficulty\": difficulty,\n \"Difficulty_Absolute\": abs(difficulty),\n\n \"Difficulty_Ratio\": inner_size_larger/inner_size_smaller,\n \"Difficulty_Diff\": inner_size_larger-inner_size_smaller,\n\n \"Size_Inner_Left\": inner_size_left,\n \"Size_Inner_Right\": inner_size_right,\n \"Size_Outer_Left\": outer_size_left,\n \"Size_Outer_Right\": outer_size_right,\n\n \"Distance_Centers\": distance_centers,\n \"Distance_Edges_Inner\": distance_edges_inner,\n \"Distance_Edges_Outer\": distance_edges_outer,\n \"Auto_Distance\": distance_auto,\n\n \"Size_Inner_Smaller\": inner_size_smaller,\n \"Size_Inner_Larger\": inner_size_larger,\n \"Size_Outer_Smaller\": outer_size_smaller,\n \"Size_Outer_Larger\": outer_size_larger,\n\n\n \"Position_Left\": position_left,\n \"Position_Right\": position_right,\n\n \"Background_Color\": background_color\n }\n\n return(parameters)\n\n\n\n\ndef delboeuf_display(parameters=None):\n \"\"\"\n \"\"\"\n n.circle(x=parameters[\"Position_Left\"], size=parameters[\"Size_Outer_Left\"], fill_color=parameters[\"Background_Color\"], line_color=\"black\", thickness=0.05)\n n.circle(x=parameters[\"Position_Left\"], size=parameters[\"Size_Inner_Left\"], fill_color=\"red\", line_color=\"white\")\n n.circle(x=parameters[\"Position_Right\"], size=parameters[\"Size_Outer_Right\"], fill_color=parameters[\"Background_Color\"], line_color=\"black\", thickness=0.05)\n n.circle(x=parameters[\"Position_Right\"], size=parameters[\"Size_Inner_Right\"], fill_color=\"red\", line_color=\"white\")\n\n\n\n\n\n\n","sub_path":"old/pyllusion/Delboeuf.py","file_name":"Delboeuf.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"131928488","text":"# Package: Machine Learning Data Processing - Forecast Engine\r\n# Version: 0.1\r\n# Date: 2018-09-26\r\n# Title: Collection of functions followed by main script for demand data pre-processing\r\n# Author: Royan Dawud Aldian, EY Data & Analytics\r\n# Maintainer: Likeati Hadyani\r\n# Description: This module has two main function, data preprocessing\r\n# and splitting data before the data is fitted to ML model.\r\n\r\n\r\n\r\n# Importing the libraries\r\n# Description:\r\n\r\nimport time\r\nimport numpy as np\r\nfrom sklearn.preprocessing import LabelEncoder\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n# ===========================================================================================================================================\r\n# Data Preprocessing\r\n# Description: \r\n\r\n\r\ndef data_preprocessing(df_train, df_test):\r\n start_time = time.time()\r\n print(\"Starting data preprocessing...\")\r\n\r\n # Append df_train and df_test\r\n df = df_train.append(df_test, ignore_index = True)[df_train.columns.tolist()]\r\n\r\n # Label Encoding for categorical values\r\n encoder = LabelEncoder()\r\n df['PLANT_EN'] = encoder.fit_transform(df.PLANT)\r\n df['FreqRank_EN'] = encoder.fit_transform(df.FreqRank)\r\n df['CVRank_EN'] = encoder.fit_transform(df.CVRank)\r\n df['Status_EN'] = encoder.fit_transform(df.Status)\r\n\r\n # Standard Deviation and Kurtosis on the previous 12 months demand\r\n last_dmd = '37|38|39|40|41|42|43|44|45|46|47|48'\r\n df['DMD_STD'] = df.filter(regex = last_dmd).std(axis = 1)\r\n df['DMD_KTS'] = df.filter(regex = last_dmd).kurtosis(axis = 1)\r\n\r\n # Specify demand column\r\n df['DMD'] = df.DMD49\r\n\r\n # Drop unnecessary column\r\n df.drop(['REF', 'PLANT', 'FreqRank', 'CVRank', 'DMD49'], axis = 1, inplace = True)\r\n\r\n print(\"Data preprocessing finished in\", \"%s minutes\" % np.round((time.time() - start_time) / 60, decimals = 1))\r\n return df\r\n\r\n# ===========================================================================================================================================\r\n# Splitting Data\r\n# Description\r\n\r\ndef data_splitting(df, ntrain):\r\n start_time = time.time()\r\n print(\"Splitting the data...\")\r\n\r\n # Select Train and Test Data\r\n train = df.iloc[0:ntrain, :]\r\n test = df.iloc[ntrain:, :]\r\n\r\n # Dependent and Independent Variables\r\n X_train = train.iloc[:, 2:-1].values\r\n y_train = train.iloc[:, -1:].values\r\n X_test = test.iloc[:, 2:-1].values\r\n \r\n print(\"Data splitting finished in\", \"%s minutes\" % np.round((time.time() - start_time) / 60, decimals = 1))\r\n return X_train, y_train, X_test","sub_path":"data_prep_ml.py","file_name":"data_prep_ml.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"573762197","text":"class Student(object):\n __slots__ = ('_name', '_age') # 用tuple定义允许绑定的属性名称\n# __slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:\n\n @property\n def score(self):\n return self._score\n\n @score.setter\n def score(self, value):\n if not isinstance(value, int):\n raise ValueError('score must be an integer!')\n if value < 0 or value > 100:\n raise ValueError('score must between 0 ~ 100!')\n self._score = value\n# @property的实现比较复杂,我们先考察如何使用。把一个getter方法变成属性,\n# 只需要加上@property就可以了,此时,@property本身又创建了\n# 另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,\n# 于是,我们就拥有一个可控的属性操作\n\n\n# 只定义getter方法,不定义setter方法就是一个只读属性:","sub_path":"liaoxuefeng/slots.py","file_name":"slots.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"168323712","text":"# coding: utf-8\n\nimport sys\nsys.path.insert(0, '../../../blog')\n\nfrom bs4 import BeautifulSoup\nimport requests\n\nGLOBAL_RANK = 168390\nRANK_BRAZIL = 4966\nNAME = 'operamundi.uol.com.br'\n\ndef get_urls():\n try:\n urls = [] \n link = 'https://operamundi.uol.com.br/'\n req = requests.get(link)\n bs = BeautifulSoup(req.text, \"html.parser\")\n noticias = bs.find('div', class_='news-grid').find_all('a', href=True)\n noticias += bs.find('div', class_='col-xs-12 col-md-6 home-grid').find_all('a', href=True)\n noticias += bs.find('div', class_='col-xs-12 news-grid').find_all('a', href=True)\n noticias += bs.find('div', class_='row news-grid').find_all('a', href=True)\n for noticia in noticias:\n href = noticia['href']\n# print(href)\n urls.append(href)\n \n return urls\n except:\n raise Exception('Exception in operamundi')\n ","sub_path":"robo/pages/gabriel/operamundi.py","file_name":"operamundi.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"42710695","text":"#\r\n# 이 코드는 장이 완전히 종료된 저녁 6시 이후에 실행시켜야 하도록 작성되었음.\r\n# 장 종료된 당일 거래량이 100만 이상되는 종목만을 추리는 코드임.\r\n\r\nimport urllib\r\nimport time\r\nimport win32com.client # to deal with excel\r\n\r\nfrom urllib.request import urlopen\r\nfrom bs4 import BeautifulSoup\r\nfrom pandas import Series, DataFrame\r\n\r\nprint(\"코스피 종목코드 압축 실행중... 약 1분30초~ 3분30초 가량이 소요됩니다.\")\r\n\r\ncode_df = DataFrame(columns=(\"ItemName\",\"Code\"))\r\n\r\nexcel_1 = win32com.client.Dispatch(\"Excel.Application\")\r\nexcel_1.Visible = False\r\nwb = excel_1.Workbooks.Open('C:\\\\Users\\\\DG\\\\PycharmProjects\\\\Stock(ver.1)\\\\kospi.xls')\r\nws = wb.ActiveSheet\r\n\r\nITEM = 772\r\n\r\nfor i in range(2,ITEM):\r\n rows = [str(ws.Cells(i,1).Value), str(ws.Cells(i,2).Value)]\r\n code_df.loc[len(code_df)] = rows\r\nexcel_1.Quit()\r\n\r\n\r\nexcel_2 = win32com.client.Dispatch(\"Excel.Application\")\r\nexcel_2.Visible = False\r\nwb = excel_2.Workbooks.Add()\r\nws = wb.Worksheets(\"Sheet1\")\r\n\r\nk = 2\r\nws.Cells(1, 1).Value = '회사명'\r\nws.Cells(1, 2).Value = '종목코드'\r\nws.Cells(1, 3).Value = '거래량'\r\n\r\nfor i in range(ITEM-2):\r\n stockName = code_df.ix[i,0]\r\n stockCode = code_df.ix[i,1]\r\n\r\n url = 'http://finance.naver.com/item/sise_day.nhn?code=' + stockCode\r\n html = urlopen(url)\r\n source = BeautifulSoup(html.read(), \"html.parser\")\r\n srlists = source.find_all(\"tr\")\r\n\r\n for j in range(1, len(srlists) - 1):\r\n # 데이터를 읽어오는 부분\r\n if (srlists[j].span != None):\r\n day = (srlists[j].find_all(\"td\", align=\"center\")[0].text).replace('.', '')\r\n volume = (srlists[j].find_all(\"td\", class_=\"num\")[5].text).replace(',', '')\r\n break;\r\n\r\n if(int(volume) >= 100000):\r\n ws.Cells(k, 1).Value = stockName\r\n ws.Cells(k, 2).Value = '\\'' + stockCode\r\n ws.Cells(k, 3).Value = volume\r\n k += 1\r\n\r\nwb.SaveAs('C:\\\\Users\\\\DG\\\\PycharmProjects\\\\Stock\\\\zipKospi.xls')\r\nexcel_2.Quit()","sub_path":"Stock(ver.1)/ZipKospiCode.py","file_name":"ZipKospiCode.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"381137822","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 3 10:20:12 2021\r\n\r\n@author: fanyak\r\n@title: multi-class classification\r\n@url:https://colab.research.google.com/drive/1Aw98z6xEIHFj6O7ZgMIXnhSPTTYs9c1O#scrollTo=eSSuci_6nCEG\r\n\"\"\"\r\n\r\nimport tensorflow as tf;\r\nimport os;\r\nimport re;\r\nimport string;\r\nimport matplotlib.pyplot as plt;\r\nfrom tensorflow.keras.layers.experimental.preprocessing import TextVectorization;\r\nimport numpy as np;\r\n\r\nurl = \"http://storage.googleapis.com/download.tensorflow.org/data/stack_overflow_16k.tar.gz\";\r\n# dataset = tf.keras.utils.get_file(\"stack_overflow_16k.tar.gz\", \r\n# url, untar=True, \r\n# cache_dir=\".\", cache_subdir=\"\");\r\ndataset = '.\\\\DATA\\\\stack_overflow_16k';\r\ndataset_dir = os.path.join(os.path.dirname(dataset), 'stack_overflow_16k');\r\nos.listdir(dataset_dir);\r\ntrain_dir = os.path.join(dataset_dir, 'train');\r\nos.listdir(train_dir);\r\ntest_dir = os.path.join(dataset_dir, 'test');\r\n\r\n\r\n# with open(os.path.join(train_wd,os.listdir(train_wd)[1]), 'r') as fs:\r\n# print(fs.read());\r\n\r\nbatch_size = 32;\r\nseed = 42;\r\n\r\n# CREATE A DATABASE from the train directory using the existing folders ('python','javascript'..)\r\n# as classes for the classification\r\n# use a validation 80:20 split\r\ntrain_raw_ds = tf.keras.preprocessing.text_dataset_from_directory(train_dir, batch_size=batch_size,\r\n seed=seed,\r\n validation_split = 0.2,\r\n subset='training');\r\n#print(train_raw_ds.class_names);\r\n\r\nval_raw_ds = tf.keras.preprocessing.text_dataset_from_directory(train_dir, \r\n batch_size = batch_size, \r\n seed = seed,\r\n validation_split=0.2,\r\n subset='validation');\r\ntest_raw_ds = tf.keras.preprocessing.text_dataset_from_directory(test_dir, \r\n batch_size = batch_size);\r\n\r\n\r\n########## NORMALIZE, TOKENIZE, VECTORIZE THE TEXTS ############\r\ndef standardize_data(data):\r\n lowercase = tf.strings.lower(data);\r\n return tf.strings.regex_replace(lowercase,'[%s]' % re.escape(string.punctuation), \" \");\r\n\r\n\r\nmax_features = 10000;#vocabulary length\r\nsequence_length = 250;\r\n\r\nvectorize_layer = TextVectorization(\r\n standardize=standardize_data,\r\n max_tokens = max_features, #tokenize\r\n output_mode = 'int', # vectorize,\r\n output_sequence_length = sequence_length);\r\n\r\n#get only the texts from the iterable tuples\r\nfit_texts = train_raw_ds.map(lambda x,y: x);\r\nfit_labels = train_raw_ds.map(lambda x,y: y);\r\n\r\n############ FIT THE TEXTVECTORIZATION ###########\r\n#use the texts to FIT the TextVectorization\r\nvectorize_layer.adapt(fit_texts);\r\n\r\ndef vectorize_text(text, label): # a Tuple as input since that is the form of the dataset\r\n text = tf.expand_dims(text, -1);\r\n return vectorize_layer(text), label;\r\n\r\n# try out the TextVectorization \r\nbatch = next(iter(train_raw_ds)); #batch of size 32\r\n# each batch is a TUPLE of 2 lists (texts<32>, labels<32>)\r\ntexts, labels = batch;\r\n#texts.numpy() # list of length = batch_size = 32;\r\n#labels.numpy() # list of length = batch_size = 32;\r\n\r\ntrain_ds = train_raw_ds.map(vectorize_text);\r\nval_ds = val_raw_ds.map(vectorize_text);\r\ntest_ds = test_raw_ds.map(vectorize_text);\r\n\r\n######### DATASET PERFMORMANCE #############\r\nAUTOTUNE = tf.data.experimental.AUTOTUNE\r\ntrain_ds = train_ds.cache().prefetch(buffer_size = AUTOTUNE);\r\nval_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE);\r\ntest_ds = test_ds.cache().prefetch(buffer_size = AUTOTUNE);\r\n\r\n\r\n##### CREATE THE MODEL ##########\r\nembedding_dim = 16;\r\ncategory_num = len(train_raw_ds.class_names);\r\n\r\nmodel = tf.keras.Sequential([\r\n tf.keras.layers.Embedding(max_features+1, embedding_dim),\r\n tf.keras.layers.Dropout(0.2),\r\n tf.keras.layers.GlobalAveragePooling1D(),\r\n tf.keras.layers.Dropout(0.2),\r\n tf.keras.layers.Dense(category_num),\r\n ]);\r\nmodel.summary();\r\n\r\n###### TRAIN THE MODEL ########\r\n\r\n##### METHOD 1: Manually train\r\n\r\n# def train_step(x,y_true):\r\n# optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3);\r\n# with tf.GradientTape() as tape: \r\n# y_pred = model(x)\r\n# loss = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True)\r\n# grads = tape.gradient(loss, model.trainable_variables);\r\n# optimizer.apply_gradients(zip(grads, model.trainable_variables));\r\n# return loss;\r\n\r\n# epochs = 5;\r\n# history = [];\r\n# vhistory = [];\r\n\r\n# for i in range(epochs):\r\n# iterator = iter(train_ds);\r\n# viterator = iter(val_ds);\r\n# epochHistory = [];\r\n# for train_batch in range(tf.data.experimental.cardinality(train_ds).numpy()):\r\n# x,y=iterator.get_next()#next(iterator);\r\n# loss = train_step(x,y);\r\n# epochHistory.extend(loss.numpy());\r\n# history.append(np.array(epochHistory).mean());\r\n\r\n# #check validation\r\n# epochVHistory = [];\r\n# for val_batch in range(tf.data.experimental.cardinality(val_ds).numpy()):\r\n# vx, vy = viterator.get_next()#next(viterator);\r\n# val_pred = model(vx);\r\n# vloss = tf.keras.losses.sparse_categorical_crossentropy(vy, val_pred);\r\n# epochVHistory.extend(vloss.numpy());\r\n# vhistory.append(np.array(epochVHistory).mean())\r\n\r\n# plt.plot(np.arange(epochs),history, color=\"blue\");\r\n# plt.plot(np.arange(epochs),vhistory, color=\"red\");\r\n# plt.legend(['train', 'validation'])\r\n# plt.show();\r\n\r\n\r\n######### METHOD 2: Use TF\r\nmodel.compile(optimizer='adam', \r\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\r\n metrics=['accuracy']);\r\n\r\nepochs = 5;\r\nhistory = model.fit(train_ds, validation_data=val_ds, epochs=epochs);\r\n#evaluate the model\r\nloss, accuracy = model.evaluate(test_ds); \r\n\r\nhistory_dict = history.history;\r\nacc = history_dict['accuracy'];\r\nval_acc = history_dict['val_accuracy'];\r\nloss = history_dict['loss'];\r\nval_loss = history_dict['val_loss'];\r\n\r\nepochs = range(1, len(acc) + 1)\r\n\r\n# \"bo\" is for \"blue dot\"\r\nplt.plot(epochs, loss, 'bo', label='Training loss')\r\n# b is for \"solid blue line\"\r\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\r\nplt.title('Training and validation loss')\r\nplt.xlabel('Epochs')\r\nplt.ylabel('Loss')\r\nplt.legend()\r\n\r\nplt.show();\r\n\r\nplt.plot(epochs, acc, 'bo', label='Training acc')\r\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\r\nplt.title('Training and validation accuracy')\r\nplt.xlabel('Epochs')\r\nplt.ylabel('Accuracy')\r\nplt.legend(loc='lower right')\r\n\r\nplt.show()","sub_path":"multiclass.py","file_name":"multiclass.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"381923380","text":"class DoublyLinked:\r\n\r\n def __init__(self):\r\n\r\n self.__head = None # Aponta para o primeiro elemento da lista\r\n self.__tail = None # Aponta para o último elemento da lista\r\n self.__length = 0\r\n self.__iterating = None # Axiliar para iterar com lazy evaluation\r\n\r\n class Node:\r\n\r\n def __init__(self, value):\r\n\r\n self.next = None\r\n self.previous = None\r\n self.content = value\r\n\r\n def __len__(self):\r\n return self.__length # Retornando o tamanho da lista\r\n\r\n def __iter__(self):\r\n return self\r\n\r\n def __next__(self):\r\n # Iterando na lista usando o conceito de lazy evaluation\r\n if self.__iterating is None:\r\n self.__iterating = self.__head # Iterando no primeiroe elemento\r\n else:\r\n self.__iterating = self.__iterating.next # Indo para o próximo elemento\r\n\r\n if self.__iterating is not None:\r\n return self.__iterating.content # Retornando o elemento da vez\r\n\r\n raise StopIteration # Não há mais itens para iterar. Logo, paramos de iterar\r\n\r\n def __repr__(self):\r\n return self.__str__()\r\n\r\n def __str__(self):\r\n\r\n aux = '|'\r\n\r\n for i, element in enumerate(self):\r\n aux += element.__repr__()\r\n\r\n if i < len(self) - 1:\r\n aux += ', '\r\n\r\n aux += '|'\r\n\r\n return aux\r\n\r\n def __delitem__(self, key):\r\n\r\n if key < 0: # Tratando índices negativos. Ex(del list[-1])\r\n key += len(self)\r\n\r\n if key < 0 or key >= len(self): # Informando possíveis erros\r\n raise IndexError('list assignment index out of range')\r\n\r\n i = 0\r\n current = self.__head\r\n\r\n while i <= key:\r\n\r\n if current is None:\r\n break\r\n\r\n if i == key:\r\n\r\n # Caso a lista tenha apenas um único elemento\r\n if len(self) == 1:\r\n self.__head = None\r\n self.__tail = None\r\n\r\n # Removendo o primeiro elemento da lista\r\n elif i == 0:\r\n\r\n self.__head = current.next\r\n self.__head.previous = None\r\n current.next = None\r\n\r\n # Removendo o último elemento da lista\r\n elif i == len(self) - 1:\r\n\r\n self.__tail = current.previous\r\n self.__tail.next = None\r\n current.previous = None\r\n\r\n # Removendo um elemento no meio da lista\r\n else:\r\n\r\n current.previous.next = current.next\r\n current.next.previous = current.previous\r\n\r\n current.next = None\r\n current.previous = None\r\n\r\n self.__length -= 1\r\n self.__iterating = None\r\n\r\n return current.content\r\n\r\n current = current.next\r\n i += 1\r\n\r\n def pop(self, i=-1): # Remover o último elemento da lista\r\n del self[i]\r\n\r\n def insert(self, key, value):\r\n\r\n new_node = self.Node(value)\r\n\r\n # Inserindo em uma lista vazia\r\n if len(self) == 0:\r\n\r\n self.__head = new_node\r\n self.__tail = new_node\r\n\r\n # Inserindo no começo da lista\r\n elif key <= 0:\r\n\r\n new_node.next = self.__head\r\n self.__head.previous = new_node\r\n\r\n self.__head = new_node\r\n\r\n # Inserindo no fim da lista\r\n elif key >= len(self):\r\n\r\n new_node.previous = self.__tail\r\n self.__tail.next = new_node\r\n\r\n self.__tail = new_node\r\n\r\n # Inserindo no meio da lista\r\n else:\r\n\r\n i = 0\r\n current = self.__head\r\n\r\n while i <= key:\r\n\r\n if current is None:\r\n break\r\n\r\n if i == key - 1:\r\n\r\n new_node.next = current.next\r\n current.next.previous = new_node\r\n\r\n current.next = new_node\r\n new_node.previous = current\r\n\r\n break\r\n\r\n current = current.next\r\n i += 1\r\n\r\n self.__length += 1 # Um elemento foi adicionado\r\n self.__iterating = None # Como a lista foi alterada, iterating é reinicializado\r\n\r\n def append(self, value): # Adiciona um elemento na última posição da lista\r\n self.insert(len(self), value)\r\n\r\n def push(self, value): # Adiciona um elemento na primeira posição da lista\r\n self.insert(0, value)\r\n\r\n\r\nlista = DoublyLinked()\r\nprint(lista)\r\n\r\nlista.insert(0, 7)\r\nlista.insert(0, 5)\r\n\r\nfor item in lista: # Conseguindo iterar na lista\r\n print(item)\r\n\r\nlista.pop()\r\nprint(lista)\r\n\r\nlista.push(7)\r\nprint(lista)","sub_path":"Listas/lista_duplamente_ligada.py","file_name":"lista_duplamente_ligada.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"451126893","text":"#coding:utf8\r\n'''\r\nCreated on 2014-2-24\r\n\r\n@author: CC\r\n'''\r\n\r\nfrom app.game.core.GamersManager import GamersManager\r\nfrom app.game.core.shop.shopmanager import ShopManager\r\nfrom app.game.core.shop.Shop import Shop\r\n\r\ndef getShopInfo(dynamicId,characterId,shopCategory):\r\n\t'''获取商城信息\r\n\t@param dynamicId:int 客户端id\r\n\t@param characterId:int 角色id\r\n\t@param shopCategory:int 商店类型 1金币2银币\r\n\t'''\r\n\tgamer=GamersManager().getGamerByID(characterId)\r\n\tif not gamer or not gamer.CheckClient(dynamicId):\r\n\t\treturn {'result':False,'message':u\"角色不存在\"}\r\n\tshop=ShopManager().getShopByCategory(shopCategory)\r\n\tif not shop:\r\n\t\tshop=Shop(shopCategory)\r\n\t\tShopManager().addShop(shop)\r\n\tdata=shop.getShopInfo()\r\n\treturn {'result':True,'data':data}\r\n\r\ndef buyItem(dynamicId,characterId,shopCategory,itemId,buyNum):\r\n\t'''购买道具'''\r\n\tgamer=GamersManager().getGamerByID(characterId)\r\n\tif not gamer or not gamer.CheckClient(dynamicId):\r\n\t\treturn {'result':False,'message':u\"角色不存在\"}\r\n\tdata=gamer.shop.buyItem(shopCategory,itemId,buyNum)\r\n\treturn data","sub_path":"app/game/appinterface/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"301568276","text":"from scrapy import Spider\n\nclass HFPSpider(Spider):\n name = 'huffpost'\n allowed_domains = ['huffingtonpost.com']\n start_urls = [\n \"http://www.huffingtonpost.com\"\n ]\n\n def parse(self, response):\n from huffpost.items import HuffpostItem\n\n ### headline ###\n for selector in response.xpath('//div[@class=\"a-page__content\"]'):\n item = HuffpostItem()\n item['left_titles'] = selector.xpath('div/section/div/div/div[@class=\"card__headlines\"]/h2/a/text()').extract()\n item['mid_titles'] = selector.xpath('div/div/div/div[@class=\"card__headlines\"]/h2/a/text()').extract()\n yield item\n","sub_path":"huffpost/huffpost/spiders/hfp_spider.py","file_name":"hfp_spider.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"57818364","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 2 14:27:47 2019\r\n\r\n@author: hjiang\r\n\"\"\"\r\n\r\n\"\"\"\r\nThere are a row of n houses, each house can be painted with one of the k colors. \r\nThe cost of painting each house with a certain color is different. \r\nYou have to paint all the houses such that no two adjacent houses have the same color.\r\n\r\nThe cost of painting each house with a certain color is represented by a n x k cost matrix. \r\nFor example, costs[0][0] is the cost of painting house 0 with color 0; \r\ncosts[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.\r\n\r\nNote:\r\nAll costs are positive integers.\r\n\r\nExample:\r\n\r\nInput: [[1,5,3],[2,9,4]]\r\nOutput: 5\r\nExplanation: Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; \r\n Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. \r\nFollow up:\r\nCould you solve it in O(nk) runtime?\r\n\"\"\"\r\n# Time: O(n * k)\r\n# Space: O(k)\r\n#import functools.reduce as reduce\r\n#class Solution(object):\r\n# def minCostII(self, costs):\r\n# \"\"\"\r\n# :type costs: List[List[int]]\r\n# :rtype: int\r\n# \"\"\"\r\n# return min(reduce(self.combine, costs)) if costs else 0\r\n#\r\n# def combine(self, tmp, house):\r\n# smallest, k, i = min(tmp), len(tmp), tmp.index(min(tmp))\r\n# tmp, tmp[i] = [smallest] * k, min(tmp[:i] + tmp[i+1:])\r\n# return map(sum, zip(tmp, house))\r\n\"\"\"\r\nhttps://leetcode.com/problems/paint-house-ii/discuss/69521/Python-O(nk)-beat-95-solution-with-explaination \r\nThis is a Markov Chain (dp) with k states (color 1, color 2...color k) and n stages, \r\nwe simply update the costs matrix to keep track of the optimal value for each state at current stage.\r\nmin1 means we paint all other states with the minimum cost, \r\nwhile min2 means we cannot paint consecutive houses with same color so we choose the second lowest cost to add up with.\r\nhttp://www.cnblogs.com/grandyang/p/5322870.html \r\n这题的解法的思路还是用DP,但是在找不同颜色的最小值不是遍历所有不同颜色,\r\n而是用min1和min2来记录之前房子的最小和第二小的花费的颜色,\r\n如果当前房子颜色和min1相同,那么我们用min2对应的值计算,反之我们用min1对应的值,\r\n这种解法实际上也包含了求次小值的方法\r\n\"\"\"\r\n# Time: O(n * k) \r\nclass Solution1(object):\r\n def minCostII(self, costs):\r\n \"\"\"\r\n :type costs: List[List[int]]\r\n :rtype: int\r\n \"\"\"\r\n if not costs: return 0\r\n n, k = len(costs), len(costs[0])\r\n for i in range(1, n):\r\n min1 = min(costs[i-1])\r\n idx = costs[i-1].index(min1)\r\n min2 = min(costs[i-1][:idx] + costs[i-1][idx+1:])# 除掉idx最小的, 括号里的表达式就是除掉idx\r\n for j in range(k):\r\n if j == idx:\r\n costs[i][j] += min2\r\n else:\r\n costs[i][j] += min1\r\n return min(costs[-1])\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":"Python3.6/265-Py3-Paint-house II.py","file_name":"265-Py3-Paint-house II.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"471051535","text":"'''\nPsuedo-Pokemon\n-By Kya Miller (Fall 2014, LING 508)\n\n==========A Quick Exposition on the Pokemon Universe==========\nAt its core, Pokemon is a game where cute animal-ish creatures battle with each other until one \nloses (\"fainting\"). While many of the mechanics of the original games by Nintendo have been \npreserved, some aspects have been modified to suit the tiny scope of this program.\n\nIn this simplified version of the game, each Pokemon has its own unique set of stats, including\nhit-points, attack, defense, and speed; they also have two moves they can use to inflict damage \nupon the opposing Pokemon. A Pokemon faints when its HP reaches 0. Pokemon and \ntheir moves have Types which determine the effectiveness of the attack. To keep the game as simple\nas possible, only five Types are used and a single Pokemon per each Type has been included. \n\t\n\tBulbasaur - Grass Type\n\tCharmander - Fire Type\n\tSquirtle - Water Type\n\tPikachu - Electric Type\n\tEevee - Normal Type\n\nIf a Pokemon uses a move Type that its opponent is weak to, the move does extra damage (2x); conversely,\nif the opposing Pokemon resists that Type, the move does less damage (0.5x). Moves also receive a damage\nbonus if its Type matches the Type of the Pokemon using it. Type effectiveness is somewhat intuitive\nand is displayed below:\n\n\t> = Super Effective\n\t< = Less Effective\n\t\n\tGrass: > Water\n\t\t< Fire\n\t\t< Grass\n\t\n\tFire: > Grass\n\t\t< Water\n\t\t< Fire\n\t\t\n\tWater: > Fire\n\t\t< Grass\n\t\t< Water\n\t\t\n\tElectric: > Water\n\t\t< Grass\n\t\t< Electric\n\t\t\n\tNormal: Neutral \n\t\nAfter you choose your Pokemon, an options menu is displayed. Choosing the Battle! option begins a\nbattle with a wild Pokemon. The View Pokemon option displays the Pokemon you have and gives you the \noption to switch which Pokemon you use to battle with (assuming you have more than one Pokemon).\nThe Heal Pokemon option restores the hit-points of your active Pokemon back to full health.\nThe Quit option exits the game.\n\t\nA battle with a wild Pokemon is a turn based system where each Pokemon uses a move to damage the\nother until one is no longer able to battle (accomplished by either Pokemon's HP being reduced to\n0, or by catching the wild Pokemon). \n\nIn the Fight! option, you choose a move for your Pokemon to use; the move used by the opposing \nPokemon is random. Which Pokemon attacks first is determined by the speed stats of each Pokemon \n(faster speed moves first). \n\nUsing the Catch! option, you attempt to catch the wild Pokemon to add it to your team. The chance\nof a successful capture increases the lower the wild Pokemon's hit-points are. If the wild Pokemon's\nhit points reach 0, it will faint and will not be able to be caught (because the battle ends once a\nPokemon faints).\n\nUsing the Run! option ends the battle and returns you to the main menu. \n\n\nI've really enjoyed writing this program, and plan on expanding upon it to add more and more aspects\nfrom the original games. It was a fun exercise in creating Python Classes and Definitions (although I\nwish I could figure out For loops!) I have heavily commented the code below to try to make it \neasy to understand what's going on with the algorithms and variables; if there are any questions or\nsuggestions, please feel free to email me.\t\n'''\n\nimport random\nimport math\n\nclass Pokemon:\n\t\n\tdef __init__ (self, name, type, hit_points, attack, defense, speed, moves_list):\n\t\t#Generates an instance of the Pokemon class using given values (called by def generatePokemon)\n\t\tself.name = name\n\t\tself.name_normal = self.name\n\t\tself.type = type\n\t\tself.hit_points = hit_points\n\t\tself.max_hit_points = hit_points\n\t\tself.attack = attack\n\t\tself.defense = defense\n\t\tself.speed = speed\n\t\tself.moves_list = moves_list\n\t\t\n\tdef __repr__ (self):\n\t\t#displays the stats of the given Pokemon\n\t\treturn(self.name + \" (Type: \" + self.type + \")\" + \"\\n\\tHit Points: \" + str(self.hit_points) + \"/\" + str(self.max_hit_points) + \"\\n\\tAttack: \" + str(self.attack) + \"\\n\\tDefense: \" + str(self.defense) + \"\\n\\tSpeed: \" + str(self.speed) + \"\\nMoves: \" + self.moves_list[0].name + \" (Type: \" + self.moves_list[0].type + \")\" + \", \" + self.moves_list[1].name + \" (Type: \" + self.moves_list[1].type + \")\")\n\t\t\n\tdef wild_name(self):\n\t\t#during a battle with a wild Pokemon, the Pokemon is referred to as \"Wild \" to \n\t\t#differentiate it from the player's Pokemon. Appends \"Wild\" to the Pokemon's name and stores the Pokemon's\n\t\t#original name in a variable to be accessed later.\n\t\tself.name_normal = self.name\n\t\tself.name = \"Wild \" + self.name\n\t\treturn self.name\n\t\n\tdef normal_name(self):\n\t\t#after catching a Pokemon, the Pokemon's name needs to be reverted from \"Wild \" to\n\t\t#its original name.\n\t\tself.name = self.name_normal\n\t\treturn self.name\n\t\n\tdef show_hit_points (self):\n\t\t#displays the Pokemon's name and hit-points (compact form used during battle)\n\t\tprint(self.name + \" Hit Points: \" + str(self.hit_points) + \"/\" + str(self.max_hit_points))\n\t\treturn None\n\t\t\n\tdef heal(self):\n\t\t#restores the Pokemon's hit-points to full health using the max_hit_points variable\n\t\tself.hit_points = self.max_hit_points\n\t\tprint(\"Your\", self.name, \"has been restored to full health!\")\n\t\treturn None\n\t\t\n\tdef take_damage (self, damage):\n\t\t#decreases the Pokemon's current hit-points by the amount of damage it takes from the\n\t\t#opposing Pokemon's attack. If hit-points reaches 0, displays a message. Is called by\n\t\t#useMove function\n\t\tself.hit_points = self.hit_points - damage\n\t\tif self.hit_points <= 0:\n\t\t\tprint(\"\\n\" + self.name, \"has fainted!\")\n\t\t\tself.hit_points = 0\n\t\treturn None\n\t\n\tdef useMove (self, move, other):\n\t\t#calls the effect_message, damage_calc and take_damage functions. Prints appropriate messages.\n\t\tmessage = move.effect_message(other)\n\t\tprint(self.name, \"uses\", move.name + \"!\", message)\n\t\tmove_damage = move.damage_calc(self, other)\n\t\tprint(other.name, \"takes\", str(move_damage), \"damage!\")\n\t\tother.take_damage(move_damage)\n\t\treturn None\n#End Pokemon Class\n\t\t\nclass Move:\n\tdef __init__ (self, name, type, base_damage):\n\t\t#creates an instance of the Move class. These instances are declared in the generatePokemon\n\t\t#function.\n\t\tself.name = name\n\t\tself.type = type\n\t\tself.base_damage = base_damage\n\t\t\t#the power of the move. Used in the damage_calc function\n\t\n\tdef __repr__ (self):\n\t\treturn (self.name, self.type, str(self.base_damage))\n\t\t\n\tdef displayType(self):\n\t\tprint(\"(Type:\", self.type, \")\")\n\t\n\tdef type_effect(self, defense_poke):\n\t\t#type interactions\n\t\ttype_eff = 1\n\t\t\t#type effectiveness is a modifier used in the calculation of the damage a move does.\n\t\t\t#If the type of the move is strong against the type of the opposing Pokemon, type_eff = 2;\n\t\t\t#if the move is weak against the opposing Pokemon, type_eff = 0.5. Otherwise, type_eff = 1\n\t\t\n\t\tif self.type == \"Fire\" and defense_poke.type == \"Fire\":\n\t\t\ttype_eff = 0.5\n\t\tif self.type == \"Fire\" and defense_poke.type == \"Water\":\n\t\t\ttype_eff = 0.5\n\t\tif self.type == \"Fire\" and defense_poke.type == \"Grass\":\n\t\t\ttype_eff = 2\n\t\tif self.type == \"Water\" and defense_poke.type == \"Fire\":\n\t\t\ttype_eff = 2\n\t\tif self.type == \"Water\" and defense_poke.type == \"Grass\":\n\t\t\ttype_eff = 0.5\n\t\tif self.type == \"Electric\" and defense_poke.type == \"Water\":\n\t\t\ttype_eff = 2\n\t\tif self.type == \"Electric\" and defense_poke.type == \"Electric\":\n\t\t\ttype_eff = 0.5\n\t\tif self.type == \"Electric\" and defense_poke.type == \"Grass\":\n\t\t\ttype_eff = 0.5\n\t\tif self.type == \"Grass\" and defense_poke.type == \"Fire\":\n\t\t\ttype_eff = 0.5\n\t\tif self.type == \"Grass\" and defense_poke.type == \"Water\":\n\t\t\ttype_eff = 2\n\t\tif self.type == \"Grass\" and defense_poke.type == \"Grass\":\n\t\t\ttype_eff = 0.5\n\t\tif self.type == \"Normal\":\n\t\t\ttype_eff = 1\n\t\treturn type_eff\n\t\n\tdef effect_message(self, defense_poke):\n\t\t#generates an effect message based on the type_eff variable created in the type_effect function\n\t\ttype_eff = self.type_effect(defense_poke) \t\n\t\t\n\t\teffect_message = \"\"\n\t\tif type_eff == 2:\n\t\t\teffect_message = \"Super effective!\"\n\t\tif type_eff == 0.5:\n\t\t\teffect_message = \"Not very effective...\"\n\t\t\t\n\t\treturn effect_message\n\t\n\tdef damage_calc (self, attack_poke, defense_poke):\n\t\t#modifier defaults\n\t\tstab = 1\n\t\t\t#stab stands for \"same type attack bonus\". When the type of a move matches that of the \n\t\t\t#Pokemon using the move, the move receives a damage bonus (stab = 1.5)\n\t\ttype_eff = self.type_effect(defense_poke)\n\t\tcrit = 1\n\t\t\t#Each move has a chance to score a critical hit. Currently there is no message displayed \n\t\t\t#for critical hits\n\t\t\n\t\t#modifier conditionals\n\t\tif self.type == attack_poke.type:\n\t\t\tstab = 1.5\n\t\t\t\n\t\tcrit_chance = random.randint(1, 10000)\n\t\tif crit_chance <= 625:\n\t\t\tcrit = 1.5\n\t\t\n\t\tmodifier = (stab * type_eff * crit * (random.randint(85, 100) / 100))\n\t\t\t#(random.randint(85, 100) / 100) - in the original algorithm, the game generates a number between\n\t\t\t#0.85 and 1. This basically just makes it so that if the same Pokemon uses the same move\n\t\t\t#it will not always do the same damage (because doing the same damage all the time is boring)\n\t\tdamage_calc = math.ceil((((2 * 10 + 10) / 250) * (attack_poke.attack / defense_poke.defense) * (self.base_damage + 2)) * modifier)\n\t\t\t#(2 * 10 + 10) / 250) - the original algorithm is (2 * level + 10) / 250. The 2, 10, and 250\n\t\t\t#are arbitrary values. Because level has not been implemented in this program, all Pokemon are\n\t\t\t#assumed to be level 10 (all Pokemon values are that of a level 10 instance of that particular\n\t\t\t#Pokemon from the actual games).\n\t\treturn damage_calc\n#End Move Class\n\t\t\ndef generatePokemon(genNumber):\n\t#moves_list\n\ttackle = Move(\"Tackle\", \"Normal\", 40)\n\tthundershock = Move(\"Thunder Shock\", \"Electric\", 40)\n\tquick_attack = Move(\"Quick Attack\", \"Normal\", 40)\n\tscratch = Move(\"Scratch\", \"Normal\", 40)\n\tember = Move(\"Ember\", \"Fire\", 40)\n\tvine_whip = Move(\"Vine Whip\", \"Grass\", 45)\n\twater_gun = Move(\"Water Gun\", \"Water\", 40)\n\tswift = Move(\"Swift\", \"Normal\", 60)\n\t\n\t#The possible stats generated for each random pokemon are based on the minimum and maximum\n\t#stats of that particular kind of Pokemon at level 10 in the original games. The types and\n\t#move list are also true to the games.\n\t\n\t#Uses a number that is passed in the arguments of the function to determine which Pokemon to \n\t#create. This number is usually random except when the player is choosing their first Pokemon\n\tif genNumber == 1:\n\t\tbulbasaur = Pokemon(\"Bulbasaur\", \"Grass\", random.randint(29, 32), random.randint(14, 17), random.randint(14, 17), random.randint(14, 17), [tackle, vine_whip])\n\t\treturn bulbasaur\n\tif genNumber == 2:\n\t\tcharmander = Pokemon(\"Charmander\", \"Fire\", random.randint(27, 30), random.randint(15, 18), random.randint(13, 16), random.randint(18, 21), [scratch, ember])\n\t\treturn charmander\n\tif genNumber == 3:\n\t\tsquirtle = Pokemon(\"Squirtle\", \"Water\", random.randint(28, 31), random.randint(14, 17), random.randint(18, 21), random.randint(13, 16), [tackle, water_gun])\n\t\treturn squirtle\n\tif genNumber == 4:\n\t\tpikachu = Pokemon(\"Pikachu\", \"Electric\", random.randint(27, 30), random.randint(16, 19), random.randint(13, 16), random.randint(23, 26), [quick_attack, thundershock])\n\t\treturn pikachu\t\n\tif genNumber == 5:\n\t\teevee = Pokemon(\"Eevee\", \"Normal\", random.randint(31, 34), random.randint(16, 19), random.randint(15, 18), random.randint(16, 19), [tackle, swift])\n\t\treturn eevee\n\t\t\ndef catch_pokemon(wild_pokemon):\n\t#catch rate\n\tchance = ((3 * (wild_pokemon.max_hit_points - 2) * wild_pokemon.hit_points) * 255 * 2) / (3 * wild_pokemon.max_hit_points)\n\t'''\n\t255 refers to the catch rate of the Pokemon. Each different pokemon has a different catch\n\trate, from 1 to 255. Weaker, more common Pokemon generally have lower catch rates than more\n\trare kinds. However, due to the tiny scope of this program, and the fact that the kinds of \n\tPokemon used in this program have particularly low catch rates in the original games (45 for all\n\tbut Pikachu, who is 190), I wanted to make catching as easy as possible so I set them all \n\tto a default maximum of 255. \n\tPokemon become easier to catch as their hit-points decrease.\n\t'''\n\t\n\t#shake check\n\tshake_check = (1048560 / math.sqrt(math.sqrt(16711680 / chance))) / 8\n\t'''\n\tThis algorithm is weird. As far as I know the numbers are arbitrary.\n\tI modified it slightly because it was generating a ridiculously large number that would\n\tresult in a 0% catch rate. I don't know how I broke it but dividing the number by 8\n\tresulted in a reasonable number for the scope of this program.\n\t'''\n\tcheck1 = random.randint(0, 65535)\n\tcheck2 = random.randint(0, 65535)\n\t'''\n\tIn the original games, there's this thing called shake check. 4 random numbers between \n\t0 and 65535 are generated and compared to the number generated in the shake_check algorithm.\n\tif these four numbers are all greater than the shake_check number, the Pokemon is caught. \n\tI modified this mechanic by changing it so there were only 2 random numbers to compare because\n\totherwise the probability of catching a wild pokemon was just way too low. This probably \n\twouldn't have been an issue if I could figure out how I broke the shake_check algorithm.\n\t'''\n\t\n\tcatch = False\n\t\t\n\tif check1 > shake_check and check2 > shake_check:\n\t\tcatch = True\n\t\n\treturn catch\n\t\ndef show_list(player_pokemon_list, player_pokemon_count):\n\t'''\n\tBecause I'm really bad at For loops, this function uses a conditional based on the number\n\tof Pokemon the player has to display the stats of each Pokemon with a number in front of it.\n\tthis could be much more elegant but it gets the job done. For that reason, I had to limit \n\tthe number of Pokemon a player could have to six because anything more than that would be \n\tridiculous to type out this way. (It still works out because in the original games you can\n\tonly have six Pokemon in your party at a time anyway).\n\t'''\n\tif player_pokemon_count == 1:\n\t\tprint(\"1.\", player_pokemon_list[0], \"\\n\")\n\telif player_pokemon_count == 2:\n\t\tprint(\"1.\", player_pokemon_list[0], \"\\n\" )\n\t\tprint(\"2.\", player_pokemon_list[1], \"\\n\")\n\telif player_pokemon_count == 3:\n\t\tprint(\"1.\", player_pokemon_list[0], \"\\n\")\n\t\tprint(\"2.\", player_pokemon_list[1], \"\\n\")\n\t\tprint(\"3.\", player_pokemon_list[2], \"\\n\")\n\telif player_pokemon_count == 4:\n\t\tprint(\"1.\", player_pokemon_list[0], \"\\n\")\n\t\tprint(\"2.\", player_pokemon_list[1], \"\\n\")\n\t\tprint(\"3.\", player_pokemon_list[2], \"\\n\")\n\t\tprint(\"4.\", player_pokemon_list[3], \"\\n\")\n\telif player_pokemon_count == 5:\n\t\tprint(\"1.\", player_pokemon_list[0], \"\\n\")\n\t\tprint(\"2.\", player_pokemon_list[1], \"\\n\")\n\t\tprint(\"3.\", player_pokemon_list[2], \"\\n\")\n\t\tprint(\"4.\", player_pokemon_list[3], \"\\n\")\n\t\tprint(\"5.\", player_pokemon_list[4], \"\\n\")\n\telse:\n\t\tprint(\"1.\", player_pokemon_list[0], \"\\n\")\n\t\tprint(\"2.\", player_pokemon_list[1], \"\\n\")\n\t\tprint(\"3.\", player_pokemon_list[2], \"\\n\")\n\t\tprint(\"4.\", player_pokemon_list[3], \"\\n\")\n\t\tprint(\"5.\", player_pokemon_list[4], \"\\n\")\n\t\tprint(\"6.\", player_pokemon_list[5], \"\\n\")\n\t\n#the game begins!\ndef main():\n\tplayer = input(\"What is your name? \")\n\tprint(\"Welcome to the world of Pokemon,\", player, \"!\")\n\tprint(\"\\nPlease choose a Pokemon!\")\n\tprint(\"\\t1. Bulbasaur\")\n\tprint(\"\\t2. Charmander\")\n\tprint(\"\\t3. Squirtle\")\n\tprint(\"\\t4. Pikachu\")\n\tprint(\"\\t5. Eevee\")\n\tprint(\"\\t6. Random\")\n\tchoice = int(input(\"Enter a number to choose: \"))\n\tif choice == 6:\n\t\trchoice = random.randint(1, 5)\n\t\tplayer_poke = generatePokemon(rchoice)\n\telse:\n\t\tplayer_poke = generatePokemon(choice)\n\tprint(\"\\nYou picked...\", player_poke.name, \"!\\n\")\n\tprint(player_poke)\n\tprint(\"\\n==========\\n\")\n\tplayer_pokemon_count = 1\n\tplayer_poke_list = [player_poke]\n\t\n\t#main menu\n\tquit = False\n\twhile quit != True:\n\t\tprint(\"What would you like to do?\")\n\t\tprint(\"\\t1. Battle!\")\n\t\tprint(\"\\t2. View Pokemon\")\n\t\tprint(\"\\t3. Heal Pokemon\")\n\t\tprint(\"\\t4. Quit\")\n\t\twhatDo_choice = int(input(\"Enter a number to choose: \"))\n\t\t\n\t\tif whatDo_choice == 1: #Battle!\n\t\t\tif player_poke_list[0].hit_points == 0:\n\t\t\t\tprint(player_poke_list[0].name, \"is unable to battle! Please heal your Pokemon!\")\n\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\telse:\n\t\t\t\tprint(\"Let's Battle!\")\n\t\t\t\t#begins battle with wild Pokemon\n\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\n\t\t\t\twild_poke_gen = random.randint(1, 5)\n\t\t\t\t\t#generates random number for the generatePokemon function\n\t\t\t\twild_pokemon = generatePokemon(wild_poke_gen)\n\t\t\t\t\t#declares the new Pokemon class instance based on the results of wild_poke_gen\n\t\t\t\t\n\t\t\t\tprint(\"A wild\", wild_pokemon.name, \"has appeared!\")\n\t\t\t\twild_pokemon.wild_name()\n\t\t\t\tprint(player, \"sends out\", player_poke_list[0].name, \"!\")\n\t\t\t\t\n\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\tplayer_poke_list[0].show_hit_points()\n\t\t\t\twild_pokemon.show_hit_points()\n\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\n\t\t\t\tfainted = False\n\t\t\t\tend_battle = False\n\t\t\t\t\n\t\t\t\t#the battle loop\n\t\t\t\twhile fainted != True and end_battle != True:\n\t\t\t\t\tprint(\"What will\", player_poke_list[0].name, \"do?\")\n\t\t\t\t\tprint(\"\\t1. Fight! \\n\\t2. Catch! \\n\\t3. Run!\")\n\t\t\t\t\tbattle_choice = int(input(\"Enter a number to choose: \"))\n\t\t\t\t\tif battle_choice == 1: #Fight!\n\t\t\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\t\tprint(\"Which move will\", player_poke_list[0].name, \"use?\")\n\t\t\t\t\t\tprint(\"\\t1.\", player_poke_list[0].moves_list[0].name, \"(Type:\", player_poke_list[0].moves_list[0].type + \")\", \"\\n\\t2.\", player_poke_list[0].moves_list[1].name, \"(Type:\", player_poke_list[0].moves_list[1].type + \")\")\n\t\t\t\t\t\t\t#Displays the moves list of the player's active Pokemon\n\t\t\t\t\t\tmove_choice = int(input(\"Enter a number to choose: \"))\n\t\t\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\t\t\n\t\t\t\t\t\t#The faster Pokemon always moves first, then the other Pokemon attacks, provided\n\t\t\t\t\t\t#it didn't faint already\n\t\t\t\t\t\tif player_poke_list[0].speed >= wild_pokemon.speed:\n\t\t\t\t\t\t#player Pokemon moves first\n\t\t\t\t\t\t\tplayer_poke_list[0].useMove(player_poke_list[0].moves_list[move_choice - 1], wild_pokemon)\n\t\t\t\t\t\t\tif wild_pokemon.hit_points == 0:\n\t\t\t\t\t\t\t\tfainted = True\n\t\t\t\t\t\t\tif fainted != True:\n\t\t\t\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\t\t\t\twild_pokemon.useMove(wild_pokemon.moves_list[random.randint(0, 1)], player_poke_list[0])\n\t\t\t\t\t\t\t\tif player_poke_list[0].hit_points == 0:\n\t\t\t\t\t\t\t\t\tfainted = True\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t#wild Pokemon moves first\n\t\t\t\t\t\t\twild_pokemon.useMove(wild_pokemon.moves_list[random.randint(0, 1)], player_poke_list[0])\n\t\t\t\t\t\t\tif player_poke_list[0].hit_points == 0:\n\t\t\t\t\t\t\t\tfainted = True\n\t\t\t\t\t\t\tif fainted != True:\n\t\t\t\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\t\t\t\tplayer_poke_list[0].useMove(player_poke_list[0].moves_list[move_choice - 1], wild_pokemon)\n\t\t\t\t\t\t\t\tif wild_pokemon.hit_points == 0:\n\t\t\t\t\t\t\t\t\tfainted = True\n\t\t\t\t\t\t\n\t\t\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\t\tplayer_poke_list[0].show_hit_points()\n\t\t\t\t\t\twild_pokemon.show_hit_points()\n\t\t\t\t\t\tinput()\n\t\t\t\t\t\n\t\t\t\t\tif battle_choice == 2: #Catch!\n\t\t\t\t\t\tif player_pokemon_count >= 6:\n\t\t\t\t\t\t\t#limits the amount of Pokemon you can have to 6, returns to the Battle menu\n\t\t\t\t\t\t\tprint(player, \"has too many Pokemon!\")\n\t\t\t\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\t\t\tprint(player, \"uses a Pokeball!\")\n\t\t\t\t\t\t\tcaught = catch_pokemon(wild_pokemon)\n\t\t\t\t\t\t\t#when attempting to catch a wild Pokemon, the capture attempt is the first thing that\n\t\t\t\t\t\t\t#happens during the turn. If the capture attempt is successful, the battle ends. If it\n\t\t\t\t\t\t\t#is unsuccessful, the wild Pokemon attacks your Pokemon like normal\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tif caught == True:\n\t\t\t\t\t\t\t#capture is successful\n\t\t\t\t\t\t\t\twild_pokemon.normal_name()\n\t\t\t\t\t\t\t\tprint(wild_pokemon.name, \"was caught!\")\n\t\t\t\t\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t#stores the information of the wild Pokemon to create a new Pokemon instance using those same values\n\t\t\t\t\t\t\t\t#to place in the player's party (player_poke_list)\n\t\t\t\t\t\t\t\ttemp_name = wild_pokemon.name\n\t\t\t\t\t\t\t\ttemp_type = wild_pokemon.type\n\t\t\t\t\t\t\t\ttemp_hp = wild_pokemon.max_hit_points\n\t\t\t\t\t\t\t\ttemp_attack = wild_pokemon.attack\n\t\t\t\t\t\t\t\ttemp_defense = wild_pokemon.defense\n\t\t\t\t\t\t\t\ttemp_speed = wild_pokemon.speed\n\t\t\t\t\t\t\t\ttemp_moves = wild_pokemon.moves_list\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tend_battle = True\n\t\t\t\t\t\t\t\tplayer_pokemon_count = player_pokemon_count + 1 \n\t\t\t\t\t\t\t\t#increases the number of Pokemon the player has by 1\n\t\t\t\t\t\t\t\tplayer_poke2 = Pokemon(temp_name, temp_type, temp_hp, temp_attack, temp_defense, temp_speed, temp_moves)\n\t\t\t\t\t\t\t\t\t#creates a new Pokemon instance using the previously stored stats\n\t\t\t\t\t\t\t\tplayer_poke_list.append(player_poke2)\n\t\t\t\t\t\t\t\t\t#appends the newly created Pokemon instance to player_poke_list\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t#unsuccessful capture\n\t\t\t\t\t\t\t\tmessage_num = random.randint(1, 3)\n\t\t\t\t\t\t\t\tif message_num == 1:\n\t\t\t\t\t\t\t\t\tprint(\"The Pokemon broke free!\\n\")\n\t\t\t\t\t\t\t\tif message_num == 2:\n\t\t\t\t\t\t\t\t\tprint(\"So close!\\n\")\n\t\t\t\t\t\t\t\tif message_num == 3:\n\t\t\t\t\t\t\t\t\tprint(\"It was almost caught!\\n\")\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t#wild Pokemon attacks your Pokemon\n\t\t\t\t\t\t\t\twild_pokemon.useMove(wild_pokemon.moves_list[random.randint(0, 1)], player_poke_list[0])\n\t\t\t\t\t\t\t\tif player_poke_list[0].hit_points == 0:\n\t\t\t\t\t\t\t\t\tfainted = True\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\t\t\t\tplayer_poke_list[0].show_hit_points()\n\t\t\t\t\t\t\t\twild_pokemon.show_hit_points()\n\t\t\t\t\t\t\t\tinput()\n\t\t\t\t\t\t\t\n\t\t\t\t\tif battle_choice == 3: #Run!\n\t\t\t\t\t\tprint(\"Got away safely!\")\n\t\t\t\t\t\tprint(\"\\n==========\\n\")\n\t\t\t\t\t\tend_battle = True\n\t\t\t\t\t\n\t\t\t\n\t\telif whatDo_choice == 2: #View Pokemon\n\t\t\tprint(\"\\n==========\\n\")\n\t\t\tshow_list(player_poke_list, player_pokemon_count)\n\t\t\t\t#displays the Pokemon instances in player_poke_list using the show_list function\n\t\t\tprint(\"\\n==========\\n\")\n\t\t\tswitch_yn = input(\"Switch active Pokemon? y|n: \")\n\t\t\t\t#Gives the option to switch the active Pokemon with a new Pokemon in player_poke_list\n\t\t\tif switch_yn == \"y\":\n\t\t\t\tswitch_num = int(input(\"Choose a new active Pokemon: \"))\n\t\t\t\t#switches the positions of the values in the list\n\t\t\t\ttmp = player_poke_list[0]\n\t\t\t\tplayer_poke_list[0] = player_poke_list[switch_num - 1]\n\t\t\t\tplayer_poke_list[switch_num - 1] = tmp\n\t\t\t\tprint(\"\\n\" + player_poke_list[0].name + \" is now the active Pokemon!\")\n\t\t\tprint(\"\\n==========\\n\")\n\t\t\n\t\telif whatDo_choice == 3: #Heal Pokemon\n\t\t\t#Calls the heal function to restore the hit-points of the active Pokemon \n\t\t\tprint(\"\\n\")\n\t\t\tplayer_poke_list[0].heal()\n\t\t\tprint(\"\\n==========\\n\")\n\t\t\n\t\telif whatDo_choice == 4: #Quit\n\t\t\t#Ends the game\n\t\t\tprint(\"Goodbye!\")\n\t\t\tquit = True\n\t\nif __name__ == '__main__':\n main()\n","sub_path":"LING 508/pokemon.py","file_name":"pokemon.py","file_ext":"py","file_size_in_byte":22120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"136829092","text":"import numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Activation\nimport matplotlib.pyplot as plt\ninputfile = './data/data1_GM11.xls'\n\ndata = pd.read_excel(inputfile)\nfeature = ['x1', 'x2', 'x3', 'x4', 'x5', 'x7']\ndata_train = data.loc[range(1994, 2014)].copy()\ndata_mean = data_train.mean()\ndata_std = data_train.std()\ndata_train = (data_train - data_mean)/data_std #数据标准化,会对每一个特征的每一行执行标准化\n#特征数据\nx_train = np.array(data_train[feature])\n#标签\ny_train = np.array(data_train['y'])\n\nmodel = Sequential()\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(1))\nmodel.compile(loss='mean_squared_error', optimizer='adam')\nmodel.fit(x_train, y_train, nb_epoch=10000, batch_size=16)\n\n#预测,并还原结果。\nx = ((data[feature] - data_mean[feature])/data_std[feature]).as_matrix()\ndata['y_pred'] = model.predict(x) * data_std['y'] + data_mean['y']\np = data[['y', 'y_pred']].plot(subplots=True, style=['b-o', 'r-*'])\nplt.show()\n\n\n\n","sub_path":"财政收入预测/yuce.py","file_name":"yuce.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"459284927","text":"from camera import Camera\nfrom display import *\n\n\nclass Controls:\n _mouse_force = 1\n _mouse_back_force = -1\n _glut_scroll_up = 3\n _glut_scroll_down = 4\n\n @staticmethod\n def mouse(btn, state, x, y):\n if state != GLUT_DOWN:\n Camera.disable_rotation()\n return\n\n if btn == GLUT_LEFT_BUTTON:\n Camera.enable_rotation()\n Camera.update(x, y)\n return\n\n Camera.disable_rotation()\n\n if btn == Controls._glut_scroll_up:\n Camera.scroll(Controls._mouse_back_force)\n elif btn == Controls._glut_scroll_down:\n Camera.scroll(Controls._mouse_force)\n\n glutPostRedisplay()\n\n @staticmethod\n def motion(x, y):\n Camera.move_to(x, y)\n","sub_path":"shadows/controls.py","file_name":"controls.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"636083627","text":"# Input: numbers = [2,7,11,15], target = 9\n# Output: [1,2]\n# Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.\nclass Solution(object):\n def twoSum(self, numbers, target):\n \"\"\"\n :type numbers: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n dic = {}\n for i in range(len(numbers)):\n if numbers[i] in dic:\n return [dic[numbers[i]]+1, i+1]\n else:\n dic[target - numbers[i]] = i ","sub_path":"two_sum_ii.py","file_name":"two_sum_ii.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"331991026","text":"import pandas as pd\nfrom wh_parser.util import convert_freq_to_pd\n\nmethods_map = {}\n\n\ndef add_methods(name=''):\n \"\"\"\n 注册函数\n :param name:\n :return:\n \"\"\"\n\n def wrapper(func):\n methods_map[name] = func\n return func\n\n return wrapper\n\n\n@add_methods('default')\ndef default_process(df, freq):\n \"\"\"\n 默认的转换频率的方式\n :param df:\n :param freq:\n :return:\n \"\"\"\n # 删除夜盘的数据\n if freq == '1m':\n return df\n\n df = df.resample(convert_freq_to_pd(freq), label='right', closed='right')\n res = pd.DataFrame({\n 'close': df.close.last(),\n 'open': df.open.first(),\n 'high': df.high.max(),\n 'low': df.high.min(),\n 'volume': df.volume.sum(),\n 'open_interest': df.open_interest.last(),\n 'total_turnover': df.total_turnover.sum(),\n 'order_book_id': df.order_book_id.last(),\n }\n )\n res = res.dropna(how='any', thresh=3)\n return res\n","sub_path":"vnpy/app/wh_strategy/wh_parser/clean2cache_pipeline/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"463515144","text":"from collections import defaultdict\nfrom gensim import corpora, models, similarities\n\nwith open('./text_not_remove_stop_word.txt') as f:\n mylist = f.read().splitlines()\n\nwith open('./stopwords.txt') as f:\n stop_words = f.read().splitlines()\n############\n'''Remove [] and replace _'''\n'''\nmylist = [line.split(' ') for line in mylist]\nremoved_b_list = []\n\nfor s in mylist:\n temp_arr = []\n word_more_than_2 = []\n global c1\n c1 = 0\n global c2\n c2 = 0\n for item in s:\n c1 += item.count('[')\n c2 += item.count(']')\n if ((c1 + c2) == 2) and (len(word_more_than_2) == 0):\n temp_arr.append(item.replace('[','').replace(']',''))\n c1 = c2 = 0\n elif ((c1 + c2) == 2) and (len(word_more_than_2) != 0):\n temp_s = \"\"\n for i in word_more_than_2:\n temp_s += i + \"_\"\n temp_s += item\n temp_arr.append(temp_s.replace('[','').replace(']',''))\n c1 = c2 = 0\n word_more_than_2 = []\n elif (c1 + c2) < 2:\n word_more_than_2.append(item)\n removed_b_list.append(temp_arr)\n\nremoved_b_list = [' '.join(s) for s in removed_b_list]\n\nremoved_b_list = [s.split(' ') for s in removed_b_list]\n\nmylist = removed_b_list\n'''\n############\ntexts = [[word for word in doc.split(' ') if word not in stop_words]\n for doc in mylist]\n\nfrequency = defaultdict(int)\nfor text in texts:\n for token in text:\n frequency[token] += 1\n\ntexts = [[token for token in text if frequency[token] > 1]\n for text in texts]\n\n'''remove empty list'''\ntexts = [x for x in texts if x]\n\n#for t in texts:\n# print(t)\n\ndictionary = corpora.Dictionary(texts)\ndictionary.save('./word_dict.dict') # store the dictionary, for future reference\n\n#print(dictionary)\n\n#print(dictionary.token2id)\n\ncorpus = [dictionary.doc2bow(text) for text in texts]\n\ncorpora.MmCorpus.serialize('./dict/corpus.mm', corpus)\n\n#print(corpus)\n","sub_path":"remove_stopword.py","file_name":"remove_stopword.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"200529314","text":"from numpy import radians\n\n\ndef sub (vector1, vector2):\n newVector = []\n if len(vector1) != len(vector2):\n return ArithmeticError(\"Las matrices no son del mismo tamaño\")\n else:\n for x in range(len(vector1)):\n newVector.append(vector1[x]-vector2[x])\n return newVector\n\n\ndef punto (vector1, vector2):\n if len(vector1) != len(vector2):\n return ArithmeticError(\"Las matrices no son del mismo tamaño\")\n else: \n total = 0 \n for x in range(len(vector1)):\n total += vector1[x] * vector2[x]\n return total\n\n\ndef cross(vector1, vector2):\n if len(vector1) == 3 & len(vector2) == 3:\n i = vector1[1]*vector2[2] - vector2[1]*vector1[2]\n j = vector1[0]*vector2[2] - vector2[0]*vector1[2]\n k = vector1[0]*vector2[1] - vector2[0]*vector1[1]\n return [i, -j, k]\n if len(vector1) == 2 & len(vector2) == 2:\n\n k = vector1[0]*vector2[1] - vector2[0]*vector1[1]\n return [k]\n else:\n\n return ArithmeticError(\"No puede hacerse\")\n\n\ndef Deg2rad(data):\n pi = 22/7\n deg = data \n radian = deg * (pi/180)\n return radian\n\ndef Pi ():\n return 22/7 \n\n\ndef Matrix(data):\n return [[data]]\n\n\n","sub_path":"MylibMath.py","file_name":"MylibMath.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"234968366","text":"import pygame\r\nfrom pygame.locals import *\r\nfrom filepath import *\r\nfrom font import *\r\n \r\n# Define some colors\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\nGOLD = (255,223,0)\r\n \r\npygame.init()\r\n \r\nd_is_for_dogecoin = pygame.mixer.music.load(\"sounds/dogecoinsong.mp3\")\r\npygame.mixer.music.play(loops=-1)\r\npygame.mixer.music.set_volume(0.1)\r\n\r\n# Set the width and height of the screen [width, height]\r\nsize = (1280, 720)\r\nscreen = pygame.display.set_mode(size)\r\n \r\npygame.display.set_caption(\"Meme Clicker\")\r\n \r\n# Loop until the user clicks the close button.\r\ndone = False\r\n \r\n# Used to manage how fast the screen updates\r\nclock = pygame.time.Clock()\r\n\r\n#Init surfaces\r\nsurf = pygame.display.set_mode((1280,720))\r\n \r\ndoge_count = 0\r\nmax_doge_count = 150\r\nclicks = 0\r\nr = 255\r\ng = b = 0\r\n\r\n# -------- Main Program Loop -----------\r\nwhile not done:\r\n\r\n if doge_count >= max_doge_count:\r\n doge_count = 0\r\n max_doge_count *= 2.5\r\n max_doge_count = int(max_doge_count)\r\n\r\n if(r > 0 and b == 0):\r\n r -= 3\r\n g += 3\r\n if(g > 0 and r == 0):\r\n g -= 3\r\n b += 3\r\n if(b > 0 and g == 0):\r\n r += 3\r\n b -= 3\r\n\r\n\r\n # --- Main event loop\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == K_SPACE:\r\n doge_count = 150\r\n if event.type == MOUSEBUTTONDOWN:\r\n clicks += 1\r\n doge_count += 1\r\n \r\n # --- Game logic should go here\r\n \r\n # --- Screen-clearing code goes here\r\n \r\n # Here, we clear the screen to white. Don't put other drawing commands\r\n # above this, or they will be erased with this command.\r\n \r\n # If you want a background image, replace this clear with blit'ing the\r\n # background image.\r\n screen.fill(WHITE)\r\n # pygame.draw.rect(surf, (0,0,0,0), pygame.Rect(1050,20,200,50))\r\n bg = pygame.image.load(PATH_bg).convert()\r\n bg = pygame.transform.scale(bg, (1280, 720))\r\n surf.blit(bg, (0,0))\r\n\r\n pygame.draw.rect(surf, GOLD, pygame.Rect(1050, 20, doge_count * 150 // max_doge_count, 30))\r\n\r\n goldbarimg = pygame.image.load(PATH_bar).convert_alpha()\r\n surf.blit(goldbarimg, (1050,20))\r\n\r\n dogecoin = pygame.image.load(PATH_dogecoin).convert_alpha()\r\n dogecoin = pygame.transform.scale(dogecoin, (40,40))\r\n surf.blit(dogecoin, (1210, 15))\r\n \r\n # titleimg = pygame.image.load(PATH_title).convert_alpha()\r\n # surf.blit(titleimg, (20,20))\r\n game_name_gui = sketch_font.render(\"Meme Clicker\", True, (0, 0, 0))\r\n screen.blit(game_name_gui,(20, 30 ))\r\n click_count_gui = sketch_font.render(\"Clicks : \" + str(clicks), True, (0,0,0))\r\n screen.blit(click_count_gui, (20,60))\r\n\r\n click_count_gui = sketch_font_20.render(str(doge_count) + \" / \" + str(max_doge_count), True, (0,0,0))\r\n screen.blit(click_count_gui, (1100,26))\r\n\r\n pygame.draw.rect(surf, (r,g,b), pygame.Rect(1018, 68, 254, 624), border_radius = 10)\r\n pygame.draw.rect(surf, (220,220,220), pygame.Rect(1020, 70, 250, 620), border_radius = 10)\r\n \r\n game_name_gui = sketch_font.render(\"Upgrades\", True, (r, g, b))\r\n screen.blit(game_name_gui,(1030, 80 ))\r\n\r\n gpu = pygame.image.load(PATH_gpu).convert_alpha()\r\n gpu = pygame.transform.scale(gpu, (200,100))\r\n surf.blit(gpu, (1050, 150))\r\n\r\n piss = pygame.image.load(PATH_piss_drawer).convert_alpha()\r\n piss = pygame.transform.scale(piss, (200,100))\r\n surf.blit(piss, (1050, 270))\r\n \r\n \r\n # --- Drawing code should go here\r\n \r\n # --- Go ahead and update the screen with what we've drawn.\r\n pygame.display.flip()\r\n \r\n # --- Limit to 60 frames per second\r\n clock.tick(60)\r\n \r\n# Close the window and quit.\r\npygame.quit()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"314707681","text":"\"\"\"Azure IoT Hub Device SDK Authentication\n\nThis package provides authentication-related functionality for use with the\nAzure IoT Hub Device SDK.\n\"\"\"\n\nfrom .authentication_provider_factory import (\n from_connection_string,\n from_shared_access_signature,\n from_environment,\n)\n\n__all__ = [\"from_connection_string\", \"from_shared_access_signature\", \"from_environment\"]\n","sub_path":"azure-iot-device/azure/iot/device/iothub/auth/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"456614643","text":"from socket import *\nimport threading\nimport time\n\n\ndef send(sock):\n while True:\n sendData = input('>>>')\n sock.sendall(sendData.encode('utf-8'))\n\n\ndef receive(sock):\n while True:\n recvData = sock.recv(1024)\n print('opponent: ', recvData.decode('utf-8'))\n\n\nport = 8080\n\nserverSock = socket(AF_INET, SOCK_STREAM)\nserverSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\nserverSock.bind(('', port))\n\nserverSock.listen(1)\n\nconnectionSock, addr = serverSock.accept()\n\nsender = threading.Thread(target=send, args=(connectionSock,))\nreceiver = threading.Thread(target=receive, args=(connectionSock, ))\n\nsender.start()\nreceiver.start()\n\nwhile True:\n time.sleep(1)\n","sub_path":"socket/chat_server.py","file_name":"chat_server.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"72910434","text":"from rtamt.semantics.abstract_dense_time_online_operation import AbstractDenseTimeOnlineOperation\nimport rtamt.semantics.stl.dense_time.online.intersection as intersect\n\n\nclass OnceTimedOperation(AbstractDenseTimeOnlineOperation):\n def __init__(self, begin, end):\n self.prev = []\n self.residual_start = -float(\"inf\")\n self.max = - float(\"inf\")\n self.begin = begin\n self.end = end\n\n def reset(self):\n pass\n\n def update(self, sample, *args, **kargs):\n # get inputs\n sample_result = []\n out = self.prev\n self.prev = []\n\n begin = self.begin\n end = self.end\n\n if sample:\n # update when the residuals start in this iteration\n self.residual_start = sample[len(sample) - 1][0] + begin\n if out:\n # update the last previous sample with current knowledge\n last_prev = out[len(out) - 1]\n first_now = sample[0]\n del(out[len(out) - 1])\n out.append((last_prev[0], first_now[0] + end, last_prev[2]))\n\n i = 1\n while len(sample) >= i:\n if i == len(sample):\n b = (sample[i - 1][0] + begin, sample[i-1][0] + end, sample[i - 1][1])\n else:\n b = (sample[i - 1][0] + begin, sample[i][0] + end, sample[i - 1][1])\n\n if not out:\n out.append(b)\n else:\n a = out[len(out) - 1]\n while (a[2] < b[2]) and (b[0] < a[0]):\n del (out[len(out) - 1])\n a = out[len(out) - 1]\n if not intersect.intersects(a[0], a[1], b[0], b[1]):\n out.append(b)\n else:\n if a[2] >= b[2]:\n out.append((a[1], b[1], b[2]))\n else:\n del (out[len(out) - 1])\n out.append((a[0], b[0], a[2]))\n out.append((b[0], b[1], b[2]))\n i = i + 1\n\n prev = float(\"nan\")\n\n for i, b in enumerate(out):\n if b[1] <= self.residual_start:\n if b[2] != prev or i == len(out) - 1:\n sample_result.append([b[0], b[2]])\n elif b[0] < self.residual_start < b[1]:\n if b[2] != prev or i == len(out) - 1:\n sample_result.append([b[0], b[2]])\n self.prev.append((self.residual_start, b[1], b[2]))\n else:\n self.prev.append(b)\n\n prev = b[2]\n\n return sample_result\n\n def update_final(self, sample, *args, **kargs):\n sample_result = self.update(sample, *args, **kargs)\n\n out = self.prev\n\n for i, b in enumerate(out):\n sample_result.append([b[0], b[2]])\n return sample_result\n","sub_path":"rtamt/semantics/stl/dense_time/online/once_timed_operation.py","file_name":"once_timed_operation.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"155889970","text":"__author__ = 'ArseneLupin'\n\nimport csv\nimport featurescom\nimport source_var\nimport timeit\n\ndef threshold_function(array, dest, runtime_path):\n\n samp_rate = source_var.sampling_rate()\n pre_impact_win = samp_rate - 1\n post_impact_win = samp_rate * 11\n destFile = dest\n featureRes=[]\n runtime=[]\n outF = open(destFile, \"w\")\n csvWriter = csv.writer(outF, delimiter='\\t')\n\n print('Calculate Features')\n #print(samp_rate)\n #print(len(array))\n\n # i is the active state point in the window\n for i in range(pre_impact_win, len(array) - post_impact_win):\n\n data = array[i]\n #if data[9] == 1:\n\n\n act_state = data[9]\n microanno = data[8]\n\n dataFeatures = array[i - pre_impact_win : i + post_impact_win]\n x = timeit.default_timer()\n featureRes = featurescom.featurescom(dataFeatures, microanno,act_state)\n y = timeit.default_timer()\n\n run = y-x\n runtime.append(run)\n #print runtime\n csvWriter.writerow(featureRes)\n\n write_runtime(runtime, runtime_path)\n print('Finish Calculate Features')\n\n\ndef write_runtime(array_run, dest_file):\n outF = open(dest_file, \"w\")\n csvWriter = csv.writer(outF)\n\n for i in range(len(array_run)):\n runtime = array_run[i]\n csvWriter.writerow([runtime])\n\n\n\n\n####################################### James Brusey's Code ##\n#from collections import namedtuple #\n#import copy #\n#MyTuple = namedtuple('MyTuple', 'active, value') #\n #\n#def grab_windows_from_stream(src, pre_win, post_win): #\n #win = [] #\n #for tup in src: #\n #if len(win) >= pre_win + post_win: #\n #win.pop(0) #\n #win.append(tup) #\n\n #if len(win) == pre_win + post_win:\n #if win[pre_win].active:\n #yield copy.deepcopy(win)\n\n \n","sub_path":"src/threshold_function.py","file_name":"threshold_function.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"61890481","text":"# This file is part of the MapProxy project.\n# Copyright (C) 2010, 2011 Omniscale \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom mapproxy.util.times import timestamp_from_isodate\n\nimport pytest\n\n\ndef test_timestamp_from_isodate():\n ts = timestamp_from_isodate(\"2009-06-09T10:57:00\")\n assert (1244537820.0 - 14 * 3600) < ts < (1244537820.0 + 14 * 3600)\n\n with pytest.raises(ValueError):\n timestamp_from_isodate(\"2009-06-09T10:57\")\n","sub_path":"mapproxy/test/unit/test_times.py","file_name":"test_times.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"39069599","text":"#!/usr/bin/env python3\n\"\"\" Simple pagination \"\"\"\n\nimport csv\nimport math\nfrom typing import List, Dict, Any\n\nindex_range = __import__('0-simple_helper_function').index_range\n\n\nclass Server:\n \"\"\"Server class to paginate a database of popular baby names.\n \"\"\"\n DATA_FILE = \"Popular_Baby_Names.csv\"\n\n def __init__(self):\n self.__dataset = None\n\n def dataset(self) -> List[List]:\n \"\"\"Cached dataset\n \"\"\"\n if self.__dataset is None:\n with open(self.DATA_FILE) as f:\n reader = csv.reader(f)\n dataset = [row for row in reader]\n self.__dataset = dataset[1:]\n\n return self.__dataset\n\n def get_page(self, page: int = 1, page_size: int = 10) -> List[List]:\n \"\"\"\n - Use assert to verify that both arguments\n are integers greater than 0.\n\n - Use index_range to find the correct indexes to paginate\n the dataset correctly and return the appropriate page\n of the dataset (i.e. the correct list of rows).\n \"\"\"\n assert type(page) == int\n assert page > 0\n assert type(page_size) == int\n assert page_size > 0\n\n pages, page_sizes = index_range(page, page_size)\n csv = []\n if pages >= len(self.dataset()):\n return csv\n csv = self.dataset()\n return csv[pages:page_sizes]\n\n def get_hyper(self, page: int = 1, page_size: int = 10) -> Dict[str, Any]:\n \"\"\"\n returns a dictionary containing the following key-value pairs\n \"\"\"\n size_all_pages = math.ceil(len(self.dataset()) / page_size)\n next_page = page + 1 if page + 1 < size_all_pages else None\n prev_page = page - 1 if page > 1 else None\n data = {'page_size': len(self.get_page(page, page_size)),\n 'page': page,\n 'data': self.get_page(page, page_size),\n 'next_page': next_page,\n 'prev_page': prev_page,\n 'total_pages': size_all_pages}\n return data\n","sub_path":"0x04-pagination/2-hypermedia_pagination.py","file_name":"2-hypermedia_pagination.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"493208391","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nfrom leshilive.items import LeshiliveItem\n\n\nclass LeshitvSpider(scrapy.Spider):\n name = 'leshitv'\n allowed_domains = ['letv.com']\n page = 1\n url = 'http://dynamic.live.app.m.letv.com/android/dynamic.php?luamod=main&mod=live&ctl=liveHuya&act=channelList&pcode=010210000&version=7.13&channelId=2168&pages=' + str(\n page) + '&country=CN&provinceid=1&districtid=9&citylevel=1&location=%E5%8C%97%E4%BA%AC%E5%B8%82%7C%E6%9C%9D%E9%98%B3%E5%8C%BA&lang=chs®ion=CN'\n start_urls = [url]\n\n def parse(self, response):\n content = json.loads(response.text, encoding='utf-8')\n item = LeshiliveItem()\n content1 = content['body']['result']\n for ev in content1:\n item['nick_name'] = ev.get('nick')\n # 主播的照片链接\n item['image_link'] = ev.get('screenshot')\n # 房间\n item['data_link'] = ev.get('liveUrl')\n yield item\n if self.page < 10:\n self.page += 1\n self.url = 'http://dynamic.live.app.m.letv.com/android/dynamic.php?luamod=main&mod=live&ctl=liveHuya&act=channelList&pcode=010210000&version=7.13&channelId=2168&pages=' + str(\n self.page) + '&country=CN&provinceid=1&districtid=9&citylevel=1&location=%E5%8C%97%E4%BA%AC%E5%B8%82%7C%E6%9C%9D%E9%98%B3%E5%8C%BA&lang=chs®ion=CN'\n yield scrapy.Request(self.url, callback=self.parse)","sub_path":"spider/0516/leshilive/leshilive/spiders/leshitv.py","file_name":"leshitv.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"412674997","text":"import pandas as pd\nfrom sklearn.base import BaseEstimator, ClassifierMixin, clone\n\nclass OneByOneClassifier(BaseEstimator,ClassifierMixin):\n \"\"\"Class to fit against each output variable in a DataFrame separately\"\"\"\n def __init__(self, classifier):\n self.classifer=classifier\n self.classifiers=None\n self.columns=None\n\n def fit(self, X, y):\n self.columns=y.columns\n self.classifiers={col:clone(self.classifer) for col in self.columns}\n\n for col in self.columns:\n y_col=y[col]\n classifier=self.classifiers[col]\n classifier.fit(X, y_col)\n\n def predict(self,X):\n classifiers=self.classifiers\n predictions={col: classifiers[col].predict(X) for col in self.columns}\n return pd.DataFrame(predictions)\n\n def predict_proba(self,X):\n classifiers=self.classifiers\n predictions={col: classifiers[col].predict_proba(X)[:,1] for col in self.columns}\n return pd.DataFrame(predictions)\n","sub_path":"models/OneByOneClassifier.py","file_name":"OneByOneClassifier.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"330901029","text":"import math\nimport random\nimport networkx as nx\nfrom _NetworKit import PowerlawDegreeSequence, ChungLuGenerator, HyperbolicGenerator\nfrom networkit import nxadapter\n\n\ndef erdos_renyi_graph(n, k, giant=True):\n graph = nx.fast_gnp_random_graph(n, k / (n - 1))\n if giant:\n graph = max(nx.connected_component_subgraphs(graph), key=len)\n\n for i in graph.nodes():\n graph.node[i]['pos'] = (random.random(), random.random())\n multiply_pos(graph, 5000)\n return graph\n\n\ndef hyperbolic_graph(n, k, giant=True):\n nk_graph = HyperbolicGenerator(n, k=k, gamma=2.5, T=0).generate()\n graph = nxadapter.nk2nx(nk_graph)\n if giant:\n graph = max(nx.connected_component_subgraphs(graph), key=len)\n for i in graph.nodes():\n graph.node[i]['pos'] = (random.random(), random.random())\n multiply_pos(graph, 5000)\n return graph\n\n\ndef chung_lu_graph(n, giant=True):\n powerlaw_gen = PowerlawDegreeSequence(3, 50, -2.5)\n powerlaw_gen.run()\n nk_graph = ChungLuGenerator(powerlaw_gen.getDegreeSequence(n)).generate()\n graph = nxadapter.nk2nx(nk_graph)\n if giant:\n graph = max(nx.connected_component_subgraphs(graph), key=len)\n for i in graph.nodes():\n graph.node[i]['pos'] = (random.random(), random.random())\n multiply_pos(graph, 5000)\n return graph\n\n\ndef geometric_graph(n, k, giant=True):\n r = math.sqrt(k / (n * math.pi))\n graph = nx.random_geometric_graph(n, r)\n if giant:\n graph = max(nx.connected_component_subgraphs(graph), key=len)\n multiply_pos(graph, 5000)\n return graph\n\n\ndef multiply_pos(graph, factor):\n for _, node in graph.nodes.items():\n node['pos'] = [factor * node['pos'][0], factor * node['pos'][1]]\n","sub_path":"generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"305969928","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThese are the functions for the force analysis\n\n@author: Wolf\n\"\"\"\nimport numpy as np\nimport scipy.sparse as sp\nimport scipy.sparse.linalg as spl\n\nimport os\n\nfrom scipy.optimize import leastsq\n\ndef load_file(filepath):\n \n data_signal = np.fromfile(filepath, sep = \" \")\n n = data_signal.size # Check the length of data\n data_base = data_signal.reshape((n/2,2)) # Reshape the data to a matrix \n \n data_positon_base = data_base[:,0]\n data_base = data_base[:,1]\n\n # Take the data of move back\n back_index = np.diff(data_positon_base)<0\n back_index = np.append(back_index,back_index[back_index.size-1]) \n \n x = data_positon_base[back_index]\n y = data_base[back_index] \n \n filename = os.path.basename(filepath)\n \n return x, y, filename\n\ndef signal_noise_ratio(path_ref, nn):\n # The inputs are the file path and the number of point to take\n \n data_ref = np.fromfile(path_ref, sep = \" \")\n n = data_ref.size\n data_ref = data_ref.reshape((n/2,2))\n temp_ref = data_ref[:,1]\n temp_ref = temp_ref[n/2-nn:n/2] # The square wave\n\n center = (max(temp_ref)+min(temp_ref))/2\n crest = np.mean(temp_ref[temp_ref>center])\n valley = np.mean(temp_ref[temp_ref=cen_peak-space_peak)&\n (temp_x0<=cen_peak+space_peak)]\n temp_y0_center = temp_y0[(temp_x0>=cen_peak-space_peak)&\n (temp_x0<=cen_peak+space_peak)]\n\n # The intersection of signal and baseline\n temp_x1_center = temp_x1[(temp_x1>=cen_peak-space_peak)&\n (temp_x1<=cen_peak+space_peak)]\n temp_y1_center = temp_y1[(temp_x1>=cen_peak-space_peak)&\n (temp_x1<=cen_peak+space_peak)]\n \n # Take the fitting value for the same x value\n temp_y0_fit = np.interp(temp_x1_center,\n np.flipud(temp_x0_center),np.flipud(temp_y0_center))\n\n # Take the difference to get the signal\n signal_x = temp_x1_center\n signal_y = temp_y1_center - temp_y0_fit\n \n return signal_x, signal_y\n\ndef airPLS(x, lambda_base, order, wep, p, itermax):\n \n # This method needs to cite: \n # Z.-M. Zhang, S. Chen, and Y.-Z. Liang, Baseline correction using adaptive \n # iteratively reweighted penalized least squares. \n # Analyst 135 (5), 1138-1146 (2010).\n \n n = np.size(x)\n wi = np.append(np.arange(np.ceil(n*wep),dtype=int), \n np.arange(np.floor(n-n*wep)-1,n,dtype=int))\n\n D = sp.csc_matrix(np.eye(n))\n for num in range (0,order):\n D = D[1:]-D[:-1]\n \n DD = lambda_base*D.T*D\n \n # Begin the iteration\n w = np.ones(n) # Initial guess\n for jj in range (1,itermax+1):\n \n W = sp.csc_matrix((w,(np.arange(w.size),np.arange(w.size))), \n shape=(w.size,w.size))\n \n C = W+DD \n z =spl.spsolve(C,w*x) \n d = x-z;\n\n dssn = abs(sum(d[d<0]))\n \n if (dssn < 0.001*sum(abs(x))): # problem \n break\n\n w[d>=0] = 0\n w[wi] = p\n w[d<0] = jj*np.exp(abs(d[d<0])/dssn)\n \n xc = x-z \n\n return xc, z\n \ndef bfvar_temp(cut_positions, x, y):\n \n a1 = np.int(np.min(cut_positions))\n a2 = np.int(np.max(cut_positions))\n \n # 20 is the space of points to take. This value can be tuned. \n pts = np.append(np.arange(0,a1,20,dtype=int),\n np.arange(a2,x.size,20,dtype=int))\n\n # Make sure to get the start and end points\n if pts[pts.size-1] != x.size-1:\n pts = np.append(pts,x.size-1)\n \n # Flip the data for the interpolation \n yt = np.interp(np.arange(x.size),pts,y[pts]) \n \n return yt\n\ndef error_bar_ana(index, y):\n \n index_max = np.empty(0) # local max\n index_min = np.empty(0) # local min\n for ii in range(1,index.size-2):\n \n if (y[index[ii]]>y[index[ii-1]])& \\\n (y[index[ii]]>y[index[ii+1]]):\n index_max = np.append(index_max,index[ii])\n elif (y[index[ii]]\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport benchexec.tools.esbmc as esbmc\nfrom benchexec.tools.template import ToolNotFoundException\n\n\nclass Tool(esbmc.Tool):\n \"\"\"\n This class serves as tool adaptor for FuSeBMC (https://github.com/kaled-alshmrany/FuSeBMC)\n \"\"\"\n\n REQUIRED_PATHS_TESTCOMP20 = [\"esbmc\", \"esbmc-wrapper.py\", \"my_instrument\"]\n REQUIRED_PATHS_TESTCOMP21 = [\n \"esbmc\",\n \"fusebmc.py\",\n \"FuSeBMC_inustrment/FuSeBMC_inustrment\",\n \"fusebmc_output\",\n \"map2check-fuzzer\",\n ]\n\n def name(self):\n return \"FuSeBMC\"\n\n def executable(self, tool_locator):\n try:\n self._version = 21\n return tool_locator.find_executable(\"fusebmc.py\")\n except ToolNotFoundException:\n self._version = 20\n return super().executable(tool_locator)\n\n def program_files(self, executable):\n \"\"\"\n Determine the file paths to be adopted\n \"\"\"\n if self._version == 20:\n paths = self.REQUIRED_PATHS_TESTCOMP20\n elif self._version > 20:\n paths = self.REQUIRED_PATHS_TESTCOMP21\n return self._program_files_from_executable(executable, paths)\n","sub_path":"benchexec/tools/fusebmc.py","file_name":"fusebmc.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"199284128","text":"from __future__ import print_function\nimport os\nimport json\nimport cPickle\nimport time\nimport torch\nimport torch.nn as nn\nimport utils\nfrom torch.autograd import Variable\n\n\n\n\ndef test(model, test_loader, output, dataroot='data'):\n utils.create_dir(output)\n logger = utils.Logger(os.path.join(output, 'log.txt'))\n model.load_state_dict(torch.load('/media/jry/MyBook/VQA/bottom-up-attention-vqa/saved_models/exp0/model.pth'))\n ans2label_path = os.path.join(dataroot, 'cache', 'trainval_ans2label.pkl')\n label2ans_path = os.path.join(dataroot, 'cache', 'trainval_label2ans.pkl')\n ans2label = cPickle.load(open(ans2label_path, 'rb'))\n label2ans = cPickle.load(open(label2ans_path, 'rb'))\n\n\n result = []\n for i, (qes_ids, img_ids, v, b, q) in enumerate(test_loader):\n v = Variable(v).cuda()\n b = Variable(b).cuda()\n q = Variable(q).cuda()\n\n pred = model(v, b, q, None)\n logits = torch.max(pred, 1)[1].data # argmax\n for qes_id, logit in zip(qes_ids, logits):\n result.append({\n 'answer': label2ans[logit],\n 'question_id': qes_id\n })\n\n outfile = os.path.join(output, 'result.json')\n with open(outfile, 'w') as f:\n json.dump(result, f)\n print('Generated %d outputs, saving to %s' % (len(result), outfile))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"600145284","text":"#!/usr/bin/env python\nimport rospy\nimport json\nimport RPi.GPIO as io\nimport time\nfrom sensor_msgs.msg import Joy\nfrom std_msgs.msg import String\n\n# sudo chmod og+rwx gpio*\n\nio.setwarnings(False)\nio.setmode(io.BOARD)\nio.setup(7, io.OUT)\nio.setup(16, io.OUT)\n\ndrive = io.PWM(7, 50)\ndrive.start(0)\n\nturn = io.PWM(16, 50)\nturn.start(0)\n\ndef callback(data):\n\tdrive_v = data.axes[8] * 3 + 7\n\tturn_v = -2 * data.axes[0] + 7\n\tif abs(drive_v - 7) < 0.1:\n\t\tdrive_v = 0\n\tif abs(turn_v - 7) < 0.1:\n\t\tturn_v = 0\n\tdrive.ChangeDutyCycle(drive_v)\n\tturn.ChangeDutyCycle(turn_v)\n\ndef listener():\n\trospy.init_node('listener', anonymous=True)\n\trospy.Subscriber(\"joy\", Joy, callback, queue_size=1)\n\trospy.spin()\n\nif __name__ == '__main__':\n \tlistener()\n","sub_path":"src/teleop/scripts/teleop.py","file_name":"teleop.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"559805481","text":"\"\"\"\"Migrate contacts\n\nMigration helper that migrates contact fields to the access control list\"\"\"\n\nfrom alembic import op\n\n\ndef migrate_contacts(type_, table_type, mappings=None):\n \"\"\"Creates new access control roles and migrates existing contacts\"\"\"\n\n connection = op.get_bind()\n if mappings is None:\n mappings = ({\n 'name': 'Primary Contacts',\n 'column': 'contact_id',\n }, {\n 'name': 'Secondary Contacts',\n 'column': 'secondary_contact_id',\n })\n # 1. Create new custom roles:\n sql = \"\"\"\n INSERT INTO access_control_roles\n (name, object_type, created_at, updated_at)\n VALUES ('{first_role}', '{type}', NOW(), NOW()),\n ('{second_role}', '{type}', NOW(), NOW())\n \"\"\".format(\n type=type_,\n first_role=mappings[0]['name'],\n second_role=mappings[1]['name']\n )\n op.execute(sql)\n\n # 2. Fetch ids for newly created roles\n results = connection.execute(\"\"\"\n SELECT id, name\n FROM access_control_roles\n WHERE (name = '{first_role}' OR name = '{second_role}')\n AND object_type = '{object_type}'\n ORDER BY id\n \"\"\".format(\n object_type=type_,\n first_role=mappings[0]['name'],\n second_role=mappings[1]['name']\n )).fetchall()\n\n # 3. Migrate each contact field to access_control_list\n for contact_name, role_id in (\n (mappings[0]['column'], results[0][0]),\n (mappings[1]['column'], results[1][0])\n ):\n extra = '' # Used for extra conditions needed by polymorphic tables\n if table_type == 'directives':\n extra = \"AND meta_kind = '{}'\".format(type_)\n elif type_ == 'Process':\n extra = \"AND is_biz_process = 1\"\n elif type_ == 'System':\n extra = \"AND is_biz_process = 0\"\n sql = \"\"\"\n INSERT INTO access_control_list\n (person_id, ac_role_id, object_id, object_type,\n created_at, updated_at)\n SELECT {contact_name}, {role_id}, id, '{object_type}', NOW(), NOW()\n FROM {table_type}\n WHERE {contact_name} IS NOT null {extra}\"\"\".format(\n role_id=role_id,\n contact_name=contact_name,\n object_type=type_,\n table_type=table_type,\n extra=extra\n )\n op.execute(sql)\n","sub_path":"src/ggrc/migrations/utils/migrate_contacts.py","file_name":"migrate_contacts.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"456588907","text":"from django.utils import timezone\nfrom django.db.models import F\n\n\ndef credit_score(user):\n '''Function that checks credit risk level for users\n this assumes that previous records of loan are stored in our database.\n this function can be modified to retrieve credit record with an API if it is available in an external resource'''\n\n risks = {\n 'N/A': 'No credit record',\n 1: 'Very High',\n 2: 'High',\n 3: 'Medium',\n 4: 'Low',\n 5: 'Very Low'\n }\n user_loans = user.loans.all()\n paid_in_due_date = user_loans.filter(\n due_date__lt=F('payment_complete_date')).count()\n out_of_due_date = user_loans.filter(\n due_date__gte=F('payment_complete_date')).count()\n overdue_loans = user_loans.filter(\n due_date__lt=timezone.now(), payment_complete=False).count()\n\n score = 'N/A'\n if user_loans.exists(): # if there's a record of loan ever taken\n\n # If he repaid all his loans on time, then his credit score should be 4\n if out_of_due_date + overdue_loans == 0:\n score = 5\n # if he has a maximum of 5 overdue loans i.e. still owing even after the agreed Repayment date, his credit score should be 1.\n elif overdue_loans >= 5:\n score = 1\n\n # if he has at most 2 overdue loans, his credit score should be 2\n elif overdue_loans >= 2:\n score = 2\n # If he repaid all his loans on time, then his credit score should be 4\n\n risk_level = risks[score]\n return score, risk_level\n\n\ndef creditScore(user):\n '''this is a modified function i suggested\n 1. unpaid overdue loans carries the highest risk = 5\n 2. loans paid outside due date = 4\n 3. loans paid in due date = 3\n 4. unpaid loans but not due date = 2\n 5. loans paid before due date = 0 #no risk\n '''\n risks = {\n 0: 'No credit record',\n 5: 'Very High',\n 4: 'High',\n 3: 'Medium',\n 2: 'Low',\n 1: 'Very Low'\n }\n\n user_loans = user.loans.all()\n\n unpaid_overdue = user_loans.filter(\n due_date__lt=timezone.now(), payment_complete=False).count()\n paid_outside_due_date = user_loans.filter(due_date__lt=F(\n 'payment_complete_date'), payment_complete=True).count()\n paid_in_due_date = user_loans.filter(due_date=F(\n 'payment_complete_date'), payment_complete=True).count()\n paid_before_due_date = user_loans.filter(due_date__gt=F(\n 'payment_complete_date'), payment_complete=True).count()\n unpaid_loans = user_loans.filter(\n due_date__lt=timezone.now(), payment_complete=False).count()\n\n # Multiplying the risks with the risk factors and computing the average\n\n try:\n\n risk = (unpaid_overdue * 5) + (paid_outside_due_date * 4) + (paid_in_due_date * 3) + (paid_before_due_date * 0) + \\\n (unpaid_loans * 1) // (unpaid_overdue + paid_outside_due_date +\n paid_in_due_date + paid_before_due_date + unpaid_loans)\n\n risk = risk//5\n except ZeroDivisionError:\n risk = 0\n\n\n return risk, risks[risk]\n","sub_path":"score/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"312834766","text":"import ast\n\nfrom typing import Callable, Tuple\n\nfrom cognitive_complexity.common_types import AnyFuncdef\n\n\ndef has_recursive_calls(funcdef: AnyFuncdef) -> bool:\n return bool([\n n for n in ast.walk(funcdef)\n if (\n isinstance(n, ast.Call)\n and isinstance(n.func, ast.Name)\n and n.func.id == funcdef.name\n )\n ])\n\n\ndef process_child_nodes(\n node: ast.AST,\n increment_by: int,\n verbose: bool,\n complexity_calculator: Callable,\n) -> int:\n child_complexity = 0\n child_nodes = ast.iter_child_nodes(node)\n\n for node_num, child_node in enumerate(child_nodes):\n if isinstance(node, ast.Try):\n if node_num == 1:\n # add +1 for all try nodes except body\n increment_by += 1\n if node_num:\n child_complexity += max(1, increment_by)\n child_complexity += complexity_calculator(\n child_node,\n increment_by=increment_by,\n verbose=verbose,\n )\n return child_complexity\n\n\ndef process_node_itself(\n node: ast.AST,\n increment_by: int,\n) -> Tuple[int, int, bool]:\n control_flow_breakers = (\n ast.If,\n ast.For,\n ast.While,\n ast.IfExp,\n )\n incrementers_nodes = (\n ast.FunctionDef,\n ast.AsyncFunctionDef,\n ast.Lambda,\n )\n\n if isinstance(node, control_flow_breakers):\n increment_by += 1\n return increment_by, max(1, increment_by), True\n elif isinstance(node, incrementers_nodes):\n increment_by += 1\n return increment_by, 0, True\n elif isinstance(node, ast.BoolOp):\n inner_boolops_amount = len([n for n in ast.walk(node) if isinstance(n, ast.BoolOp)])\n base_complexity = inner_boolops_amount * max(increment_by, 1)\n return increment_by, base_complexity, False\n elif isinstance(node, (ast.Break, ast.Continue)):\n return increment_by, max(1, increment_by), True\n return increment_by, 0, True\n","sub_path":"cognitive_complexity/utils/ast.py","file_name":"ast.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"8749753","text":"# coding=utf-8\nclass Solution:\n def removeDuplicates(self, nums): # 删除一个数组中重复的元素\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums.sort()\n if not nums: # 如果列表为空,返回0\n return 0\n waiting_point = 0\n for moving_point in range(1, len(nums)):\n if nums[waiting_point] != nums[moving_point]:\n nums[waiting_point + 1] = nums[moving_point]\n waiting_point += 1\n return waiting_point+1\n\n\na = Solution()\nlist = [1, 1, 2]\nprint(a.removeDuplicates(list)) # 使用引用的原地排序\nprint(list[:a.removeDuplicates(list)])","sub_path":"python/array/removeDuplicates.py","file_name":"removeDuplicates.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"269398292","text":"import datetime\nfrom io import BytesIO\n\nimport boto3\n\nfrom django.conf import settings\nfrom django.contrib.admin.models import (\n CHANGE,\n LogEntry,\n)\nfrom django.contrib.contenttypes.models import ContentType\n\nimport requests\n\nfrom core.models import FinancialYear\n\n\ndef get_current_financial_year():\n y = FinancialYear.objects.filter(current=True)\n if y:\n current_financial_year = y.last().financial_year\n else:\n # If there is a data problem\n # and the current year is not\n # defined, return the financial\n # year for the current date\n # The UK financial year starts\n # in April, so Jan, Feb and Mar\n # are part of the previous year\n today = datetime.datetime.now()\n current_month = today.month\n current_financial_year = today.year\n if current_month < 3 or (current_month == 4 and today.day < 5):\n # before 5th April, the financial\n # year it is one year behind the\n # calendar year\n current_financial_year -= (\n 1\n )\n\n return current_financial_year\n\n\ndef get_year_display(year):\n y = FinancialYear.objects.get(financial_year=year)\n if y:\n return y.financial_year_display\n else:\n return \"Invalid year\"\n\n\ndef create_financial_year_display(year):\n if year < 2000:\n return \"Invalid year\"\n return f\"{year}/{year - 1999}\"\n\n\ndef make_financial_year_current(financial_year):\n FinancialYear.objects.all().update(current=False)\n FinancialYear.objects.filter(financial_year=financial_year).update(current=True)\n\n\nclass GetValidYear:\n regex = r'20\\d{2}'\n\n def to_python(self, value):\n return int(value)\n\n def to_url(self, value):\n return '%04d' % value\n\n\ndef get_s3_file_body(file_name):\n s3 = boto3.resource(\n 's3',\n aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,\n region_name=settings.AWS_REGION,\n )\n\n obj = s3.Object(\n settings.AWS_STORAGE_BUCKET_NAME,\n file_name,\n )\n data = obj.get()['Body'].read()\n # loadworkbook needs a file like object to work. BytesIO transform the stream\n return BytesIO(data)\n\n\ndef run_anti_virus(file_body):\n # Check file with AV web service\n if settings.IGNORE_ANTI_VIRUS:\n return {'malware': False}\n\n files = {\"file\": file_body}\n\n auth = (\n settings.CLAM_AV_USERNAME,\n settings.CLAM_AV_PASSWORD,\n )\n response = requests.post(\n settings.CLAM_AV_URL,\n auth=auth,\n files=files,\n )\n\n return response.json()\n\n\ndef today_string():\n today = datetime.datetime.today()\n return today.strftime(\"%d %b %Y\")\n\n\n# Classes used to display totals and subtotals when showing Forecast/Actuals\nSUB_TOTAL_CLASS = \"sub-total\"\nTOTAL_CLASS = \"mid-total\"\nGRAND_TOTAL_CLASS = \"grand-total\"\n\n\ndef check_empty(value):\n if value is not None and value != '':\n return value\n\n return None\n\n\ndef log_object_change(\n requesting_user_id,\n message,\n obj=None,\n):\n if obj:\n content_type_id = ContentType.objects.get_for_model(\n obj\n ).pk\n\n LogEntry.objects.log_action(\n user_id=requesting_user_id,\n content_type_id=content_type_id,\n object_id=obj.pk,\n object_repr=str(obj),\n action_flag=CHANGE,\n change_message=f\"{str(obj)} {message}\",\n )\n else:\n LogEntry.objects.log_action(\n user_id=requesting_user_id,\n content_type_id=None,\n object_id=None,\n object_repr=\"\",\n action_flag=CHANGE,\n change_message=message,\n )\n","sub_path":"core/utils/generic_helpers.py","file_name":"generic_helpers.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"466838776","text":"from flask_bootstrap import Bootstrap\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_moment import Moment\nfrom flask_login import LoginManager\nfrom flask_uploads import UploadSet, IMAGES, configure_uploads, patch_request_class\nfrom flask_debugtoolbar import DebugToolbarExtension\nimport pymysql\n\npymysql.install_as_MySQLdb()\n\"\"\"创建对象\"\"\"\nbootstrap = Bootstrap()\ndb = SQLAlchemy()\nmoment = Moment()\nlogin_manager = LoginManager()\n\"\"\"上传\"\"\"\nphotos = UploadSet('photos', IMAGES)\n\"\"\"调试工具\"\"\"\ntoolbar = DebugToolbarExtension()\n\ndef config_extensions(app):\n\t\"\"\"\n\t三方插件配置\n\t:param app:\n\t:return:\n\t\"\"\"\n\tbootstrap.init_app(app)\n\tdb.init_app(app)\n\tmoment.init_app(app)\n\tlogin_manager.init_app(app)\n\ttoolbar.init_app(app)\n\n\t\"\"\"图片上传的配置\"\"\"\n\tconfigure_uploads(app, photos)\n\t\"\"\"设置上传文件大小\"\"\"\n\tpatch_request_class(app, size=None)\n\n\t\"\"\"指定登录的端点\"\"\"\n\tlogin_manager.login_view = 'users.login'\n\n\t\"\"\"需要登录时的提示信息\"\"\"\n\tlogin_manager.login_message = '需要先登录'\n\t\"\"\"\n\t设置session保护级别\n\tNone:禁用session保护\n\t'basic':基本的保护,默认选项\n\t'strong':最严格的保护,一旦用户登录信息改变,立即退出登录\n\t\"\"\"\n\tlogin_manager.session_protection = 'strong'\n","sub_path":"edm_web/app/extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"335478537","text":"import cv2, sys, numpy as np\n\nfrom PyQt4 import QtCore\nfrom PyQt4 import Qt\nfrom PyQt4 import QtGui\nfrom PyQt4 import QtOpenGL\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\n\n\nclass CameraDevice(QtCore.QObject):\n\n _DEFAULT_FPS = 30\n\n newFrame = QtCore.pyqtSignal(np.ndarray)\n\n def __init__(self, cameraId=0, mirrored=False, parent=None):\n super(CameraDevice, self).__init__(parent)\n\n self.mirrored = mirrored\n\n self._cameraDevice = cv2.VideoCapture(cameraId)\n\n self._timer = QtCore.QTimer(self)\n self._timer.timeout.connect(self._queryFrame)\n self._timer.setInterval(1000/self.fps)\n\n self.paused = False\n\n @QtCore.pyqtSlot()\n def _queryFrame(self):\n success, frame = self._cameraDevice.read()\n if success:\n if self.mirrored:\n frame = cv2.flip(frame, 1)\n self.newFrame.emit(frame)\n\n @property\n def paused(self):\n return not self._timer.isActive()\n\n @paused.setter\n def paused(self, p):\n if p:\n self._timer.recognize_face_stopped()\n else:\n self._timer.start()\n\n @property\n def frameSize(self):\n w = self._cameraDevice.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)\n h = self._cameraDevice.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)\n return int(w), int(h)\n\n @property\n def fps(self):\n _fps = self._cameraDevice.get(cv2.cv.CV_CAP_PROP_FPS)\n if not _fps > 0:\n _fps = self._DEFAULT_FPS\n return _fps\n\n\n\nclass ARWidget(QtOpenGL.QGLWidget):\n\n newFrame = QtCore.pyqtSignal(np.ndarray)\n\n def __init__(self, cameraDevice, parent=None):\n super(ARWidget, self).__init__(parent)\n\n self._frame = None\n\n self._pose = np.eye(4, dtype = np.float64)\n\n self._cameraDevice = cameraDevice\n self._cameraDevice.newFrame.connect(self._onNewFrame)\n\n #w, h = self._cameraDevice.frameSize\n w = 640\n h = 480\n\n if not w*h:\n w = 640\n h = 480\n raise ValueError(\"Incorrect image size! (An error seems to have occured with the video device)\")\n\n self.setMinimumSize(w, h)\n self.setMaximumSize(w, h)\n\n\n def initializeGL(self):\n glViewport(0, 0, self.width(), self.height());\n glClearColor(1.0, 0.5, 0.0, 1.0)\n glClearDepth(1.0)\n glPolygonMode( GL_FRONT_AND_BACK, GL_FILL )\n glEnable(GL_NORMALIZE);\n glEnable(GL_DEPTH_TEST);\n glShadeModel(GL_SMOOTH);\n glDepthMask(GL_TRUE);\n glDepthFunc(GL_LEQUAL);\n glEnable(GL_LIGHT0);\n glLineWidth(3.0)\n\n\n def paintGL(self):\n if self._frame is None:\n return\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n self.drawFrame()\n #self.draw3DScene()\n\n def resizeGL(self, w, h):\n pass\n\n @QtCore.pyqtSlot(np.ndarray)\n def _onNewFrame(self, frame):\n self._frame = np.copy(frame)\n self.newFrame.emit(self._frame)\n\n ### TODO: (Ignore for assignment 3) ###\n ### Estimate the camera/marker pose ###\n ### For example: ###\n\n #self._pose = tracker.estimatePose(self._frame)\n\n #and delete this:\n self._pose[2, 3] = (self._pose[2, 3] + 1)%100\n\n self.updateGL()\n\n def draw3DScene(self):\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(45.0, float(self.width())/float(self.height()), 0.1, 1000.0)\n # Better: glMultMatrixd(tracker.getProjectionMatrix().T)\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -1.0, 0.0)\n\n # use the etimated pose for model transformation\n glMultMatrixd(self._pose.T)\n\n # draw simple coordinate axes\n glBegin(GL_LINES)\n glColor3d(1.0,0.0,0.0)\n glVertex3d(0.0, 0.0, 0.0)\n glVertex3d(10.0, 0.0, 0.0)\n glColor3d(0.0,1.0,0.0)\n glVertex3d(0.0, 0.0, 0.0)\n glVertex3d(0.0, 10.0, 0.0)\n glColor3d(0.0, 0.0, 1.0)\n glVertex3d(0.0, 0.0, 0.0)\n glVertex3d(0.0, 0.0, 10.0)\n glEnd()\n\n # draw teapot\n glEnable(GL_LIGHTING)\n glPushMatrix()\n glTranslate(0.0, 0.0, 1.0)\n glRotate(90.0, 1.0, 0.0, 0.0)\n glutSolidTeapot(1)\n glPopMatrix()\n glDisable(GL_LIGHTING)\n\n\n def drawFrame(self):\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0.0, self.width(), self.height(), 0.0, -1.0, 1.0);\n glMatrixMode(GL_MODELVIEW);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glLoadIdentity();\n\n # convert the numpy array to an opengl texture\n glTexImage2D(GL_TEXTURE_2D, 0, 3, self._frame.shape[1], self._frame.shape[0], 0, GL_BGR, GL_UNSIGNED_BYTE, self._frame.tostring());\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);\n\n glDisable(GL_DEPTH_TEST);\n\n glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );\n glColor3d(1.0,1.0,1.0);\n\n # draw the frame mapped to a textured quad\n glEnable(GL_TEXTURE_2D);\n glBegin(GL_QUADS);\n glTexCoord2f( 0.0, 0.0);\n glVertex3f( 0, 0, 0 );\n\n glTexCoord2f( 1.0, 0.0 );\n glVertex3f( self.width(), 0, 0 );\n\n glTexCoord2f( 1.0, 1.0 );\n glVertex3f( self.width(), self.height(), 0 );\n\n glTexCoord2f( 0.0, 1.0 );\n glVertex3f( 0, self.height(), 0 );\n glEnd();\n glDisable(GL_TEXTURE_2D);\n\n glEnable(GL_DEPTH_TEST);\n\n\n def changeEvent(self, e):\n if e.type() == QtCore.QEvent.EnabledChange:\n if self.isEnabled():\n self._cameraDevice.newFrame.connect(self._onNewFrame)\n else:\n self._cameraDevice.newFrame.disconnect(self._onNewFrame)\n\n\nclass MyMainWindow(QtGui.QWidget):\n def __init__(self):\n self.lframe = None\n QtGui.QWidget.__init__(self, None)\n self.setWindowTitle('Simple AR Display')\n #cv2.resize(self.lframe,100,100)\n\n # specify layout\n vbox = QtGui.QGridLayout(self)\n\n # get camera device\n self.cameraDevice = CameraDevice(mirrored=False)\n self.cameraDevice.newFrame.connect(self.onNewCameraFrame)\n\n # add widget to show the augmented video input image\n\n arWidget = ARWidget(self.cameraDevice)\n arWidget.newFrame.connect(self.onNewCameraFrame)\n vbox.addWidget(arWidget,0,0)\n\n\n def onNewCameraFrame(self, frame):\n\n # ================================ Face Recognize =========================================== #\n img =frame.copy()\n\n # Quadrat zum Groessenvergleich \n## square = 400\n## cv2.rectangle(img,(320-square/2, 240-square/2),(320+square/2, 240+square/2),(255, 255, 0), 2)\n##\n #face_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_alt2.xml\") # schneller angeblilch \n face_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n eye_cascade = cv2.CascadeClassifier(\"haarcascade_eye.xml\")\n #mouth_cascade = cv2.CascadeClassifier(\"haarcascade_mcs_mouth.xml\")\n\n #Image fuer Gesichts Erkennung vorbereiten\n assert(img.shape[2] == 3)\n g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n DETECTION_WIDTH = 320\n scale = img.shape[1] / float(DETECTION_WIDTH)\n if img.shape[1] > DETECTION_WIDTH:\n scaled_height = int(img.shape[0]/scale +0.5)\n smallg = cv2.resize(g, (DETECTION_WIDTH,scaled_height))\n else:\n smallg = g\n smallg = cv2.equalizeHist(smallg)\n # Parameter erhoehen die Performance\n \n faces = face_cascade.detectMultiScale(smallg, \n scaleFactor = 1.2, \n minNeighbors = 4, \n minSize = (60, 60),\n maxSize = (400, 400),\n flags = cv2.cv.CV_HAAR_SCALE_IMAGE #| cv2.cv.CV_HAAR_FIND_BIGGEST_OBJECT | cv2.cv.CV_HAAR_DO_ROUGH_SEARCH\n )\n\n for (x,y,w,h) in faces:\n if img.shape[1] > DETECTION_WIDTH:\n x = int(x * scale + 0.5)\n y = int(y * scale + 0.5)\n w = int(w * scale + 0.5)\n h = int(h * scale + 0.5)\n cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n roi_gray = img[y:y+h, x:x+w]\n\n roi_color = img[y:y+h, x:x+w]\n eyes = eye_cascade.detectMultiScale(roi_gray)\n for (ex,ey,ew,eh) in eyes:\n cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)\n\n #mouth = mouth_cascade.detectMultiScale(g, 1.3, 5)\n \n if self.lframe is not None:\n frame[:] = self.lframe\n\n self.lframe = img\n\n\nif __name__ == \"__main__\":\n\n app = QtGui.QApplication(sys.argv)\n w = MyMainWindow()\n w.show()\n sys.exit(app.exec_())\n\n\n\n","sub_path":"trunk/facedetection/old_stuff/faceRecognize.py","file_name":"faceRecognize.py","file_ext":"py","file_size_in_byte":9236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"534604754","text":"import sys\nimport pygame\nfrom bullet import Bullet\nfrom alien import Alien\nfrom time import sleep\n\ndef check_events(settings, screen, ship, bullets):\n #any keyboard will fire the loop to run\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n #when the user press a key\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event, settings, screen, ship, bullets)\n elif event.type == pygame.KEYUP:\n check_keyup_events(event, ship)\n\ndef check_keydown_events(event, settings, screen, ship, bullets):\n #when the user press a key\n if event.key == pygame.K_q:\n sys.exit()\n elif event.key == pygame.K_RIGHT:\n ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n elif event.key == pygame.K_SPACE:\n fire_bullet(settings, screen, ship, bullets)\n\ndef check_keyup_events(event, ship):\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n ship.moving_left = False\n\ndef fire_bullet(settings, screen, ship, bullets):\n if len(bullets) < settings.bullets_allowed:\n new_bullet = Bullet(settings, screen, ship)\n bullets.add(new_bullet)\n\ndef update_screen(settings, screen, ship, aliens, bullets):\n #fill screen with the background color\n screen.fill(settings.backgroundColor)\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n ship.blitme()\n aliens.draw(screen)\n #most recent screen is visible, erasing old screen\n pygame.display.flip()\n\n\ndef update_bullets(settings, screen, ship, aliens, bullets):\n bullets.update()\n for bullet in bullets.copy():\n if bullet.rect.bottom <=0:\n bullets.remove(bullet)\n check_bullet_alien_collisions(settings, screen, ship, aliens, bullets)\n\ndef check_bullet_alien_collisions(settings, screen, ship, aliens, bullets):\n collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)\n #delete the bullet and alien when the bullet hit the alien\n collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)\n if len(aliens) == 0:\n bullets.empty()\n create_fleet(settings, screen, ship, aliens)\n\ndef create_fleet(settings, screen, ship, aliens):\n alien = Alien(settings, screen)\n number_aliens_x = get_number_aliens_x(settings, alien.rect.width)\n number_rows= get_number_rows(settings, ship.rect.height, alien.rect.height)\n for row_number in range(number_rows):\n for alien_number in range(number_aliens_x):\n create_alien(settings, screen, aliens, alien_number, row_number)\n\ndef get_number_aliens_x(settings, alien_width):\n #number of aliens in one row\n available_space_x = settings.screen_width - 2 * alien_width\n number_aliens_x = int(available_space_x / (2 * alien_width))\n return number_aliens_x\n\ndef create_alien(settings, screen, aliens, alien_number, row_number):\n #create alien and place it in the row\n alien = Alien(settings, screen)\n alien_width=alien.rect.width\n alien.x_coor = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x_coor\n alien.rect.y = alien.rect.height + 2*alien.rect.height*row_number\n aliens.add(alien)\n\ndef get_number_rows(settings, ship_height, alien_height):\n #number of aliens in the screen\n available_space_y = (settings.screen_height - 3 * alien_height - ship_height)\n number_rows = int(available_space_y / (2 * alien_height))\n return number_rows\n\ndef update_aliens(settings, stats, screen, ship, aliens, bullets):\n #update p[osition of aliens\n check_fleet_edges(settings, aliens)\n aliens.update()\n if pygame.sprite.spritecollideany(ship, aliens):\n ship_hit(settings, stats, screen, ship, aliens, bullets)\n check_aliens_bottom(settings, stats, screen, ship, aliens, bullets)\n\n\ndef check_fleet_edges(settings, aliens):\n for alien in aliens.sprites():\n if alien.check_edges():\n change_fleet_direction(settings, aliens)\n break\n\ndef change_fleet_direction(settings, aliens):\n for alien in aliens.sprites():\n alien.rect.y += settings.fleet_drop_speed\n settings.fleet_direction *=-1\n\ndef ship_hit(settings, stats, screen, ship, aliens, bullets):\n if stats.ships_left > 0: \n stats.ships_left -= 1\n aliens.empty()\n bullets.empty()\n create_fleet(settings, screen, ship, aliens)\n ship.center_ship()\n sleep(0.5)\n else:\n stats.game_active = False\n\ndef check_aliens_bottom(settings, stats, screen, ship, aliens, bullets):\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n ship_hit(settings, stats, screen, ship, aliens, bullets)\n break\n\n","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":4829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"544305778","text":"#/usr/bin/env python\n# -*- coding:utf-8 -*-\n'''\n @File : scrapy-jobs.py \n @Contact : guoxin@126.com\n @License : (C)Copyright 2018-2019, xguo\n\n@Modify Time @Author @Version @Desciption\n------------ ------- -------- -----------\n2020/2/5 17:07 xguo 1.0 None\n\n'''\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n\ndef main():\n text = urlopen('http://python.org/jobs').read()\n soup = BeautifulSoup(text, 'html.parser')\n jobs = set()\n for job in soup.body.section('h2'):\n jobs.add('{} ({})'.format(job.a.string, job.a['href']))\n print('\\n'.join(sorted(jobs, key=str.lower)))\n\nif __name__ == \"__main__\":\n main()","sub_path":"web_scrapt/scrapy-jobs.py","file_name":"scrapy-jobs.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"529792058","text":"import numpy as np\nimport scipy.signal as sg\nimport matplotlib.pyplot as plt\nimport filter as Filter\nimport fourier_transform as FFT\nimport waveform3 as wf3\nimport display as Disp\n\ndef get_amp_phase_freq(b_norm,a_norm,fs):\n w, h = sg.freqz(b_norm, a_norm, fs);\n f_norm = np.array(w) / (2 * np.pi) * fs;\n a = 20 * np.array(np.log10(np.abs(h)));#gain\n p = np.angle(h) * 180 / np.pi;#phase\n\n return(a,p,f_norm)\n\ndef HPF(input_signal,q,f0,fs):\n b,a=Filter.highpath(q,f0,fs)\n output=sg.lfilter(b,a,output)\n return(output)\n\n\ndef filtering(input_signal,q,gain,f0,fs):\n output = input_signal\n # amp = [0]*len(q)\n # phase = [0]*len(q)\n for num in range(len(q)):\n b,a = Filter.peaking_eq(q[num],gain[num],f0[num],fs)\n output = sg.lfilter(b,a,output)\n #amp[num],phase[num],f_norm = get_amp_phase_freq(b[num],a[num],fs)\n\n # fil_amplitude = sum(amp)\n # fil_phase = sum(phase)\n\n # return(output,fil_amplitude,fil_phase,f_norm)\n return(output)\n\ndef filtering_reform(input_signal,q,gain,f0,fs):\n b = [0]*len(q)\n a = [0]*len(q)\n h_buff = [0]*len(q)\n h_sum = [0]*fs\n # amp = [0]*len(q)\n # phase = [0]*len(q)\n output = [0]*len(input_signal)\n for num in range(len(q)):\n b,a = Filter.peaking_eq(q[num],gain[num],f0[num],fs)\n w,h = sg.freqz(b, a, fs)\n h_sum = np.array(h_sum) + np.array(h)\n output_buff = sg.lfilter(b,a,input_signal)\n output = np.array(output) + np.array(output_buff)\n f_norm = w / (2 * np.pi) * fs\n a = 20 * np.array(np.log10(abs(h_sum)))#gain\n p = np.array(np.angle(h_sum)) * 180 / np.pi;\n # fil_amplitude = sum(amp)\n # fil_phase = sum(phase)\n\n # return(output,fil_amplitude,fil_phase,f_norm)\n return(output,a,p)\n\ndef filtering_bank(input_signal,q,gain,f0,fs):\n b = [0]*len(q)\n a = [0]*len(q)\n h_buff = [0]*len(q)\n h_sum = [0]*fs\n # amp = [0]*len(q)\n # phase = [0]*len(q)\n output = [0]*len(input_signal)\n for num in range(len(q)):\n b,a = Filter.peaking_eq(q[num],gain[num],f0[num],fs)\n w,h = sg.freqz(b, a, fs)\n h_sum = np.array(h_sum) + np.array(h)\n output_buff = sg.lfilter(b,a,input_signal)\n output = np.array(output) + np.array(output_buff)\n f_norm = w / (2 * np.pi) * fs\n a = 20 * np.array(np.log10(abs(h_sum)))#gain\n p = np.array(np.angle(h_sum)) * 180 / np.pi;\n # fil_amplitude = sum(amp)\n # fil_phase = sum(phase)\n\n # return(output,fil_amplitude,fil_phase,f_norm)\n return(output,a,p)\n\ndef filter_co(q,gain,f0,fs):\n amp = [0]*fs\n phase = [0]*fs\n h_sum = [0]*44100\n for num in range(len(q)):\n b,a = Filter.peaking_eq(q[num],gain[num],f0[num],fs)\n w,h = sg.freqz(b, a, fs)\n h_sum = np.array(h_sum) + np.array(h)\n print(h)\n f_norm = w / (2 * np.pi) * fs\n amp = 20 * np.array(np.log10(abs(np.array(h_sum))))#gain\n phase = np.array(np.angle(h_sum)) * 180 / np.pi\n\n # for num in range(len(q)):\n # b,a = Filter.peaking_eq(q[num],gain[num],f0[num],fs)\n # amp_buff,phase_buff,f_norm = get_amp_phase_freq(b,a,fs)\n # amp = np.array(amp) + np.array(amp_buff)\n # phase = np.array(phase) + np.array(phase_buff)\n\n\n return(amp,phase,f_norm)\n\ndef filter_co2(q,f0,fs):\n amp = [0]*fs\n phase = [0]*fs\n # b,a = Filter.bandpath(q,f0,fs)\n # w,h = sg.freqz(b, a, fs)\n # f_norm = w / (2 * np.pi) * fs\n # a = 20 * np.log10(abs(h))#gain\n # p = np.angle(h) * 180 / np.pi\n\n for num in range(len(q)):\n b,a = Filter.bandpath(q[num],f0[num],fs)\n amp[num],phase[num],f_norm = get_amp_phase_freq(b,a,fs)\n\n a = sum(amp)\n p = sum(phase)\n\n return(a,p,f_norm)\n\ndef filter_co3(q,f0,fs):\n amp = [0]*fs\n phase = [0]*fs\n h_sum = [0]*44100\n for num in range(len(q)):\n b,a = Filter.bandpath(q[num],f0[num],fs)\n w,h = sg.freqz(b, a, fs)\n h_sum = np.array(h_sum) + np.array(h)\n f_norm = w / (2 * np.pi) * fs\n amp = 20 * np.array(np.log10(abs(np.array(h_sum))))#gain\n phase = np.array(np.angle(h_sum)) * 180 / np.pi\n\n # for num in range(len(q)):\n # b,a = Filter.peaking_eq(q[num],gain[num],f0[num],fs)\n # amp_buff,phase_buff,f_norm = get_amp_phase_freq(b,a,fs)\n # amp = np.array(amp) + np.array(amp_buff)\n # phase = np.array(phase) + np.array(phase_buff)\n\n\n return(amp,phase,f_norm)\n\ndef Amplitude_square_error(input_signal,ref_signal,fs,mag):\n n_len = len(input_signal)\n n_fft = fs\n n_overlap = 1\n n_shift = n_fft / n_overlap\n J_k = 0\n J = 0\n\n half=44100\n\n in_cut=[0]*fs\n ref_cut=[0]*fs\n REF_sg=[0]*half\n IN_sg=[0]*half\n REF_sum = [0]*half\n IN_sum = [0]*half\n sub_ary2=[0]*half\n sub=0\n\n fc1 = 1000\n fc2 = 2000\n freq = np.linspace(0,fs,fs)\n \"窓あり\"\n for start in range(0, int(n_len - n_shift), int(n_shift)):\n in_cut = input_signal[start: start + fs]\n ref_cut = ref_signal[start: start + fs]\n\n REF_fft = np.fft.fft(ref_cut)\n IN_fft = np.fft.fft(in_cut)\n\n REF_sg = np.abs(REF_fft[:half])\n IN_sg = np.abs(IN_fft[:half])\n \"レベル調整\"\n #IN_sg = np.array(IN_sg) * mag\n \"レベル調整\"\n \"評価領域\"\n # REF_sg[(freqfc2)] = 1\n # IN_sg[(freqfc2)] = 1\n # REF_sg=[i for i in REF_sg if not i==0]\n # IN_sg=[i for i in IN_sg if not i==0]\n \"評価領域\"\n REF_sum = np.array(REF_sum) + np.array(REF_sg)\n IN_sum = np.array(IN_sum) + np.array(IN_sg)\n\n div = int(n_len - n_shift)/n_shift\n REF_div = np.array(REF_sum)/div\n IN_div = np.array(IN_sum)/div\n\n REF_sg = 20*np.array(np.log10(REF_div))\n IN_sg = 20*np.array(np.log10(IN_div))\n\n sub_ary=np.abs((np.array(REF_sg)-np.array(IN_sg)))\n sub_ary=np.array(sub_ary)**2\n for i in range(len(sub_ary)):\n sub_ary2[i]=sub_ary[i]/(i+1)\n sub = sum(sub_ary2)\n sub += sub\n \"窓あり\"\n \"窓なし\"\n # REF_sg = np.fft.fft(ref_signal)\n # IN_sg = np.fft.fft(input_signal)\n # REF_sg =\n \"窓なし\"\n print(sub)\n # plt.plot(REF_sg,color='blue')\n # plt.plot(IN_sg,color='red')\n # plt.xlabel('Frequency[Hz]')\n # plt.xlim(20,20000)\n # plt.ylim(-40,40)\n # plt.xscale(\"log\")\n # plt.ylabel('amp')\n # plt.show()\n return(sub)\n\ndef freq_oct(freq,num,oct_div):\n octave = freq\n f0_array = [0]*num\n f0_array[0]=freq\n for i in range(1,num):\n octave = round(octave*(2**(oct_div)),0)\n f0_array[i] = octave\n return(f0_array)\n\ndef cross_correlation(sg1,sg2):\n max = 44100*5\n sg1_cut = sg1[:max]\n sg2_cut = sg2[:max]\n corr = np.correlate(sg1_cut,sg2_cut,\"full\")\n delay = corr.argmax() - (len(sg2_cut) - 1)\n return(delay)\n\ndef fourier(target,speak,corr,fs):\n time = int(len(target)/fs)\n N = 44100\n freq = np.fft.fftfreq(len(target),(1/fs))\n REF_sum = [0]*int(N/2)\n IN_sum = [0]*int(N/2)\n CORR_sum = [0]*int(N/2)\n REF_psum = [0]*int(N/2)\n IN_psum = [0]*int(N/2)\n CORR_psum = [0]*int(N/2)\n\n \"窓あり\"\n # for sec in range(time):\n # REF_sg = np.fft.fft(target[sec*fs:(sec+1)*fs])\n # IN_sg = np.fft.fft(speak[sec*fs:(sec+1)*fs])\n # CORR_sg = np.fft.fft(corr[sec*fs:(sec+1)*fs])\n # REF_sg = REF_sg[:int(len(REF_sg)/2)]\n # IN_sg = IN_sg[:int(len(IN_sg)/2)]\n # CORR_sg = CORR_sg[:int(len(CORR_sg)/2)]\n #\n # ref_phase = np.unwrap(np.angle(REF_sg))\n # ori_phase = np.unwrap(np.angle(IN_sg))\n # corr_phase = np.unwrap(np.angle(CORR_sg))\n #\n #\n # REF_amp = np.abs(REF_sg)\n # IN_amp = np.abs(IN_sg)\n # CORR_amp = np.abs(CORR_sg)\n #\n #\n # REF_psum = np.array(REF_psum)+np.array(ref_phase)\n # IN_psum = np.array(IN_psum)+p.array(ori_phase)\n # CORR_psum = np.array(CORR_psum)+np.array(corr_phase)\n #\n # REF_sum = np.array(REF_sum)+np.array(REF_amp)\n # IN_sum = np.array(IN_sum)+np.array(IN_amp)\n # CORR_sum = np.array(CORR_sum)+np.array(CORR_amp)\n #\n # REF_div = np.array(REF_sum)/time\n # IN_div = np.array(IN_sum)/time\n # CORR_div = np.array(CORR_sum)/time\n #\n # REF_pdiv = np.array(REF_psum)/time\n # IN_pdiv = np.array(IN_psum)/time\n # CORR_pdiv = np.array(CORR_psum)/time\n #\n # REF_log = 20*np.array(np.log10(np.array(REF_div)))\n # IN_log = 20*np.array(np.log10(np.array(IN_div)))\n # CORR_log = 20*np.array(np.log10(np.array(CORR_div)))\n \"窓あり\"\n \"窓なし\"\n \"窓なし\"\n origin = Amplitude_square_error(speak,target,fs,1)\n corr = Amplitude_square_error(corr,target,fs,mag)\n print(origin)\n print(corr)\n print((origin-corr)/origin)\n return(REF_log,IN_log,CORR_log,REF_pdiv,IN_pdiv,CORR_pdiv)\n\nif __name__ == '__main__':\n fs =44100\n N=int(fs/2)\n target,_,_ = wf3.get_signal(\"/Users/kudo/Google ドライブ/local/study/source/data/corr-speaker5.wav\")\n speak,_,_ = wf3.get_signal(\"/Users/kudo/Google ドライブ/local/study/source/data/reference/LG_small2_whitenoise.wav\")\n corr,_,_ = wf3.get_signal(\"/Users/kudo/Google ドライブ/local/study/source/data/speaker-corr5.wav\")\n time = int(len(target)/44100)\n freq = np.fft.fftfreq(44100,(1/44100))\n REF_sum = [0]*N\n IN_sum = [0]*N\n CORR_sum = [0]*N\n REF_psum = [0]*N\n IN_psum = [0]*N\n CORR_psum = [0]*N\n pow_psdsum=[0]*(N-1)\n\n #sg2,_ = wf3.get_signal(\"output.wav\")\n\n \"レベル調整\"\n # freq = np.linspace(0,fs,len(target))\n # ref_fft = np.fft.fft(target)\n # corr_fft = np.fft.fft(speak)\n # ref_fft = np.abs(ref_fft)\n # corr_fft = np.abs(corr_fft)\n # fc1=1000\n # fc2=2000\n # ref_fft[(freqfc2)]=1\n # corr_fft[(freqfc2)]=1\n # magnitude = sum(ref_fft)/sum(corr_fft)\n # magnitude=1\n \"レベル調整\"\n #\n #\n # ref_sg = ref_sg[:int(len(ref_sg)/2)]\n # ori_sg = ori_sg[:int(len(ori_sg)/2)]\n # corr_sg = corr_sg[:int(len(corr_sg)/2)]\n #\n # ref_phase = np.unwrap(np.angle(ref_sg))\n # ori_phase = np.unwrap(np.angle(ori_sg))\n # corr_phase = np.unwrap(np.angle(corr_sg))\n\n #sg1 = sg1[44100*5:44100*15]\n for sec in range(time):\n REF_sg = np.fft.fft(target[sec*44100:(sec+1)*44100])\n IN_sg = np.fft.fft(speak[sec*44100:(sec+1)*44100])\n CORR_sg = np.fft.fft(corr[sec*44100:(sec+1)*44100])\n\n REF_sg = REF_sg[:int(len(REF_sg)/2)]\n IN_sg = IN_sg[:int(len(IN_sg)/2)]\n CORR_sg = CORR_sg[:int(len(CORR_sg)/2)]\n\n ref_phase = np.unwrap(np.angle(REF_sg))\n ori_phase = np.unwrap(np.angle(IN_sg))\n corr_phase = np.unwrap(np.angle(CORR_sg))\n\n\n REF_amp = np.abs(REF_sg)\n IN_amp = np.abs(IN_sg)\n CORR_amp = np.abs(CORR_sg)\n\n\n REF_psum += np.array(ref_phase)\n IN_psum += np.array(ori_phase)\n CORR_psum += np.array(corr_phase)\n\n REF_sum = np.array(REF_sum)+np.array(REF_amp)\n IN_sum = np.array(IN_sum)+np.array(IN_amp)\n CORR_sum = np.array(CORR_sum)+np.array(CORR_amp)\n\n\n #magnitude = 3\n REF_div = np.array(REF_sum)/time\n IN_div = np.array(IN_sum)/time\n CORR_div = np.array(CORR_sum)/time\n \"レベル調整\"\n #CORR_div= np.array(CORR_div) * magnitude\n \"レベル調整\"\n REF_pdiv = np.array(REF_psum)/time\n IN_pdiv = np.array(IN_psum)/time\n CORR_pdiv = np.array(CORR_psum)/time\n\n REF_log = 20*np.array(np.log10(REF_div))\n IN_log = 20*np.array(np.log10(IN_div))\n CORR_log = 20*np.array(np.log10(CORR_div))\n\n sum3=[]\n sum4=[]\n sum5=[]\n shift=2\n for i in range(101,(1002-shift),shift):\n sum3.append(sum(CORR_log[i:i+shift])/shift)\n shift=20\n for i in range(1001,(10002-shift),shift):\n sum4.append(sum(CORR_log[i:i+shift])/shift)\n shift=200\n for i in range(10001,20002-shift,shift):\n sum5.append(sum(CORR_log[i:i+shift])/shift)\n print(len(CORR_log[101:1001]),len(sum3),len(sum4),len(sum5))\n CORR_log2=[]\n fr=[]\n CORR_log2.extend(CORR_log[0:100])\n CORR_log2.extend(sum3)\n CORR_log2.extend(sum4)\n CORR_log2.extend(sum5)\n fr.extend(np.arange(0,100))\n fr.extend(np.arange(100,1000,2))\n fr.extend(np.arange(1000,10000,20))\n fr.extend(np.arange(10000,20000,200))\n #CORR_log=CORR_log[::5]\n plt.figure(1, figsize=(8, 12))\n plt.subplots_adjust(hspace = 1)\n # plt.subplot(311)\n # plt.title('target',fontsize=12)\n # plt.plot(REF_log,color='blue')\n # plt.xlabel('Frequency[Hz]')\n # plt.xlim(20,20000)\n # plt.ylim(-10,70)\n # plt.xscale(\"log\")\n # #plt.yscale(\"log\")\n # plt.ylabel('amp')\n #\n plt.subplot(211)\n plt.title('target-origin',fontsize=12)\n plt.plot(REF_log,color='blue')\n plt.plot(IN_log,color='red')\n plt.xlabel('Frequency[Hz]')\n plt.xlim(20,20000)\n plt.ylim(-20,20)\n plt.xscale(\"log\")\n plt.ylabel('amp')\n\n plt.subplot(212)\n plt.title('target-corr',fontsize=12)\n plt.plot(REF_log,color='blue',label=\"target\")\n plt.plot(CORR_log,color='red',label=\"corr\")\n plt.xlabel('Frequency[Hz]')\n plt.xlim(20,20000)\n #plt.ylim(-20,20)\n plt.xscale(\"log\")\n #plt.yscale(\"log\")\n plt.ylabel('amp')\n #plt.legend(loc = 'upper right')\n plt.show()\n # plt.plot(REF_pdiv,color='blue')\n # plt.plot(IN_pdiv,color='red')\n # plt.plot(CORR_pdiv,color='yellow')\n # plt.xlim(20,20000)\n # plt.show()\n # print(np.correlate(REF_log,IN_log,\"valid\"))\n # print(np.correlate(REF_log,CORR_log,\"valid\"))\n print(np.corrcoef(REF_log,CORR_log))\n origin = Amplitude_square_error(speak,target,44100,1)\n corr = Amplitude_square_error(corr,target,44100,1)\n print(origin)\n print(corr)\n print((origin-corr)/origin)\n","sub_path":"code/calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":13754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"327647666","text":"#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n# magyartalanító script: az idézőjelben (\"\") lévő szöveget módosítja, majd törli az idézőjelet\nimport re\n\nsql_file=input('Add meg a javítandó fájl elérési útvonalát és nevét: ')\n\nkuka=[('á','a'),('é','e'),('í','i'),('ó','o'),('ö','o'),('ő','o'),('ú','u'),('ü','u'),('ű','u')]\n\nwith open(sql_file, 'r', encoding='utf-8') as all:\n szoveg=all.read()\n\nquoted= re.findall(r'(\\\".+?\\\")', szoveg)\nq=''\nprint(quoted)\nfor m in quoted:\n q = m\n for i in kuka:\n if i[0] in m or i[0].upper() in m:\n print(i)\n q=q.replace((i[0]) , i[1])\n print(q)\n q=q.replace((i[0]).upper() , i[1].upper())\n q = re.sub('[^0-9a-zA-Z\\\"]+', '_', q)\n szoveg = szoveg.replace(m, q)\n\nwhile '__' in szoveg:\n szoveg=szoveg.replace('__', '_')\nszoveg=szoveg.replace('\"', '')\n\n\nwith open(sql_file, 'w', encoding='utf-8') as all:\n all.write(szoveg)\n\nprint('Kész. A módosított file eleje így néz ki:', szoveg[:255])","sub_path":"talendize_sql.py","file_name":"talendize_sql.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"206067667","text":"# -*- coding: UTF-8 -*-\n# -Cleaned and Checked on 10-16-2019 by JewBMX in Scrubs.\n\nimport re\nfrom resources.lib.modules import cfscrape\nfrom resources.lib.modules import cleantitle\nfrom resources.lib.modules import source_utils\n\n\nclass source:\n def __init__(self):\n self.priority = 1\n self.language = ['en']\n self.domains = ['hdmovie8.com']\n self.base_link = 'https://hdmovie8.com'\n self.scraper = cfscrape.create_scraper()\n\n\n def movie(self, imdb, title, localtitle, aliases, year):\n try:\n movietitle = cleantitle.geturl(title)\n url = self.base_link + '/movies/%s-%s/' % (movietitle, year)\n return url\n except:\n return\n\n\n def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):\n try:\n url = cleantitle.geturl(tvshowtitle)\n return url\n except:\n return\n\n\n def episode(self, url, imdb, tvdb, title, premiered, season, episode):\n try:\n if url == None:\n return\n tvshowtitle = url\n url = self.base_link + '/episodes/%s-%sx%s/' % (tvshowtitle, season, episode)\n return url\n except:\n return\n\n\n def sources(self, url, hostDict, hostprDict):\n try:\n sources = []\n if url == None:\n return sources\n hostDict = hostDict + hostprDict\n sourcePage = self.scraper.get(url).content\n thesources = re.compile('(.+?)', re.DOTALL).findall(sourcePage)[0]\n links = re.compile(\"
Download\", re.DOTALL).findall(thesources)\n for link in links:\n linkPage = self.scraper.get(link).content\n vlink = re.compile(' bool:\n _, pointer_x, pointer_y = self.pointer_device.get_position()\n x, y = self.popup.get_position()\n width, height = self.popup.get_size()\n return x < pointer_x < x + width and y < pointer_y < y + height\n\n def run(self):\n while True:\n if self.popup.is_visible() and time.time() >= self.popup.time_to_hide:\n # 若鼠标在窗口中,延迟隐藏窗口\n if not self.is_pointer_in_window():\n # self.window.hide()\n # 只在主线程中操作 UI\n GLib.idle_add(self.popup.hide)\n time.sleep(0.3)\n","sub_path":"popupdict/daemon/audo_hide.py","file_name":"audo_hide.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"404426477","text":"# Takes average around the pixel and then applies Adaptive threshold\n\nimport cv2 as cv\nimport numpy as np\n\nimg = cv.imread('car.png',0)\nret,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)\nth2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\\\n cv.THRESH_BINARY,11,2)\nth3 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\\\n cv.THRESH_BINARY,11,2)\ntitles = ['Original Image', 'Global Thresholding (v = 127)',\n 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']\nimages = [img, th1, th2, th3]\nfor i in range(4):\n cv.imshow(titles[i],images[i])\n k = cv.waitKey(0)\n if k == ord('q'):\n break\n\ncv.destroyAllWindows()","sub_path":"Opencv/7_adaptiveThreshold.py","file_name":"7_adaptiveThreshold.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"562633822","text":"import sys\nimport math\n\n_description_ = \"\"\"\n Circle calculations. Enter the radius.\n Use one function to calculate circumference and area of the circle.\n Use math.pi\n Use a float input function.\n formats {:g} provides numeric rounding. E.g. 314.1592653589793 to 314.159.\n Procedural programming style.\n \"\"\"\n_author_ = \"\"\"Ian Stewart - December 2016\n Hamilton Python User Group - https://hampug.pythonanywhere.com\n CC0 https://creativecommons.org/publicdomain/zero/1.0/ \"\"\"\n\n# Program: snip_l2_07_g.py\n\n# Define constants and variables\nTEXT = \"Enter the radius\"\nradius_prompt = 5.2\ndebug = False\n\n\ndef main(radius):\n \"Main rountine for calculating circle circumference and area.\"\n if debug: print(\"Value of prompt radius: {}\".format(radius))\n radius = get_float_entry(radius, TEXT)\n if debug: print(\"Value of radius used: {}\".format(radius))\n circumference, area = calculate_circle(radius)\n\n print(\"A circle with a radius of: {:g}\".format(radius))\n print(\"Has a circumference of: {:g}\".format(circumference))\n print(\"And an area of: {:g}\".format(area))\n\n\ndef get_float_entry(prompt=\"0\", text=\"Input floating point value\"):\n \"\"\"\n Return a floating point value from input on the console.\n A float value as a prompt may be provided. Default prompt string is \"0\".\n The input prompting text may also be provided.\n \"\"\"\n while True:\n data = input(\"{} [{}]: \".format(text, prompt))\n if data == \"\":\n data = prompt\n try:\n return float(data)\n except ValueError as e:\n if debug: print(\"Value Error: {}\".format(e))\n print(\"Please re-enter...\")\n continue\n\n\ndef calculate_circle(radius):\n \"Calculate the circumference and area of a circle\"\n circumference = 2 * math.pi * float(radius)\n area = math.pi * float(radius)**2\n return circumference, area\n\n\nif __name__ == \"__main__\":\n print(\"Program {} has started...\".format(sys.argv[0]))\n print(\"Enable debugging with -d or --debug\")\n print(\"E.g. python {} --debug\".format(sys.argv[0]))\n print(\"Set radius prompt value -r= or --radius=\")\n print(\"E.g. python {} --radius=5.2\".format(sys.argv[0]))\n\n # Get command line options from sys.argv list\n for index, option in enumerate(sys.argv):\n\n if \"-d\" in option:\n debug = not debug\n\n # Collect string data from command line interface (cli) sys.argv list\n if \"-r\" in option:\n radius_prompt_list = sys.argv[index].split(\"=\")\n if len(radius_prompt_list) > 1:\n radius_prompt = radius_prompt_list[1]\n\n main(radius_prompt)\n\n print(\"End of program.\")\nsys.exit()\n\"\"\"\nTo check code style:\nLinux...\n$ python3 -m pep8 --statistic --ignore=E701 snip_l2_07_g.py\nInstall pep8 on Linux: $ sudo apt-get install python3-pep8\nWindows...\n> python -m pep8 --statistic --ignore=E701 snip_l2_07_g.py\nInstall pep8 on Windows: >pip3 install pep8\nMore information: https://www.python.org/dev/peps/pep-0008/\n\"\"\"\n","sub_path":"ncea_level2/snippets/snip_l2_07_g.py","file_name":"snip_l2_07_g.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"93354385","text":"'''\nCreated on Sep 11, 2013\n\n@author: fli\n'''\nfrom urlparse import urlparse\n\nUNSUPPORTED_URL_FRAGMENT = [\n 'v','s','tv','letv','video',#video\n 'slide','pic','picture','pictures','gallery','photo','photoview',#image\n 'club','forum','bbs',#forum\n 't','weibo',#weibo\n ]\nUNSUPPORTED_URL_PATH = [\n #'tv','video','videos',#video\n #'slide','pic','picture','pictures','gallery','photo','photoview',#image\n 'match',#match report\n 'search',#search result\n ]\n\nWHITE_LIST = [\n 'bbs.huanqiu.com',\n 'qing.weibo.com',\n]\n\ndef is_supported(link):\n url = urlparse(link)\n if url.netloc.lower() in WHITE_LIST:\n return True\n for fragment in url.netloc.lower().split('.'):\n if fragment in UNSUPPORTED_URL_FRAGMENT:\n return False\n for path in url.path.lower().split('/')[:-1]:\n if path in UNSUPPORTED_URL_PATH:\n return False\n return True\n","sub_path":"admin/admin/weibonews/rollnews/utils/newsfilter.py","file_name":"newsfilter.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"285341006","text":"#encoding: utf-8\nfrom OpenOrange import *\nfrom GlobalTools import *\nimport cPickle\n\nParentUserReportSpecWindow = SuperClass(\"UserReportSpecWindow\",\"Window\",__file__)\nclass UserReportSpecWindow(ParentUserReportSpecWindow):\n\n def afterEditRow(self, fieldname, rowfieldname, rownr):\n afterEditRow(self, fieldname, rowfieldname, rownr)\n\n def updateFieldSpecs(self):\n record = self.getRecord()\n if (hasattr(record,\"CurrentReport\")):\n record.fillReportFields(record.CurrentReport)\n\n def buttonClicked(self, buttonname):\n if (buttonname == \"updateFieldSpecs\"):\n self.updateFieldSpecs()\n \n def changeSize(self):\n from WindowState import WindowState\n wstate = WindowState.bring(currentUser(),self.name())\n if (wstate):\n from WindowStateWindow import WindowStateWindow\n wswin = WindowStateWindow()\n wswin.setRecord(wstate)\n wswin.open()","sub_path":"base/windows/UserReportSpecWindow.py","file_name":"UserReportSpecWindow.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"493380186","text":"# coding=utf-8\n# !/usr/bin/python\n\n# version 1.0\n__author__ = 'leo'\n\nfrom os import path, makedirs\nimport json, requests, time, random, hashlib\nfrom werkzeug.contrib.fixers import ProxyFix\nfrom flask import Flask, request, Response\nfrom sqlalchemy import Column, create_engine, INT, VARCHAR, TEXT, ForeignKey, DATETIME, TIMESTAMP\nfrom sqlalchemy.orm import sessionmaker, relationship\nfrom sqlalchemy.ext.declarative import declarative_base\n\nurl_db = 'mysql+mysqlconnector://root:shixi1992@58bd54b1c0efd.bj.cdb.myqcloud.com:7413/lxsp'\n\napp = Flask(__name__)\nBase = declarative_base()\nengine = create_engine(url_db, encoding='utf-8', echo=True)\nDBSession = sessionmaker(bind=engine)\n\n\nclass AppVersion(Base):\n __tablename__ = 'app_version'\n id = Column(INT, autoincrement=True, primary_key=True)\n version = Column(VARCHAR)\n url = Column(VARCHAR)\n content = Column(TEXT)\n time = Column(TIMESTAMP)\n\n\nclass BuyHistory(Base):\n __tablename__ = 'buy_history'\n id = Column(INT, autoincrement=True, primary_key=True)\n user_id = Column(INT)\n video_id = Column(INT)\n time = Column(TIMESTAMP)\n\n def __init__(self, user_id, video_id):\n self.user_id = user_id\n self.video_id = video_id\n\n\nclass Comment(Base):\n __tablename__ = 'comment'\n id = Column(INT, autoincrement=True, primary_key=True)\n user_id = Column(INT)\n video_id = Column(INT)\n comment = Column(TEXT)\n time = Column(TIMESTAMP)\n\n def __init__(self, user_id, video_id, comment):\n self.user_id = user_id\n self.video_id = video_id\n self.comment = comment\n\n\nclass Open(Base):\n __tablename__ = 'open'\n id = Column(INT, autoincrement=True, primary_key=True)\n user_id = Column(INT)\n video_id = Column(INT)\n time = Column(TIMESTAMP)\n\n def __init__(self, user_id, video_id):\n self.user_id = user_id\n self.video_id = video_id\n\n\nclass Star(Base):\n __tablename__ = 'star'\n id = Column(INT, autoincrement=True, primary_key=True)\n user_id = Column(INT)\n video_id = Column(INT)\n time = Column(TIMESTAMP)\n\n def __init__(self, user_id, video_id):\n self.user_id = user_id\n self.video_id = video_id\n\n\nclass Suggestion(Base):\n __tablename__ = 'suggestion'\n id = Column(INT, autoincrement=True, primary_key=True)\n user_id = Column(INT)\n contact = Column(VARCHAR)\n suggestion = Column(TEXT)\n time = Column(TIMESTAMP)\n\n def __init__(self, user_id, contact, suggestion):\n self.user_id = user_id\n self.contact = contact\n self.suggestion = suggestion\n\n\nclass User(Base):\n __tablename__ = 'user'\n id = Column(INT, autoincrement=True, primary_key=True)\n money = Column(INT)\n username = Column(VARCHAR)\n password = Column(VARCHAR)\n email = Column(VARCHAR)\n phone = Column(VARCHAR)\n img_url = Column(VARCHAR)\n time = Column(TIMESTAMP)\n\n def __init__(self, money, username, password, email, phone, img_url):\n self.money = money\n self.username = username\n self.password = password\n self.email = email\n self.phone = phone\n self.img_url = img_url\n\n\n# 视频类\nclass Video(Base):\n __tablename__ = 'video'\n id = Column(INT, autoincrement=True, primary_key=True)\n author_id = Column(INT)\n price = Column(INT)\n img_url = Column(VARCHAR)\n video_url = Column(VARCHAR)\n title = Column(VARCHAR)\n describe = Column(TEXT)\n time = Column(TIMESTAMP)\n\n def __init__(self, author_id, price, img_url, video_url, title, describe):\n self.author_id = author_id\n self.price = price\n self.img_url = img_url\n self.video_url = video_url\n self.title = title\n self.describe = describe\n\n\n# 获取免费视频列表\n@app.route('/v1/videos/free', methods={'GET'})\ndef get_free_video():\n session = DBSession()\n user_id = request.args.get('user_id', '1')\n limit_id = request.args.get('limit_id', '1')\n if int(limit_id) == -100:\n # 存在的最大id\n m = session.query(Video).order_by(Video.id.desc()).limit(1).one().id\n else:\n # 客户端请求发送小于等于此id的行\n m = int(limit_id)\n video_list = session.query(Video).filter(Video.id <= m).filter(Video.author_id == 1).filter(Video.price == 0) \\\n .order_by(Video.id.desc()).limit(15).all()\n back_list = []\n for video in video_list:\n s = session.query(Star).filter(Star.video_id == video.id).filter(Star.user_id == user_id).count()\n json_dict = {\n 'id': video.id,\n 'img_url': video.img_url,\n 'video_url': video.video_url,\n 'time': video.time.strftime('%Y-%m-%d %H:%M:%S'),\n 'open': session.query(Open).filter(Open.video_id == video.id).count(),\n 'star': session.query(Star).filter(Star.video_id == video.id).count(),\n 'starred': s != 0\n }\n back_list.append(json_dict)\n session.close()\n return Response(json.dumps(back_list, ensure_ascii=False), status=200, mimetype='application/json')\n\n\n# 获取会员视频列表\n@app.route('/v1/videos/vip', methods={'GET'})\ndef get_vip_video():\n session = DBSession()\n user_id = request.args.get('user_id', '1')\n limit_id = request.args.get('limit_id', '1')\n if int(limit_id) == -100:\n # 存在的最大id\n m = session.query(Video).order_by(Video.id.desc()).limit(1).one().id\n else:\n # 客户端请求发送小于等于此id的行\n m = int(limit_id)\n video_list = session.query(Video).filter(Video.id <= m).filter(Video.author_id == 1).filter(Video.price == 1) \\\n .order_by(Video.id.desc()).limit(15).all()\n back_list = []\n for video in video_list:\n s = session.query(Star).filter(Star.video_id == video.id).filter(Star.user_id == user_id).count()\n json_dict = {\n 'id': video.id,\n 'img_url': video.img_url,\n 'video_url': video.video_url,\n 'time': video.time.strftime('%Y-%m-%d %H:%M:%S'),\n 'open': session.query(Open).filter(Open.video_id == video.id).count(),\n 'star': session.query(Star).filter(Star.video_id == video.id).count(),\n 'starred': s != 0\n }\n back_list.append(json_dict)\n session.close()\n return json.dumps(back_list, ensure_ascii=False)\n\n\n# 获取用户分享视频列表\n@app.route('/v1/videos/user', methods={'GET'})\ndef get_user_video():\n session = DBSession()\n user_id = request.args.get('user_id', '1')\n limit_id = request.args.get('limit_id', '1')\n if int(limit_id) == -100:\n # 存在的最大id\n m = session.query(Video).order_by(Video.id.desc()).limit(1).one().id\n else:\n # 客户端请求发送小于等于此id的行\n m = int(limit_id)\n video_list = session.query(Video).filter(Video.id <= m).filter(Video.author_id != 1) \\\n .order_by(Video.id.desc()).limit(15).all()\n back_list = []\n for video in video_list:\n s = session.query(Star).filter(Star.video_id == video.id).filter(Star.user_id == user_id).count()\n b = session.query(BuyHistory).filter(BuyHistory.video_id == video.id).filter(BuyHistory.user_id == user_id).count()\n author_name = session.query(User).filter(User.id == video.author_id).limit(1).one().username\n author_img_url = session.query(User).filter(User.id == video.author_id).limit(1).one().img_url\n json_dict = {\n 'id': video.id,\n 'img_url': video.img_url,\n 'video_url': video.video_url,\n 'time': video.time.strftime('%Y-%m-%d %H:%M:%S'),\n 'open': session.query(Open).filter(Open.video_id == video.id).count(),\n 'star': session.query(Star).filter(Star.video_id == video.id).count(),\n 'author_id': video.author_id,\n 'author_name': author_name,\n 'author_img_url': author_img_url,\n 'price': video.price,\n 'starred': s != 0,\n 'bought': b != 0\n }\n back_list.append(json_dict)\n session.close()\n return json.dumps(back_list, ensure_ascii=False)\n\n\n# 点赞or取消点赞\n@app.route('/v1/star//', methods={'GET'})\ndef change_star(video_id, user_id):\n session = DBSession()\n m = session.query(Star).filter(Star.video_id == video_id).filter(Star.user_id == user_id).count()\n if m == 0:\n session.add(Star(user_id=int(user_id), video_id=int(video_id)))\n else:\n star = session.query(Star).filter(user_id == user_id).filter(video_id == video_id).order_by(Star.id) \\\n .limit(1).one()\n session.delete(star)\n session.commit()\n session.close()\n return json.dumps(session.query(Star).filter(Star.video_id == video_id).count(), ensure_ascii=False)\n\n\n# 标记看过\n@app.route('/v1/open//', methods={'GET'})\ndef add_open(video_id, user_id):\n session = DBSession()\n m = session.query(Open).filter(Open.video_id == video_id).filter(Open.user_id == user_id).count()\n if m == 0:\n session.add(Open(user_id=int(user_id), video_id=int(video_id)))\n session.commit()\n session.close()\n return json.dumps(1, ensure_ascii=False)\n\n\n# 上传意见或建议\n@app.route('/v1/suggestion', methods={'POST'})\ndef add_sugesstion():\n session = DBSession()\n user_id = request.form.get('user_id', '1')\n contact = request.form.get('contact', '01234567890')\n suggestion = request.form.get('suggestion', 'nothing')\n session.add(Suggestion(user_id=int(user_id), contact=contact, suggestion=suggestion))\n session.commit()\n session.close()\n return json.dumps(1, ensure_ascii=False)\n\n\n# 获取最新APP版本\n@app.route('/v1/app_version', methods={'GET'})\ndef get_app_version():\n session = DBSession()\n v = session.query(AppVersion).order_by(AppVersion.id.desc()).limit(1).one()\n session.close()\n json_dict = {\n 'id': v.id,\n 'url': v.url,\n 'version': v.version,\n 'time': v.time.strftime('%Y-%m-%d %H:%M:%S'),\n 'content': v.content\n }\n return json.dumps(json_dict, ensure_ascii=False)\n\n\n# 下载APK安装包\n\n\n\n# 上传视频信息\n@app.route('/v1/videos/upload', methods={'POST'})\ndef add_video():\n session = DBSession()\n author_id = request.form.get('author_id', '1')\n price = request.form.get('price', '1')\n img_url = request.form.get('img_url', 'nothing')\n video_url = request.form.get('video_url', 'nothing')\n title = request.form.get('title', '无标题')\n describe = request.form.get('describe', '空')\n session.add(Video(author_id=int(author_id), price=int(price), img_url=img_url, video_url=video_url, title=title,\n describe=describe))\n session.commit()\n session.close()\n return json.dumps(1, ensure_ascii=False)\n\n\n# 获取评论列表\n@app.route('/v1/comments//', methods={'GET'})\ndef get_comments(limit_id, video_id):\n session = DBSession()\n if int(limit_id) == -100:\n # 存在的最大id\n m = session.query(Comment).order_by(Comment.id.desc()).limit(1).one().id\n else:\n # 客户端请求发送小于等于此id的行\n m = int(limit_id)\n comment_list = session.query(Comment).filter(Comment.video_id == video_id).filter(Comment.id <= m) \\\n .order_by(Comment.id.desc()).limit(15).all()\n back_list = []\n for comment in comment_list:\n json_dict = {\n 'user_id': comment.user_id,\n 'user_name': session.query(User).filter(User.id == comment.user_id).limit(1).one().username,\n 'user_img_url': session.query(User).filter(User.id == comment.user_id).limit(1).one().img_url,\n 'video_id': comment.video_id,\n 'comment': comment.time.strftime('%Y-%m-%d %H:%M:%S'),\n 'time': session.query(Comment).filter(Comment.video_id == comment.id).count(),\n }\n back_list.append(json_dict)\n session.close()\n return json.dumps(back_list, ensure_ascii=False)\n\n\napp.wsgi_app = ProxyFix(app.wsgi_app)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"lxsp.py","file_name":"lxsp.py","file_ext":"py","file_size_in_byte":11292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"414441223","text":"import os\nfrom shutil import copy2\n\ndata_path = 'data\\\\extracted_images'\ntrain_path = 'data\\\\math_symbols\\\\train'\ntest_path = 'data\\\\math_symbols\\\\test'\n\n#5 classes\nincludedLabels = ['+','-','times',',','forward_slash']\nos.mkdir(train_path)\nos.mkdir(test_path)\nlabels = os.listdir(data_path)\nfor label in labels:\n if label in includedLabels:\n path = os.path.join(data_path, label)\n print(os.listdir(path))\n numfiles = len(os.listdir(path))\n print(numfiles)\n threshold = 80/100 * numfiles\n print(threshold)\n iterator = 0\n os.mkdir(os.path.join(train_path, label))\n os.mkdir(os.path.join(test_path, label))\n\n for file in os.listdir(path):\n iterator += 1\n print(file)\n srcpath = os.path.join(path, file)\n if (iterator < threshold):\n dstpath = os.path.join(train_path, label)\n else:\n dstpath = os.path.join(test_path, label)\n\n copy2(srcpath, dstpath)","sub_path":"split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"386778022","text":"# Reverse proxy with load balancer\n\nimport socket, errno\n\n#import thread module\nfrom _thread import *\nimport threading\nfrom threading import Timer\n\nimport sys\nimport argparse\nimport json\nimport os\nimport signal\n\nBUFF_SIZE = 1024\n\nclass ReverseProxy(object):\n def __init__(self, port):\n super().__init__()\n \n self.switch_table = {}\n self.host = ''\n self.port = port\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\n try:\n self.socket.bind((self.host, self.port))\n except socket.error as e:\n print(str(e))\n \n self.listen()\n\n def listen(self):\n self.socket.listen(10)\n print(\"Reverse proxy is listening on port {0}\".format(self.port))\n while True:\n conn, addr = self.socket.accept()\n \n print(\"Connected to {0}:{1}\".format(addr[0], addr[1]))\n \n #reverse proxy forks a thread and pass the connection\n # socket to this thread\n # self.handle_client_connection(client_conn, client_addr)\n start_new_thread(self.multi_thread, (conn,)) \n \n # self.serve(s)\n self.socket.close()\n \n def multi_thread(self, conn):\n while True:\n data = conn.recv(BUFF_SIZE)\n if not data:\n print('Connection disconnected.')\n break\n #lock released on exit\n # print_lock.release()\n # break\n \n\n data = json.loads(data) #convert string to json object\n \n if(data['type'] == 1):\n self.handle_server_setup(data,conn)\n elif(data['type'] == 0):\n self.handle_client_connection(data,conn)\n # elif(data['type'] == 2):\n # response = self.handle_server_connection(data,conn)\n \n # send back response\n # conn.send(response)\n\n # response = json.dumps(response)\n # conn.sendall(bytes(response, encoding=\"utf-8\"))\n\n # connection closed\n conn.close()\n \n \n # When reverse proxy receives the setup message, it creates \n # a message switch table that records the server id, its\n # privacy policy and the port number the server is listening\n def handle_server_setup(self, message, conn):\n print(\"Handling server setup...\")\n print('Received setup message from server id {0}, privacy policy {1}, port {2}'\\\n .format(message['id'], message['privPolyId'], message['listenport']))\n \n server_id = message['id']\n policy_id = message['privPolyId']\n server_port = message['listenport']\n server = [server_id,server_port, True]\n \n if policy_id in self.switch_table:\n if server not in self.switch_table[policy_id]:\n self.switch_table[policy_id].append(server)\n print(self.switch_table)\n else:\n self.switch_table[policy_id] = [server]\n print(self.switch_table)\n \n ack = {\n 'Status': 'Successfully setup with reverse proxy'\n }\n \n response = json.dumps(ack)\n conn.sendall(bytes(response, encoding=\"utf-8\"))\n\n\n def handle_client_connection(self, message,conn):\n print(\"Handling client connection ... \")\n print(\"Received a data message from client id {0}, privacy policy {1}, payload: {2}\"\\\n .format(message['srcid'], message['privPoliId'], message['payload']))\n \n # Look up requested privacy policy in switch table\n policy_id = message['privPoliId']\n if policy_id in self.switch_table:\n servers = self.switch_table[policy_id]\n \n for idx, server in enumerate(servers):\n if server[2] == False:\n send = False\n if idx == len(servers) - 1:\n r = Timer(2.0, self.forward_message, (message, servers,conn,policy_id))\n r.start()\n else: \n print(\"Server is busy. Please wait.\")\n continue\n \n else:\n print(\"Policy exists. Connect to the server and send message\")\n \n serverPort = server[1]\n print(\"Connect to server\", server)\n \n server[2] = False\n self.switch_table[policy_id][idx] = server\n print(self.switch_table)\n print(\"Forwarding a data message from client id {0} to server id {1}, payload: {2}\"\\\n .format(message['srcid'], server[0], message['payload']))\n #Create a socket connection to this server, get response and update the switch table.\n serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \n check_socket_open = serverSocket.connect_ex((self.host, serverPort))\n # try:\n # serverSocket.connect((self.host,serverPort))\n # except socket.error as e:\n # print(str(e))\n \n if check_socket_open == 0:\n print(\"Port is open\")\n else:\n print(\"Port is not open. Create new connection to server.\")\n # try:\n serverSocket.connect((self.host,serverPort))\n # except socket.error as e:\n # print(str(e))\n \n while True:\n \n message = json.dumps(message)\n \n serverSocket.sendall(bytes(message,encoding=\"utf-8\"))\n # message received from server\n response = serverSocket.recv(1024)\n response = json.loads(response)\n \n if response:\n print(\"Received a data message from server id {0}, payload: {1}\"\\\n .format(response['srcid'], response['payload']))\n \n print(\"Forwarding a data message to client {0}, payload: {1}\"\\\n .format(response['destid'], response['payload']))\n response= json.dumps(response)\n conn.sendall(bytes(response, encoding=\"utf-8\"))\n\n \n server[2]=True\n self.switch_table[policy_id][idx] = server\n print(self.switch_table)\n \n \n serverSocket.close()\n self.switch_table[policy_id].remove(server)\n # print(server)\n break\n else:\n print(\"Policy does not exist.\")\n response = {'Error': 'No server currently serving this privacy policy'}\n response= json.dumps(response)\n conn.sendall(bytes(response, encoding=\"utf-8\"))\n \n\n\n def handle_server_connection(self,message, conn):\n print('Received a data message from server id {0}, payload {1}'\\\n .format(message['id'], message['payload']))\n \n return message\n \n \n def forward_message(self,message, servers, conn,policy_id):\n \n print(\"Rescan the switch table\")\n for idx, server in enumerate(servers):\n if server[2] == True:\n serverPort = server[1]\n print(\"Connect to server\", server)\n \n server[2] = False\n self.switch_table[policy_id][idx] = server\n print(self.switch_table)\n print(\"Forwarding a data message from client id {0} to server id {1}, payload: {2}\"\\\n .format(message['srcid'], server[0], message['payload']))\n #Create a socket connection to this server, get response and update the switch table.\n serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \n check_socket_open = serverSocket.connect_ex((self.host, serverPort))\n # try:\n # serverSocket.connect((self.host,serverPort))\n # except socket.error as e:\n # print(str(e))\n \n if check_socket_open == 0:\n print(\"Port is open\")\n else:\n print(\"Port is not open. Create new connection to server.\")\n # try:\n serverSocket.connect((self.host,serverPort))\n # except socket.error as e:\n # print(str(e))\n \n while True:\n \n message = json.dumps(message)\n \n serverSocket.sendall(bytes(message,encoding=\"utf-8\"))\n # message received from server\n response = serverSocket.recv(1024)\n response = json.loads(response)\n \n if response:\n print(\"Received a data message from server id {0}, payload: {1}\"\\\n .format(response['srcid'], response['payload']))\n \n print(\"Forwarding a data message to client {0}, payload: {1}\"\\\n .format(response['destid'], response['payload']))\n response= json.dumps(response)\n conn.sendall(bytes(response, encoding=\"utf-8\"))\n \n server[2]=True\n self.switch_table[policy_id][idx] = server\n print(self.switch_table)\n \n serverSocket.close()\n break\n\n \n# parse commandline arguments\n# initialize the parser\nparser = argparse.ArgumentParser(description='Process arguments.')\n\n# add arguments\nparser.add_argument('-port', type=int, help='port number of reverse proxy')\n\n# parse\nargs = parser.parse_args()\n\nproxy = ReverseProxy(args.port)","sub_path":"HW1/revproc.py","file_name":"revproc.py","file_ext":"py","file_size_in_byte":10586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"399621295","text":"#Does not work for large inputs\n#Takes longer than 1 second to process when N>20000\n\nN = int(input())\n\nnum_trees = N//2 if N%2==0 else N//2+1\n\ndef all_tree_yeah(N, num):\n global num_trees\n for i in range(2, N-num+1):\n wk = N//i\n if wk>2:\n num1 = wk//2 if wk%2==0 else wk//2+1\n num_trees+=num1\n all_tree_yeah(wk, num1)\n else:\n num_trees+=1\n\nall_tree_yeah(N, num_trees)\nprint(num_trees)\n\n","sub_path":"2018/S4.py","file_name":"S4.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"18233454","text":"__author__ = \"Maximus Mutschler\"\n__version__ = \"1.0\"\n__email__ = \"maximus.mutschler@uni-tuebingen.de\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.framework import is_tensor\nimport matplotlib.pyplot as plt\nimport os\n\n\n\nclass PalOptimizer:\n \"\"\"\n Approximates the loss in negative gradient direction with a parabolic function.\n Uses minimum of approximation for weight update.\n !!!!!\n IMPORTANT, READ THE INFORMATION BELOW!!!!\n !!!!!\n This optimizer can't be used like usual TensorFlow optimizers. The reason is that one train step of PAL\n needs multiple graph inferences over the same input data.\n 1. Use Variables for your input data. Load a new batch each time before you call PAL's do_train_step method.\n 2. Exclude all random operators from your graph. (like Dropout , ShakeDrop or Shake-Shake).\n In general, they are not supported by PAL, since, if used, the loss function changes with each inference.\n However, random operators are supported, if they are implemented in a way that they can reuse random chosen\n numbers for multiple inferences.\n \"\"\"\n\n # tunable parameters\n loose_approximation_factor = None\n momentum = None\n measuring_step_size = None\n max_step_size = None\n\n # region initialization\n def __init__(self, loss_tensor, measuring_step_size=0.1, momentum=0.6, loose_approximation_factor=0.6,\n max_step_size=1, gradients=None, global_step=None, calc_exact_directional_derivative=False,\n is_plot=False, plot_step_interval=10, save_dir=\"/tmp/pt.lineopt/lines/\"):\n \"\"\"\n :param loss_tensor: only scalar loss tensors are supported in the moment\n :param measuring_step_size: python scalar or tf.tensor are accepted. Should have the same decay as max_step_size\n Good values are between 0.01 and 0.1\n :param momentum: python scalar or tf.tensor are accepted\n Good values are either 0 or 0.6\n :param loose_approximation_factor: intentionally approximates the function with less or more curvature\n Values between 0 and inf (inf exclusive) are accepted. Values <1 lead to approximations with less curvature.\n python scalar or tf.tensor are accepted. Good values are between 0.4 and 0.6\n :param max_step_size: python scalar or tf.tensor are accepted. Same decay as for measuring_step_size should be\n applied\n Good values are between 0.1 and 1.\n :param gradients: (grad,corresponding variable) tuple list\n :param global_step: step counter\n :param calc_exact_directional_derivative: more exact approximation but more time consuming (not recommended)\n :param is_plot: plot lines in gradient direction as well as the parabolic approximation. Latex has to be\n installed for plotting.\n :param plot_step_interval: defines how often a line is plotted.\n :save_dir: plot save location\n \"\"\"\n if is_plot is True and not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n self._sess = tf.get_default_session()\n\n self.loose_approximation_factor = loose_approximation_factor\n self.momentum = momentum\n self.measuring_step_size = measuring_step_size\n self.max_step_size = max_step_size\n\n self.epsilon = 1e-15\n\n self._loss_tensor = loss_tensor\n self.calc_exact_directional_derivative = calc_exact_directional_derivative\n self.is_plot = is_plot\n self.plot_step_interval = plot_step_interval\n self.save_dir = save_dir\n\n if global_step is None:\n self._global_step = tf.Variable(0.0, trainable=False, name=\"global_step\")\n else:\n self._global_step = global_step\n\n if gradients is None:\n self._train_vars = tf.trainable_variables()\n self._gradient_tensors = list(tf.gradients(loss_tensor, tf.trainable_variables()))\n\n else:\n self._train_vars = [e[1] for e in gradients]\n self._gradient_tensors = [e[0] for e in gradients] # same order holds with tf >= 1.10\n\n self._increase_global_step_op = tf.assign(self._global_step, self._global_step + 1)\n self._step_on_line_plh = tf.placeholder(tf.float32, shape=(), name=\"line_step_size\")\n\n # Build additional graph variables and operators\n self._create_line_gradient_variables()\n self._create_momentum_norm_and_derivative_ops()\n self._create_weight_update_ops()\n print(\"successfully initialized PAL optimizer\")\n return\n\n def _create_line_gradient_variables(self):\n \"\"\"\n Creates variables in which the current adapted gradient (= negative line direction)\n (usually -(last_gradient*momentum+gradient)) is saved.\n :return: --\n \"\"\"\n with tf.variable_scope(\"Line_Direction_Variables\"):\n self.gradient_vars = []\n for gradient_tensor in self._gradient_tensors:\n new_var = tf.Variable(tf.zeros(gradient_tensor.shape), trainable=False, name=gradient_tensor.name[0:-2])\n self.gradient_vars.append(new_var)\n\n def _create_momentum_norm_and_derivative_ops(self):\n \"\"\"\n Creates ops that calculate, adapt and saves the gradient, to get the norm of the gradient and\n to get the directional derivative.\n :return: --\n \"\"\"\n with tf.name_scope(\"Momentum_Norm_Derivative_Operators\"):\n self._gradient_vars_assign_ops = []\n directional_deriv = tf.constant(0.0)\n norm_grad_mom = tf.constant(0.0)\n self.norm_of_gradient_var = tf.Variable(0.0, trainable=False, name=\"norm_of_gradient_var\")\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) # important for batch normalization\n if self.momentum != 0:\n for grad_tensor, gradient_var in zip(self._gradient_tensors, self.gradient_vars):\n # Update ops important for batch normalization\n # since _gradient_vars_assign_ops is always evaluated together with the loss op it\n # is valid to put the dependency here\n grad_mom = gradient_var * self.momentum + grad_tensor\n norm_grad_mom = tf.add(norm_grad_mom, tf.reduce_sum(tf.multiply(grad_mom, grad_mom)))\n if self.calc_exact_directional_derivative:\n directional_deriv = tf.add(directional_deriv, tf.reduce_sum(tf.multiply(grad_tensor, grad_mom)))\n with tf.control_dependencies(update_ops):\n grad_var_ass_op = (gradient_var.assign(grad_mom)).op\n self._gradient_vars_assign_ops.append(grad_var_ass_op)\n norm_grad_mom = tf.sqrt(norm_grad_mom)\n norm_grad_mom = tf.cond(tf.equal(norm_grad_mom, 0.0), lambda: self.epsilon, lambda: norm_grad_mom)\n if self.calc_exact_directional_derivative:\n directional_deriv = - directional_deriv / norm_grad_mom\n else:\n directional_deriv = -norm_grad_mom\n else:\n for grad_tensor, gradient_var in zip(self._gradient_tensors, self.gradient_vars):\n # Update ops important for batch normalization\n # since _gradient_vars_assign_ops is always evaluated together with the loss op it\n # is valid to put the dependency here\n norm_grad_mom = tf.add(norm_grad_mom, tf.reduce_sum(tf.multiply(grad_tensor, grad_tensor)))\n with tf.control_dependencies(update_ops):\n grad_var_ass_op = (gradient_var.assign(grad_tensor)).op\n self._gradient_vars_assign_ops.append(grad_var_ass_op)\n norm_grad_mom = tf.sqrt(norm_grad_mom)\n norm_grad_mom = tf.cond(tf.equal(norm_grad_mom, 0.0), lambda: self.epsilon, lambda: norm_grad_mom)\n directional_deriv = -norm_grad_mom\n self.ass_norm_grad_var = tf.assign(self.norm_of_gradient_var, norm_grad_mom)\n self.directional_derivative = directional_deriv\n\n def _create_weight_update_ops(self):\n \"\"\"\n Updates weights by step_on line * -grad / norm of step direction)\n :return: --\n \"\"\"\n with tf.name_scope(\"Weight_Update_Operators\"):\n self.weight_vars_assign_ops = []\n for weight_matrix, grad in zip(self._train_vars, self.gradient_vars):\n self.weight_vars_assign_ops.append(\n tf.assign_add(weight_matrix, self._step_on_line_plh * -grad / self.norm_of_gradient_var).op)\n\n def _get_loss_directional_deriv_and_save_gradient(self, additional_ops):\n \"\"\"\n Calculates loss and gradient at the current position. Saves the (adapted)\n gradient to gradient vars.\n :param additional_ops: additional operators that will get inferred from the graph\n :return: loss, results_of_additional_ops,\n \"\"\"\n loss, directional_deriv, _, _, results_of_additional_ops = self._sess.run(\n (self._loss_tensor, self.directional_derivative, self._gradient_vars_assign_ops, self.ass_norm_grad_var,\n additional_ops))\n return loss, directional_deriv, results_of_additional_ops\n\n def _do_line_step(self, step_size):\n \"\"\"\n moves all weights in negative gradient direction by step_size\n :param step_size: in negative gradient direction\n :return: loss at new position\n \"\"\"\n if step_size != 0:\n self._sess.run(self.weight_vars_assign_ops, feed_dict={self._step_on_line_plh: step_size})\n loss = self._sess.run((self._loss_tensor))\n return loss\n\n # endregion\n\n # region training\n\n def do_train_step(self, additional_ops):\n \"\"\"\n Does one training step. Look at the class documentation to get the requirements needed for a successful\n update step. Approximates a 1 dimensional parabolic function along the negative gradient direction.\n If the approximation is a negative line, a step of measuring_step_size is done in line direction.\n If the approximation is an other, unsuited parabola, no update step is done.\n :param additional_ops: additional operations that infer information from the graph\n :return: loss (before parameter update), additional_ops_results\n \"\"\"\n max_step_size = self._sess.run(self.max_step_size) if is_tensor(self.max_step_size) else self.max_step_size\n loose_approximation_factor = self._sess.run(self.loose_approximation_factor) if \\\n is_tensor(self.loose_approximation_factor) else self.loose_approximation_factor\n measuring_step = self._sess.run(self.measuring_step_size) if \\\n is_tensor(self.measuring_step_size) else self.measuring_step_size\n\n # does step to position on line, which got inferred in the last call of this function\n loss_at_current_position, line_derivative_current_pos, additional_ops_results = \\\n self._get_loss_directional_deriv_and_save_gradient(additional_ops)\n\n loss1 = loss_at_current_position\n loss2 = self._do_line_step(measuring_step)\n\n first_derivative_current_line_pos_plus_one_half = (loss2 - loss1) / measuring_step\n second_derivative_current_line_pos = loose_approximation_factor * (\n first_derivative_current_line_pos_plus_one_half - line_derivative_current_pos) / \\\n (measuring_step / 2)\n\n if np.isnan(second_derivative_current_line_pos) or np.isnan(line_derivative_current_pos) \\\n or np.isinf(second_derivative_current_line_pos) or np.isinf(line_derivative_current_pos):\n return loss1, additional_ops_results\n\n\n if second_derivative_current_line_pos > 0 and line_derivative_current_pos < 0:\n # approximation is positive (convex) square function.\n # Minimum is located in positive line direction. Should be the primary case.\n step_size_on_line = - line_derivative_current_pos / second_derivative_current_line_pos\n\n elif second_derivative_current_line_pos <= 0 and line_derivative_current_pos < 0:\n # l''<0, l'<0 approximation is negative (concave) square function.\n # maximum is located in negative line direction.\n # l''==0, l'<0 approximation is negative line\n # Second step was more negative. so we jump there.\n step_size_on_line = measuring_step\n else:\n # l'>0 can't happen since the first derivative is the norm of the gradient\n # l'==0\n # the current position is already an optimum\n step_size_on_line = 0\n\n if step_size_on_line > max_step_size:\n step_size_on_line = max_step_size\n\n step_to_target_point = step_size_on_line - measuring_step\n\n # plotting\n if self.is_plot:\n global_step = self._sess.run(self._global_step)\n if global_step % self.plot_step_interval == 1:\n self.plot_loss_line_and_approximation(measuring_step / 10, step_to_target_point,\n measuring_step, second_derivative_current_line_pos,\n line_derivative_current_pos, loss1, loss2, self.save_dir)\n\n if step_to_target_point != 0:\n self._sess.run(self.weight_vars_assign_ops, feed_dict={self._step_on_line_plh: step_to_target_point})\n\n self._sess.run(self._increase_global_step_op)\n\n return loss1, additional_ops_results\n\n def __str__(self):\n dict_ = {\"measuring_step_size\": self.measuring_step_size, \"momentum\": self.momentum,\n \"loose_approximation_factor\": self.loose_approximation_factor, \"max_step_size\": self.max_step_size}\n param_string = ', '.join(\"{!s}={!r}\".format(k, v) for (k, v) in dict_.items())\n return self.__class__.__name__ + \"_\" + param_string\n\n # region plotting\n def plot_loss_line_and_approximation(self, resolution, a_min, mu, loss_d2, loss_d1_0, loss_0, loss_mu,\n save_dir):\n real_a_min = a_min + mu\n line_losses = []\n max_step = max(real_a_min * 2, mu)\n interval = list(np.arange(-resolution, max_step + 2 * resolution, resolution))\n line_losses.append(self._do_line_step(-mu - resolution))\n\n for i in range(len(interval) - 1):\n line_losses.append(self._do_line_step(resolution))\n\n # parabola parameters:\n a = loss_d2 / 2\n b = loss_d1_0\n c = loss_0\n\n def parabolic_function(x, a, b, c):\n \"\"\"\n :return: value of f(x)= a(x-t)^2+b(x-t)+c\n \"\"\"\n return a * x ** 2 + b * x + c\n\n x = interval\n x2 = list(np.arange(-resolution, 1.1 * resolution, resolution))\n approx_values = [parabolic_function(x_i, a, b, c) for x_i in x]\n grad_values = [b * x2_i + c for x2_i in x2]\n global_step = int(self._sess.run(self._global_step))\n\n plt.rc('text', usetex=True)\n plt.rc('font', serif=\"Times\")\n scale_factor = 1\n tick_size = 21 * scale_factor\n labelsize = 23 * scale_factor\n headingsize = 26 * scale_factor\n fig_sizes = np.array([10, 8]) * scale_factor\n linewidth = 4.0\n\n fig = plt.figure(0)\n fig.set_size_inches(fig_sizes)\n plt.plot(x, line_losses, linewidth=linewidth)\n plt.plot(x, approx_values, linewidth=linewidth)\n plt.plot(x2, grad_values, linewidth=linewidth)\n plt.axvline(real_a_min, color=\"red\", linewidth=linewidth)\n y_max = max(line_losses)\n y_min = min(min(approx_values), min(line_losses))\n plt.ylim([y_min, y_max])\n plt.scatter(0, loss_0, color=\"black\", marker='x', s=100, zorder=10, linewidth=linewidth)\n plt.scatter(mu, loss_mu, color=\"black\", marker='x', s=100, zorder=10, linewidth=linewidth)\n plt.legend([\"loss\", \"approximation\", \"derivative\", \"update step\", \"loss measurements\"], fontsize=labelsize,\n loc=\"upper center\")\n plt.xlabel(r\"step on line\", fontsize=labelsize)\n plt.ylabel(\"loss in line direction\", fontsize=labelsize)\n\n plt.title(\"update step {0:d}\".format(global_step), fontsize=headingsize)\n\n plt.gca().tick_params(\n axis='both',\n which='both',\n labelsize=tick_size\n )\n plt.gca().ticklabel_format(style='sci')\n plt.gca().yaxis.get_offset_text().set_size(tick_size)\n\n plt.savefig(\"{0}line{1:d}.png\".format(save_dir, global_step))\n print(\"plottet line {0}line{1:d}.png\".format(save_dir, global_step))\n # plt.show(block=True)\n plt.close(0)\n self._do_line_step(-(len(interval) - 1) * resolution + mu)\n\n #endregion\n","sub_path":"TensorFlow/pal_optimizer.py","file_name":"pal_optimizer.py","file_ext":"py","file_size_in_byte":16911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"567672070","text":"# -*- coding: utf-8 -*-#\n\n#-------------------------------------------------------------------------------\n# Name: word_search\n# Description: 二维网格中的单词搜索问题\n# Author: zhaomengyi\n# Date: 2021/5/19\n# NO:LC212\n# 解法:将查找的单词生成一个字典树,然后对board表进行遍历,从起点开始枚举,在生成的trie树上进行dfs\n#-------------------------------------------------------------------------------\nimport collections\nfrom typing import List\n\nfrom xlwings import xrange\n\ndx = [-1,1,0,0]\ndy = [0,0,-1,1]\n\nEND_OF_WORD = \"#\"\nclass Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n if not board or not board[0]:return []\n if not words:return []\n\n self.result = set()\n\n root = collections.defaultdict()\n for word in words:\n node = root\n for char in word:\n node = node.setdefault(char,collections.defaultdict())\n node[END_OF_WORD] = END_OF_WORD\n\n self.m,self.n = len(board),len(board[0])\n\n for i in range(self.m):\n for j in range(self.n):\n if board[i][j] in root:\n self._dfs(board,i,j,\"\",root)\n\n return list(self.result)\n\n\n def _dfs(self,board,i,j,cur_word,cur_dict):\n cur_word += board[i][j]\n cur_dict = cur_dict[board[i][j]]\n\n if END_OF_WORD in cur_dict:\n self.result.add(cur_word)\n\n tmp,board[i][j] = board[i][j],'@'\n for k in range(4):\n x,y = i + dx[k],j+dy[k]\n if 0<=x 0) :\n simvrlib.simvrGetBackLog.restype = c_char_p #for unix\n p = create_string_buffer(size)\n simbuffer = cast(simvrlib.simvrGetBackLog(),c_char_p)\n memmove(p, simbuffer, size)\n simvrbufferString = p.value.decode()\n print(simvrbufferString.rstrip(\"\\n\"))\n simvrlib.simvrClearBackLog()\n\ndef simvrUpdateState() :\n global simvrIsOpen\n global simvrlib\n \n stateNo = simvrlib.simvrGetState();\n\n #State\n if(stateNo <= simvrStatus.Initial) :\n return False\n return True\n \ndef simvrUpdateSIMVR(roll, pitch, yaw) :\n global simvrIsOpen\n global simvrlib\n \n if(simvrIsOpen == False) :\n return\n\n packet = simvrPacket()\n packet.roll = roll\n packet.pitch = pitch\n packet.yaw = yaw\n\n packet.rotationMotionRatio = 1.0\n packet.gravityMotionRatio = 0.0\n \n simvrlib.simvrWrite(byref(packet));\n\n#---------------------------------------------------\n# Main Program\nsimvrAwake(\"\")\nprint (\"SIMVR-START...\")\n\ntime.sleep(1) #wait\n\nsimvrlib.simvrSetOriginMode(False)\nsimvrlib.simvrSetAxisProcessingMode(True)\n\nsimvrUpdateBackLog()\n\ntime.sleep(5) #wait\nif(simvrUpdateState()) : \n print(\"This program can change ROLL, PITCH, YAW of SIMVR from UDP/IP\\n\")\n\nwhile(simvrUpdateState()) :\n rolldata = 0.0\n pitchdata = 0.0\n yawdata = 0.0\n\n try:\n data, addr = sc.recvfrom(256)\n res = struct.unpack('>ff', data)\n print(data)\n except socket.error:\n print(\"UDP ERROR\")\n break\n\n simvrUpdateSIMVR(float(rolldata), float(pitchdata), float(yawdata))\n \nprint(\"SIMVR-SHUTDOWN\")\n\nsimvrDestroy()\nsc.close()\n#---------------------------------------------------\n","sub_path":"build_python/x86/simvr_python_udp.py","file_name":"simvr_python_udp.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"644447616","text":"# Copyright (C) 2017 Alpha Griffin\n# @%@~LICENSE~@%@\n\n\"\"\"\nTF_Curses\nAlphagriffin.com\nEric Petersen @Ruckusist \n\"\"\"\n\n__author__ = \"Eric Petersen @Ruckusist\"\n__copyright__ = \"Copyright 2017, The Alpha Griffin Project\"\n__credits__ = [\"Eric Petersen\", \"Shawn Wilson\", \"@alphagriffin\"]\n__license__ = \"***\"\n__version__ = \"0.0.1\"\n__maintainer__ = \"Eric Petersen\"\n__email__ = \"ruckusist@alphagriffin.com\"\n__status__ = \"Prototype\"\n\n# print(\"AGTFCP - Frontend Init\")","sub_path":"ag/tf_curses/frontend/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"505839516","text":"#NOMBRE:MICHAEL CARDENAS\n#PROGRAMACION AVANZADA\n#20/12/2016\n\nimport sys\nfrom tkinter import*\n\nmaster=Tk()\nwhatever_you_do=\"Bienvenido cierre la venatana del mensaje e ingrese un numero\"\nmsg=Message(master,text=whatever_you_do)\nmsg.config(bg='red',font=('times',18,'italic'))\nmsg.pack()\nmainloop()\n\ndef hacer_click():\n try:\n a=int(entrada_texto.get())\n a=a*5\n etiqueta.config(text=a)\n except ValueError:\n etiqueta.config(text=\"introduzca el numero porfavor\")\napp=Tk()\napp.title(\"MULTIPLICA EL NUMERO *5 \")\n \n#Ventana Principal\n\nvp = Frame(app)\nvp.grid(column=0, row=0, padx=(80,80), pady=(30,30))\nvp.columnconfigure(0, weight=5)\nvp.rowconfigure(0, weight=5)\n \netiqueta = Label(vp,text=\"ingrese el Valor\")\netiqueta.grid(column=2, row=2)\n \nboton = Button(vp, text=\"Aceptar\", command=hacer_click)\nboton.grid(column=1, row=1)\n\nboton2=Button(vp, text='Cerrar', command=vp.destroy)\nboton2.grid(column=6, row=6)\n \nvalor = \"\"\nentrada_texto = Entry(vp,textvariable=valor)\nentrada_texto.grid(column=2, row=1)\n\n\n \napp.mainloop()\n","sub_path":"20122016deber_taller1CardenasMichael/numero y se multiplica x 5.py","file_name":"numero y se multiplica x 5.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"152714678","text":"\n# coding: utf-8\n\n# In[18]:\n\nimport requests\nimport datetime as dt\nimport os\nimport json\npath = \"C:\\\\Shamal\\\\NEU\\\\Python\\\\MidTerm\\\\StackData\\\\\"\n\nbadgefiles = []\nos.chdir(path)\nfor a in os.listdir(path):\n if os.path.isfile(os.path.join(path,a)) and 'badgeUser' in a:\n badgefiles.append(a)\n#print (badgefiles)\n\nbadgeTypeList = []\nfor file in badgefiles:\n with open(file,'r') as json_data:\n a = json.load(json_data)\n data = a['items']\n for i in data:\n if (i['name'] not in badgeTypeList):\n badgeTypeList.append(i['name'])\n#print (badgeTypeList)\n\nbadgeDetail=[]\nfor badge in badgeTypeList:\n count = 0\n for file in badgefiles:\n with open(file,'r') as json_data:\n a = json.load(json_data)\n data = a['items']\n for i in data:\n if (i['name'] == badge):\n count = count+1\n \n #print (count)\n #print (badge)\n badgeDetail.append([badge, count])\n \n \n \nimport csv\ndef getitem(item):\n return item[1]\n\ntestList =[]\ntestList = sorted(badgeDetail, key=getitem, reverse= True)\n#print (testList)\n\nwith open('Analysis3Output.csv', 'w',newline='') as myfile:\n wr = csv.writer(myfile,delimiter=',', quoting=csv.QUOTE_ALL)\n for itm in testList:\n wr.writerow([itm[0],itm[1]])\n\n\n# In[ ]:\n\n\n\n","sub_path":"Analysis/Analysis3/Analysis_3.py","file_name":"Analysis_3.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"4723191","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport functions\nimport time\n\n\ndriver = webdriver.Chrome('./chromedriver')\naction = webdriver.common.action_chains.ActionChains(driver)\n\nf =functions.function(driver)\n\n#statistic\nkakao_id = 'xygene01@nate.com'\nkakao_pw = 'js**91^^11'\nnaver_id = 'jijohn01'\nnaver_pw = 'js**91^^1119'\nauthor_name = '김인겸_인큐브랜드'\nfoem_per_day = 144\nfoem_cnt = 0\n#variable\ncontents_cnt = 0\nscroll_y = 350\nfoems = []\n\n\n#네이버 로그인 접근 후 아이디 비번은 수동으로 입력하여 로그인 해야함\nf.naver_go2_login()\nwait = WebDriverWait(driver,20)\nblog = wait.until(EC.element_to_be_clickable((By.XPATH,\"//*[@id='PM_ID_ct']/div[1]/div[2]/div[1]/ul[1]/li[3]/a\")))\nblog.click()\nf.naver_go2_blog_write()\n\ndriver.switch_to.frame(\"mainFrame\")\nif driver.find_element_by_xpath(\"//*[@id='blog-editor']/div/div/div/div[1]/article/div/header/button\").is_displayed():\n driver.find_element_by_xpath(\"//*[@id='blog-editor']/div/div/div/div[1]/article/div/header/button\").click()\ndriver.switch_to.default_content()\n\ndriver.execute_script(\"window.open('');\")\nf.kakao_tap_change()\nf.kakao_go2_login(kakao_id,kakao_pw)\n\ndriver.implicitly_wait(3)\ndriver.find_element_by_xpath(\"//span[text()='\"+author_name+\"'][1]\").click()\ndriver.implicitly_wait(10)\nfor five_contents_idx in range (1,1000):\n if foem_cnt >= foem_per_day:\n break\n cnt = driver.find_elements_by_xpath(\"//*[@id='myStoryContentWrap']/div[2]/div/div/div[1]/div[\"+str(five_contents_idx)+\"]/div/div/div\")\n for contents_cnt in range(1,len(cnt)+1):\n\n # 스크롤\n scroll_y = driver.find_element_by_xpath(\"//*[@id='myStoryContentWrap']/div[2]/div/div/div[1]/div[\" + str(five_contents_idx) + \"]/div/div/div[\" + str(contents_cnt) + \"]\").location\n driver.execute_script(\"window.scrollTo(0,\" + str(scroll_y['y']-100) + \")\")\n\n driver.implicitly_wait(10)\n if 't:remove'==driver.find_element_by_xpath(\"//*[@id='myStoryContentWrap']/div[2]/div/div/div[1]/div[\"+str(five_contents_idx)+\"]/div/div/div[\"+str(contents_cnt)+\"]/div[1]/div[3]/div[@class='btn_top_group']/div/div/a\").get_attribute('data-kant-option'):\n continue\n time.sleep(0.5)\n\n f.click_more(five_contents_idx,contents_cnt)\n #text 가져오기\n foem = driver.find_element_by_xpath(\"//*[@id='myStoryContentWrap']/div[2]/div/div/div[1]/div[\"+str(five_contents_idx)+\"]/div/div/div[\"+str(contents_cnt)+\"]/div[1]/div[4]/div[1]/div\").text\n\n #시 인지 판별 아니면 다음글로\n if not f.is_foem(foem):\n continue\n f.naver_tap_change()\n f.naver_go2_blog_write()\n foem_cnt +=1\n\n f.naver_blog_write(foem)\n f.kakao_tap_change()\n print('#####################\\n묶음 {} 번째, {}번째글\\n'.format(five_contents_idx,contents_cnt))\n print(foem+'\\n Count:{}'.format(foem_cnt))\n driver.find_element_by_xpath(\"//*[@id='myStoryContentWrap']/div[2]/div/div/div[1]/div[\"+str(five_contents_idx)+\"]/div/div/div[\"+str(contents_cnt)+\"]/div[1]/div[3]/div[@class='btn_top_group']/div/div\").click()\n if foem_cnt >= foem_per_day:\n break\n\ndriver.close()","sub_path":"kakao2nav.py","file_name":"kakao2nav.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"77140879","text":"import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\ndx = [-1, 0, 1, 0]\ndy = [0, -1, 0, 1]\n\nN = int(input())\nboard = []\nshark = []\nshark_weight = 2\nfor i in range(N):\n tmp = list(map(int, input().split()))\n for j in range(N):\n if tmp[j] == 9:\n shark = [i,j]\n board.append(tmp)\nboard[shark[0]][shark[1]] = 0\n\ndef in_bound(x, y):\n if x in range(N) and y in range(N):\n return True\n return False\n\ndef find(shark, d):\n visited = [[float('INF') for _ in range(N)] for _ in range(N)]\n queue = deque([[shark[0], shark[1]]])\n visited[shark[0]][shark[1]] = 0\n min_count, n_x, n_y = float('INF'), 0, 0\n \n while queue:\n x, y = queue.popleft()\n for i in range(4):\n nx, ny = x+dx[i], y+dy[i]\n if in_bound(nx, ny) and visited[x][y]+1 < visited[nx][ny]:\n if board[nx][ny] != 0 and board[nx][ny] < shark_weight:\n # 작으면 이 물고기 먹기 -> 제일 위쪽 왼쪽에 있는거\n if visited[x][y]+1 < min_count:\n min_count = visited[x][y]+1\n n_x, n_y = nx, ny\n visited[nx][ny] = visited[x][y]+1\n elif visited[x][y]+1 == min_count:\n if n_x > nx:\n n_x, n_y = nx, ny\n visited[nx][ny] = visited[x][y]+1\n elif n_x == nx and n_y > ny:\n n_x, n_y = nx, ny\n visited[nx][ny] = visited[x][y]+1\n elif board[nx][ny] == 0 or board[nx][ny] == shark_weight:\n if visited[x][y]+1 > min_count:\n break\n else:\n # 이동가능하면 이동\n visited[nx][ny] = visited[x][y] + 1\n queue.append([nx,ny])\n\n if min_count != float('inf'):\n return min_count, n_x, n_y \n else:\n return -1, -1, -1\n\ntime = 0\neat = 0\nwhile True:\n # 상어 이동하기\n count, x, y = find(shark, i)\n\n if count == -1:\n # 더 먹을 물고기 x\n break\n \n board[x][y] = 0\n shark = [x, y]\n eat += 1\n if eat == shark_weight:\n shark_weight += 1\n eat = 0\n time += count\n\nprint(time)","sub_path":"삼성 SW 역량 테스트 기출 문제/16236_아기상어.py","file_name":"16236_아기상어.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"253729958","text":"\nimport glob\nimport os\n\n#fastq_folder = \"/home/hakan/scratch/dba/DBA\" \nfastq_folder = \"/work/06059/ozadamh/lonestar/projects/DBA/fastq/merged\"\noutput_folder = \"/scratch/06059/ozadamh/dba/run_july_4\" \n\n\n## Not used for reference purposes we keep it here\nslurm_options_example = \\\n\"\"\"\n#SBATCH -J Job%j # Job name\n#SBATCH -o /PATH_to_be_determined/out.o%j # Name of stdout output file\n#SBATCH -e /PATH_to_be_determined/err.e%j # Name of stderr error file\n#SBATCH -p normal # Queue (partition) name\n#SBATCH -N 1 # Total # of nodes (must be 1 for serial)\n#SBATCH -n 16 # Total # of mpi tasks (should be 1 for serial)\n#SBATCH -t 12:30:00 # Run time (hh:mm:ss)\n#SBATCH -A Ceniklab-CPRIT\n\"\"\"\n\nslurm_footer = \\\n\"\"\"#SBATCH -p normal # Queue (partition) name\n#SBATCH -N 1 # Total # of nodes (must be 1 for serial)\n#SBATCH -n 16 # Total # of mpi tasks (should be 1 for serial)\n#SBATCH -t 12:30:00 # Run time (hh:mm:ss)\n#SBATCH -A Ceniklab-CPRIT\n\"\"\"\n\n\ndef generate_slurm_commands(exp_name, output_folder):\n slurm_str = \"#!/bin/bash\\n\"\n slurm_str += \"#SBATCH -J {}\".format(exp_name)\n outdir_line = \"#SBATCH -o {}/slurm_out/{}.out%j\".format(output_folder, exp_name)\n errdir_line = \"#SBATCH -e {}/slurm_err/{}.err%j\".format(output_folder, exp_name)\n\n return \"\\n\".join( (slurm_str, outdir_line,\n errdir_line, slurm_footer) )\n\n\n\nbase_script = \\\n\"\"\"\noutput1=$(basename $input1| awk -F \"_\" '{print($1\"_\"$2)}')\noutput2=$(basename $input2| awk -F \"_\" '{print($1\"_\"$2)}')\n\n\nOUTFOLDER=${SCRATCH}/dba/run_july_4/pipeline\n\nHISAT2INDEX=\"/work/06059/ozadamh/lonestar/reference/human/HISAT2/grch38_snp_tran/genome_snp_tran\"\nCHESSGTF=\"/work/06059/ozadamh/lonestar/projects/DBA/reference/chessmod.gtf\"\nNP=16\n\nsource activate dba\n###############################################################################\n\nmkdir -p $OUTFOLDER/fastqc/${output1}\nmkdir -p $OUTFOLDER/clippedreads/${output1}\nmkdir -p $OUTFOLDER/alignment/${output1}\nmkdir -p $OUTFOLDER/sorted/${output1}\n#echo $output1\n#echo $output2\n\n### C U T A D A P T #########################\n\ncutadapt -a GATCGGAAGAGCACACGTCTGAACTCCAGTCACNNNNNNATCTCGTATGCCGTCTTCTGCTTG \\\n -A GATCGGAAGAGCACACGTCTGAACTCCAGTCACNNNNNNATCTCGTATGCCGTCTTCTGCTTG \\\n -A CAGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTC \\\n -u 6 -U 6 -q 22 -m 22 \\\n -o $OUTFOLDER/clippedreads/${output1}/clipped_${output1}_R1.fastq.gz \\\n -p $OUTFOLDER/clippedreads/${output1}/clipped_${output2}_R2.fastq.gz \\\n --cores ${NP} \\\n $input1 $input2\n\n#############################################\n\n###### F A S T Q C ########################\nfastqc -o $OUTFOLDER/fastqc/${output1}/ \\\n $OUTFOLDER/clippedreads/${output1}/clipped_${output1}_R1.fastq.gz\n\nfastqc -o $OUTFOLDER/fastqc/${output2}/ \\\n $OUTFOLDER/clippedreads/${output1}/clipped_${output2}_R2.fastq.gz\n###########################################\n\n#### H I S A T 2 ##########################\nhisat2 -p ${NP} -x ${HISAT2INDEX} \\\n -1 $OUTFOLDER/clippedreads/${output1}/clipped_${output1}_R1.fastq.gz \\\n -2 $OUTFOLDER/clippedreads/${output1}/clipped_${output2}_R2.fastq.gz \\\n -S $OUTFOLDER/alignment/${output1}/${output1}_align.sam \\\n --un-conc-gz $OUTFOLDER/alignment/${output1}/${output1}_unaligned.gz\n\n#### S A M T O O L S #####################\n\nsamtools view -@ ${NP} -bS $OUTFOLDER/alignment/${output1}/${output1}_align.sam \\\n | samtools sort -@ ${NP} -o $OUTFOLDER/sorted/${output1}/${output1}_sorted.bam\n\nsamtools index -@ ${NP} -b $OUTFOLDER/sorted/${output1}/${output1}_sorted.bam\n\n#### S T R I N G T I E #####################\nstringtie -M 0.75 -e -p ${NP} -G ${CHESSGTF} \\\n -b $OUTFOLDER/ballgown/${output1}/ \\\n -A $OUTFOLDER/ballgown/${output1}/gene_abundance.tab \\\n $OUTFOLDER/sorted/${output1}/${output1}_sorted.bam \\\n -o $OUTFOLDER/misc/${output1}/n.gtf\n\"\"\"\n\n\ndef get_experiment_folders():\n lev_1_list = os.listdir( fastq_folder ) \n\n exp_folders = []\n \n for seq_lane in lev_1_list:\n sub_folder = os.path.join( fastq_folder, seq_lane ) \n seq_lane_experiments = os.listdir( sub_folder )\n\n for experiment in seq_lane_experiments:\n \t exp_folder = os.path.join(sub_folder, experiment)\n \t exp_folders.append(exp_folder)\n\n return exp_folders\n\n\ndef generate_script(paired_files):\n if len(paired_files) < 2:\n return 0\n\n exp_name = paired_files[0].split(\"/\")[-2]\n \n with open(exp_name + \".sh\", \"w\") as output_stream:\n\n slurm_str = generate_slurm_commands(exp_name, output_folder)\n print(slurm_str, file = output_stream)\n\n print( \"input1=\" + paired_files[0], \n file = output_stream )\n print( \"input2=\" + paired_files[1] + \"\\n\\n\\n\", \n file = output_stream)\n\n print(base_script, file = output_stream)\n\n\n\ndef main():\n exp_folders = get_experiment_folders()\n print(exp_folders)\n\n for e in exp_folders:\n r1_contents = glob.glob( e + \"/*_R1*gz\" )\n r2_contents = glob.glob( e + \"/*_R2*gz\" )\n e_contents = r1_contents + r2_contents\n generate_script(e_contents)\n \n \nif __name__ == '__main__':\n main()\n\n","sub_path":"run_july_4_2019/scripts/generate_dba_scripts.py","file_name":"generate_dba_scripts.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"140773442","text":"\ndef swappingoftwonumbers(list,fromindex,toindex):\n temp = list[fromindex]\n list[fromindex] = list[toindex]\n list[toindex] = temp\n\ndef isswappingrequired(fromelement,toelement):\n return fromelement > toelement\n\ndef bubblesort(listofelements):\n for i in range(0, len(listofelements) , 1):\n position = 0\n for j in range(1,len(listofelements)):\n if isswappingrequired(listofelements[position],listofelements[j]):\n swappingoftwonumbers(listofelements,position,j)\n position=j\n printingofelements(listofelements) \n return listofelements \n\ndef printingofelements(listofelements):\n for element in listofelements:\n print(element)\n\nif __name__ == \"__main__\":\n elements = [ 5, 1, 4, 2, 8 ]\n listofelements = bubblesort(elements) \n printingofelements(listofelements) \n","sub_path":"sorting/src/main/java/com/sorting/bubblesort/BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"345119511","text":"import importlib\nimport os\nfrom typing import List\n\nimport pandas as pd\nimport pytest\n\nimport ibis\nimport ibis.common.exceptions as com\nimport ibis.util as util\n\ntry:\n import importlib.metadata as importlib_metadata\nexcept ImportError:\n import importlib_metadata\n\nfrom .base import BackendTest\n\n\ndef _random_identifier(suffix):\n return f'__ibis_test_{suffix}_{util.guid()}'\n\n\ndef _get_all_backends() -> List[str]:\n \"\"\"\n Return the list of known backend names.\n \"\"\"\n return [\n entry_point.name\n for entry_point in importlib_metadata.entry_points()[\"ibis.backends\"]\n ]\n\n\ndef _backend_name_to_class(backend_str: str):\n \"\"\"\n Convert a backend string to the test configuration class for the backend.\n \"\"\"\n try:\n backend_package = getattr(ibis, backend_str).__module__\n except AttributeError:\n raise ValueError(\n f'Unknown backend {backend_str}. '\n f'Known backends: {_get_all_backends()}'\n )\n\n conftest = importlib.import_module(f'{backend_package}.tests.conftest')\n return conftest.TestConf\n\n\ndef _get_backends_to_test():\n \"\"\"\n Get a list of `TestConf` classes of the backends to test.\n\n The list of backends can be specified by the user with the\n `PYTEST_BACKENDS` environment variable.\n\n - If the variable is undefined or empty, then no backends are returned\n - Otherwise the variable must contain a space-separated list of backends to\n test\n\n \"\"\"\n backends_raw = os.environ.get('PYTEST_BACKENDS')\n\n if not backends_raw:\n return []\n\n backends = backends_raw.split()\n\n return [\n pytest.param(\n _backend_name_to_class(backend),\n marks=[getattr(pytest.mark, backend), pytest.mark.backend],\n id=backend,\n )\n for backend in sorted(backends)\n ]\n\n\ndef pytest_runtest_call(item):\n \"\"\"Dynamically add various custom markers.\"\"\"\n nodeid = item.nodeid\n backend = item.funcargs[\"backend\"]\n assert isinstance(backend, BackendTest), \"backend has type {!r}\".format(\n type(backend).__name__\n )\n\n for marker in item.iter_markers(name=\"only_on_backends\"):\n if backend.name() not in marker.args[0]:\n pytest.skip(\n f\"only_on_backends: {backend} is not in {marker.args[0]} \"\n f\"{nodeid}\"\n )\n\n for marker in item.iter_markers(name=\"skip_backends\"):\n (backend_types,) = map(tuple, marker.args)\n if backend.name() in marker.args[0]:\n pytest.skip(f\"skip_backends: {backend} {nodeid}\")\n\n for marker in item.iter_markers(name=\"skip_missing_feature\"):\n features = marker.args[0]\n missing_features = [\n feature for feature in features if not getattr(backend, feature)\n ]\n if missing_features:\n pytest.skip(\n f'Backend {backend} is missing features {missing_features} '\n f'needed to run {nodeid}'\n )\n\n for marker in item.iter_markers(name=\"xfail_backends\"):\n if backend.name() in marker.args[0]:\n item.add_marker(\n pytest.mark.xfail(\n reason=f'{backend} in xfail list: {marker.args[0]}',\n **marker.kwargs,\n )\n )\n\n for marker in item.iter_markers(name=\"xpass_backends\"):\n if backend.name() not in marker.args[0]:\n item.add_marker(\n pytest.mark.xfail(\n reason=f'{backend} not in xpass list: {marker.args[0]}',\n **marker.kwargs,\n )\n )\n\n for marker in item.iter_markers(name='min_spark_version'):\n min_version = marker.args[0]\n if backend.name() in ['spark', 'pyspark']:\n from distutils.version import LooseVersion\n\n import pyspark\n\n if LooseVersion(pyspark.__version__) < LooseVersion(min_version):\n item.add_marker(\n pytest.mark.xfail(\n reason=f'Require minimal spark version {min_version}, '\n f'but is {pyspark.__version__}',\n **marker.kwargs,\n )\n )\n\n\n@pytest.hookimpl(hookwrapper=True)\ndef pytest_pyfunc_call(pyfuncitem):\n \"\"\"Dynamically add an xfail marker for specific backends.\"\"\"\n outcome = yield\n try:\n outcome.get_result()\n except (\n com.OperationNotDefinedError,\n com.UnsupportedOperationError,\n com.UnsupportedBackendType,\n NotImplementedError,\n ) as e:\n markers = list(pyfuncitem.iter_markers(name=\"xfail_unsupported\"))\n backend = pyfuncitem.funcargs[\"backend\"]\n backend_type = type(backend).__name__\n\n if len(markers) == 0:\n # nothing has marked the failure as an expected one\n raise e\n elif len(markers) == 1:\n if not isinstance(backend, BackendTest):\n pytest.fail(f\"Backend has type {backend_type!r}\")\n pytest.xfail(reason=f\"{backend_type!r}: {e}\")\n else:\n pytest.fail(\n f\"More than one xfail_unsupported marker found on test \"\n f\"{pyfuncitem}\"\n )\n\n\npytestmark = pytest.mark.backend\n\n\n@pytest.fixture(params=_get_backends_to_test(), scope='session')\ndef backend(request, data_directory):\n \"\"\"\n Instance of BackendTest.\n \"\"\"\n # See #3021\n # TODO Remove this to backend_test, since now that a `Backend` class exists\n return request.param(data_directory)\n\n\n@pytest.fixture(scope='session')\ndef con(backend):\n \"\"\"\n Instance of Client, already connected to the db (if applies).\n \"\"\"\n # See #3021\n # TODO Rename this to `backend` when the existing `backend` is renamed to\n # `backend_test`, and when `connect` returns `Backend` and not `Client`\n return backend.connection\n\n\n@pytest.fixture(scope='session')\ndef alltypes(backend):\n return backend.functional_alltypes\n\n\n@pytest.fixture(scope='session')\ndef sorted_alltypes(backend, alltypes):\n return alltypes.sort_by('id')\n\n\n@pytest.fixture(scope='session')\ndef batting(backend):\n return backend.batting\n\n\n@pytest.fixture(scope='session')\ndef awards_players(backend):\n return backend.awards_players\n\n\n@pytest.fixture(scope='session')\ndef geo(backend):\n if backend.geo is None:\n pytest.skip(f'Geo Spatial type not supported for {backend}.')\n return backend.geo\n\n\n@pytest.fixture\ndef analytic_alltypes(alltypes):\n return alltypes\n\n\n@pytest.fixture(scope='session')\ndef df(alltypes):\n return alltypes.execute()\n\n\n@pytest.fixture(scope='session')\ndef sorted_df(backend, df):\n return df.sort_values('id').reset_index(drop=True)\n\n\n@pytest.fixture(scope='session')\ndef batting_df(batting):\n return batting.execute(limit=None)\n\n\n@pytest.fixture(scope='session')\ndef awards_players_df(awards_players):\n return awards_players.execute(limit=None)\n\n\n@pytest.fixture(scope='session')\ndef geo_df(geo):\n # Currently geo is implemented just for OmniSciDB\n if geo is not None:\n return geo.execute(limit=None)\n return None\n\n\n@pytest.fixture\ndef temp_table(con) -> str:\n \"\"\"\n Return a temporary table name.\n\n Parameters\n ----------\n con : ibis.backends.base.Client\n\n Yields\n ------\n name : string\n Random table name for a temporary usage.\n \"\"\"\n name = _random_identifier('table')\n try:\n yield name\n finally:\n try:\n con.drop_table(name, force=True)\n except NotImplementedError:\n pass\n\n\n@pytest.fixture\ndef temp_view(con) -> str:\n \"\"\"Return a temporary view name.\n\n Parameters\n ----------\n con : ibis.omniscidb.OmniSciDBClient\n\n Yields\n ------\n name : string\n Random view name for a temporary usage.\n \"\"\"\n name = _random_identifier('view')\n try:\n yield name\n finally:\n try:\n con.drop_view(name, force=True)\n except NotImplementedError:\n pass\n\n\n@pytest.fixture(scope='session')\ndef current_data_db(con, backend) -> str:\n \"\"\"Return current database name.\"\"\"\n try:\n return con.current_database\n except NotImplementedError:\n pytest.skip(\n f\"{backend.name()} backend doesn't have current_database method.\"\n )\n\n\n@pytest.fixture\ndef alternate_current_database(con, backend, current_data_db: str) -> str:\n \"\"\"Create a temporary database and yield its name.\n Drops the created database upon completion.\n\n Parameters\n ----------\n con : ibis.backends.base.Client\n current_data_db : str\n Yields\n -------\n str\n \"\"\"\n name = _random_identifier('database')\n try:\n con.create_database(name)\n except NotImplementedError:\n pytest.skip(\n f'{backend.name()} backend doesn\\'t have create_database method.'\n )\n try:\n yield name\n finally:\n con.set_database(current_data_db)\n con.drop_database(name, force=True)\n\n\n@pytest.fixture\ndef test_employee_schema() -> ibis.schema:\n sch = ibis.schema(\n [\n ('first_name', 'string'),\n ('last_name', 'string'),\n ('department_name', 'string'),\n ('salary', 'float64'),\n ]\n )\n\n return sch\n\n\n@pytest.fixture\ndef test_employee_data_1():\n df = pd.DataFrame(\n {\n 'first_name': ['A', 'B', 'C'],\n 'last_name': ['D', 'E', 'F'],\n 'department_name': ['AA', 'BB', 'CC'],\n 'salary': [100.0, 200.0, 300.0],\n }\n )\n\n return df\n\n\n@pytest.fixture\ndef test_employee_data_2():\n df2 = pd.DataFrame(\n {\n 'first_name': ['X', 'Y', 'Z'],\n 'last_name': ['A', 'B', 'C'],\n 'department_name': ['XX', 'YY', 'ZZ'],\n 'salary': [400.0, 500.0, 600.0],\n }\n )\n\n return df2\n","sub_path":"ibis/backends/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":9855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"539117914","text":"import RPi.GPIO as GPIO\nimport time\nfrom picamera import PiCamera\n\ndef take_photo(camera):\n file_name = \"/home/pi/Camera/img_\" + str(time.time()) + \".jpg\"\n camera.capture(file_name)\n return file_name\n\nPIR_PIN = 4\nBLUE_LED_PIN = 27\n\n#Setup camera\ncamera = PiCamera()\ncamera.resolution = (720, 480)\ncamera.rotation = 90\nprint(\"Waiting two seconds to initialise the camera...\")\ntime.sleep(2)\nprint(\"Camera setup OK\")\n\n#Setup GPIO\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(PIR_PIN, GPIO.IN)\nGPIO.setup(BLUE_LED_PIN, GPIO.OUT)\nGPIO.output(BLUE_LED_PIN, GPIO.LOW)\n\nMOV_DETECT_THRESHOLD = 3.0\nMIN_DURATION_BETWEEN_PHOTOS = 30.0\nlast_pir_state = GPIO.input(PIR_PIN)\nmovement_timer = time.time()\nlast_time_photo_taken = 0\n\ntry:\n while True:\n time.sleep(0.01)\n pir_state = GPIO.input(PIR_PIN)\n if pir_state == GPIO.HIGH:\n GPIO.output(BLUE_LED_PIN, GPIO.HIGH)\n else:\n GPIO.output(BLUE_LED_PIN, GPIO.LOW)\n if last_pir_state == GPIO.LOW and pir_state == GPIO.HIGH:\n movement_timer = time.time()\n if last_pir_state == GPIO.HIGH and pir_state == GPIO.HIGH:\n if time.time() - movement_timer > MOV_DETECT_THRESHOLD:\n if time.time() - last_time_photo_taken > MIN_DURATION_BETWEEN_PHOTOS:\n print(\"Take photo and send by email\")\n take_photo(camera)\n last_time_photo_taken = time.time()\n last_pir_state = pir_state\n \nexcept KeyboardInterrupt:\n GPIO.cleanup()","sub_path":"project_step2.py","file_name":"project_step2.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"413466072","text":"import pygame\nimport random\n\nfrom hexical import hexmap, layout\n\n\ndef initpygame():\n \"\"\"Initialises the pygame environment and returns a gameDisplay and\n display_info object.\n\n \"\"\"\n pygame.init()\n pygame.font.init()\n gameDisplay = pygame.display.set_mode((0,0), pygame.FULLSCREEN)\n display_info = pygame.display.Info()\n pygame.display.set_caption('Graphical Hex Test')\n\n return (gameDisplay, display_info)\n\n\ndef drawmap(hexgrid, lay, gameDisplay, display_info):\n\n width = display_info.current_w\n height = display_info.current_h\n\n for akey in hexgrid:\n for bkey in hexgrid[akey]:\n h = hexgrid[akey][bkey]\n corners = h.corners(lay)\n pygame.draw.aalines(gameDisplay,\n (255,255,255),\n True,\n corners)\n\ndef main():\n\n gameDisplay, display_info = initpygame()\n\n WIDTH = display_info.current_w\n HEIGHT = display_info.current_h\n\n draw = False\n quitting = False\n while not quitting:\n\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n quitting = True\n\n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_ESCAPE:\n quitting = True\n\n if event.key == pygame.K_SPACE:\n draw = True\n\n if event.type == pygame.KEYUP:\n\n if event.key == pygame.K_SPACE:\n draw = False\n\n if draw:\n gameDisplay.fill((0,0,0))\n\n drawmap(hexmap.hexagon(3),\n layout.Layout((random.randint(30,35),random.randint(30,35)),\n (300,300),\n random.choice(['p','f'])),\n gameDisplay, display_info)\n\n drawmap(hexmap.parallelogram(-3,3, -3,3, random.choice([1,2,3])),\n layout.Layout((random.randint(30,35),random.randint(30,35)),\n (1000,300),\n random.choice(['p','f'])),\n gameDisplay, display_info)\n\n drawmap(hexmap.triangle(4, random.choice([1,2])),\n layout.Layout((random.randint(15,20),random.randint(15,20)),\n (1600,200),\n random.choice(['p','f'])),\n gameDisplay, display_info)\n\n\n pygame.display.update()\n\n\n\nif __name__ == '__main__':\n main()\n pygame.quit()\n quit()\n","sub_path":"graphicaltests/mapgenerator.py","file_name":"mapgenerator.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"433017047","text":"\"\"\"SOURCE PANEL METHOD\nLogan Halstrom\nEAE 127\n22 OCTOBER 2014\n\nDESCRIPTION: Represent symmetric geometry as distribution of source panels\n\"\"\"\nimport sys\nsys.path.append('/Users/Logan/lib/python')\nfrom lplot import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\nimport os\n\nimport makeSymGeom\n\nclass Panel:\n def __init__(self, xa, ya, xb, yb):\n \"\"\"Initialize panel\n (xa, ya) --> first end-point of panel\n (xb, yb) --> second end-point of panel\n \"\"\"\n self.xa, self.ya = xa, ya\n self.xb, self.yb = xb, yb\n # control-point (center-point)\n self.xc, self.yc = (xa + xb) / 2, ( ya + yb ) / 2\n # length of the panel\n self.length = ((xb - xa)**2 + (yb - ya)**2) ** 0.5\n\n #INITIALIZE\n # source strength distribution\n self.strength = 0.\n # tangential velocity at panel surface\n self.vt = 0.\n # pressure coefficient at panel surface\n self.Cp = 0.\n\n # orientation of the panel (angle between x-axis and panel's normal)\n if xb-xa <= 0.:\n self.beta = np.arccos((yb-ya)/self.length)\n elif xb-xa > 0.:\n self.beta = 2*np.pi - np.arccos((yb-ya)/self.length)\n # self.beta = np.arccos((yb-ya)/self.length)\n\ndef MakePanels(xgeom, ygeom, n_panel, method='constant'):\n \"\"\"Discretize geometry into panels using various methods.\n Return array of panels.\n n_panel --> number of panels\n method --> panel discretization method:\n 'circle' --> map circle points to airfoil,\n 'given' --> use given distribution\n 'constant' --> use constant panel spacing (in x)\n 'constantairfoil'\n \"\"\"\n def ConstantSpacing(xgeom, ygeom, n_panel):\n \"\"\"Creates panels for arbitrary geometry\n x, y --> geometry coordinates\n n_panel --> number of panels to distretize into\n \"\"\"\n xends, yends = makeSymGeom.main(xgeom, ygeom, n_panel+1)\n return xends, yends\n\n\n def ConstantSpacingAirfoil(xgeom, ygeom, n_panel):\n \"\"\"Creates airfoil panel points with even x-spacing.\n Requires odd number of panels.\n x, y --> geometry coordinates\n n_panel --> number of panels to distretize into\n \"\"\"\n\n def GeomSplit(x,y):\n \"\"\"Given mses type data, find location of leading edge and split x,y coordintes\n into two sets (upper and lower)\"\"\"\n #Get index of leading edge on upper surface\n i = 0\n while i < len(x):\n if (np.arctan2(y[i], x[i]) >= 0) and (np.arctan2(y[i+1], x[i+1]) < 0):\n iLE = i\n break\n i += 1\n #Split upper and lower surfaces for interpolation\n xup, yup= x[iLE::-1], y[iLE::-1]\n xlo, ylo= x[iLE+1:], y[iLE+1:]\n\n return xup, yup, xlo, ylo\n\n def GeomMerge(xup, yup, xlo, ylo):\n \"\"\"merge upper and lower surface geometry sets into one set of x,y (XFOIL format)\"\"\"\n n1 = len(xup)\n n = n1 + len(xlo)\n x, y = np.zeros(n), np.zeros(n)\n #reverse direction of upper surface coordinates\n x[:n1], y[:n1] = xup[-1::-1], yup[-1::-1]\n #append lower surface coordinates as they are\n x[n1:], y[n1:] = xlo, ylo\n return x, y\n\n if n_panel%2 == 0:\n print('WARNING: Constant spacing method requires odd number of \\\n panels')\n c = xgeom.min()+xgeom.max()\n #TE panel lengths are proportinal to lenth of other panels by frac\n frac = 0.25\n #get TE panel lengths\n TE_length = frac * c / ((n_panel+1)/2-1-1 + frac)\n xnew = np.append( np.linspace( xgeom.min()+0.001*c,\n xgeom.max()-TE_length, (n_panel+1)/2-1 ),\n xgeom.max() )\n xoldup, yoldup, xoldlo, yoldlo = GeomSplit(xgeom, ygeom)\n #linear interpolate new y points\n ynewup = np.interp(xnew, xoldup, yoldup)\n ynewlo = np.interp(xnew, xoldlo, yoldlo)\n #Merge new coordinates into one set\n yends = GeomMerge(xnew, ynewup, xnew, ynewlo)[1]\n xends = np.empty_like(yends)\n xends[0:len(xnew)] = xnew[-1::-1]\n xends[len(xnew):] = xnew[:]\n # yends[n_panel] = yends[0]\n return xends, yends\n\n\n def CircleMethod(xgeom, ygeom, n_panel):\n \"\"\"Create x-spacing based on a circle, then map y-points onto body\n geometry using linear interpolation. Some panel spacings cause\n interpolation to break, so check the resulting geometry for each panel#\n x, y --> geometry coordinates\n n_panel --> number of panels to distretize into\n \"\"\"\n\n #Make circle with diameter equal to chord of airfoil\n R = (xgeom.max() - xgeom.min()) / 2\n center = (xgeom.max() + xgeom.min()) / 2\n #x-coordinates of circle (also new x-coordinates of airfoil)\n #(n+1 because first and last points are the same)\n xends = center + R*np.cos(np.linspace(0, 2*np.pi, n_panel+1))\n #for each new x, find pair of original geometry points surrounding\n #it and linear interpolate to get new y\n #append first point of original geometry to end so that i+1 at\n #last point works out\n xgeom, ygeom = np.append(xgeom, xgeom[0]), np.append(ygeom, ygeom[0])\n\n #Get index of split in circle x\n i = 0\n while i < len(xends):\n if (xends[i] - xends[i-1] < 0) and (xends[i+1] - xends[i] > 0):\n isplit = i\n break\n i += 1\n #Split upper and lower surfaces for interpolation\n xnewup = xends[isplit::-1]\n xnewlo = xends[isplit+1:]\n xoldup, yoldup, xoldlo, yoldlo = GeomSplit(xgeom, ygeom)\n #linear interpolate new y points\n ynewup = np.interp(xnewup, xoldup, yoldup)\n ynewlo = np.interp(xnewlo, xoldlo, yoldlo)\n #Merge new coordinates into one set\n yends = GeomMerge(xnewup, ynewup, xnewlo, ynewlo)[1]\n # yends[n_panel] = yends[0]\n\n #***************************might need to make trailing edge one point*\n return xends, yends\n\n if method == 'constant':\n #Constant spacing method Method\n xends, yends = ConstantSpacing(xgeom, ygeom, n_panel)\n elif method == 'constantairfoil':\n #Constant spacing method Method\n xends, yends = ConstantSpacingAirfoil(xgeom, ygeom, n_panel)\n elif method == 'circle':\n #Circle Method\n xends, yends = CircleMethod(xgeom, ygeom, n_panel)\n elif method == 'given':\n #use points as given\n xends, yends = xgeom, ygeom\n n_panel = len(xends) - 1\n\n print('Upper/Lower y-coordinate at TE: (', xends[0], ',', yends[0],\n ') ; (', xends[0], ',', yends[-1], ')')\n\n print(len(xends))\n\n #assign panels\n panels = np.zeros(n_panel, dtype=object)\n for i in range(0, n_panel):\n panels[i] = Panel(xends[i], yends[i], xends[i+1], yends[i+1])\n\n return panels\n\ndef PlotPanels(xgeom, ygeom, panels, name, show_plot):\n #dont plot if show_plot=0\n if show_plot==0:\n return\n\n print('set bounds')\n\n # edgespace = 0.1 * (xgeom.max()-xgeom.min())\n # xmin, xmax = xgeom.min()-edgespace, xgeom.max()+edgespace\n # ymin, ymax = ygeom.min()-edgespace, ygeom.max()+edgespace\n # factor = 12\n # size = (factor*(xmax-xmin), factor*(ymax-ymin))\n # plt.figure(figsize = size)\n # plt.axis([xmin, xmax, ymin, ymax])\n\n plt.figure()\n\n plt.title(str(len(panels)) + ' Panel Discretization of ' + name,\n fontsize=txt_ttl)\n plt.xlabel(r'$\\frac{x}{c}$', fontsize=txt_lbl)\n plt.ylabel(r'$\\frac{y}{c}$', fontsize=txt_lbl)\n # plt.grid(True)\n\n print('plot geom')\n\n plt.plot(xgeom, ygeom, '--b', label = 'Original Geometry', linewidth=2)\n\n print('plot panel')\n\n plt.plot(np.append([p.xa for p in panels], panels[-1].xb),\n np.append([p.ya for p in panels], panels[-1].yb),\n 'g', label = 'Panel', linewidth=2)\n\n print('plot panel ends')\n\n plt.plot([p.xa for p in panels], [p.ya for p in panels],\n 'go', label = 'End Points', linewidth=1, markersize = mkr)\n\n print('plot panel centers')\n\n plt.plot([p.xc for p in panels], [p.yc for p in panels],\n 'k^', label = 'Center Points', linewidth=1, markersize = mkr)\n plt.legend(loc='best')\n plt.axis('equal')\n L = max(xgeom) - min(xgeom)\n plt.xlim([min(xgeom)-L*0.1, max(xgeom)+L*0.1])\n SavePlot( 'results/{}_Panels.png'.format(name) )\n # plt.show()\n\ndef PanelIntegral(pi, pj, dir):\n \"\"\"Evaluate contribution of panel at center of another panel, in normal\n direction.Insure flow is tangent to surface at control point of each panel.\n\n pi --> panel on which contribution is calculated\n pj --> panel from which contribution is calculated\n direction of component -->\n 'normal' --> normal to given panel,\n 'tangent' --> tangent to given panel,\n 'x','y' --> x and y directions (for velocity field)\n \"\"\"\n if dir=='normal':\n #derivatives with respect to: normal direction\n dxd_, dyd_ = np.cos(pi.beta), np.sin(pi.beta)\n elif dir=='tangent':\n #derivatives with respect to: tangential direction\n dxd_, dyd_ = -np.sin(pi.beta), np.cos(pi.beta)\n\n #function to integrate\n def func(s):\n #x-coord of s-vector along panel\n xjsj = pj.xa - np.sin(pj.beta)*s\n #y-coord of s-vector along panel\n yjsj = pj.ya + np.cos(pj.beta)*s\n return (1./(2.*np.pi) * ((pi.xc - xjsj)*dxd_ + (pi.yc - yjsj)*dyd_)\n / ((pi.xc - xjsj) ** 2 + (pi.yc - yjsj) ** 2))\n\n #Integrate along length of panel\n return integrate.quad(lambda s:func(s), 0., pj.length)[0]\n\n\ndef PointIntegral(x, y, p, dir):\n \"\"\"Evaluates the contribution of a panel at one point.\n p --> panel\n dir --> direction component\n \"\"\"\n if dir=='x':\n dxd_, dyd_ = 1, 0\n elif dir=='y':\n dxd_, dyd_ = 0, 1\n def func(s):\n return ( ((x - (p.xa - np.sin(p.beta)*s))*dxd_\n +(y - (p.ya + np.cos(p.beta)*s))*dyd_)\n / ((x - (p.xa - np.sin(p.beta)*s))**2\n +(y - (p.ya + np.cos(p.beta)*s))**2) )\n return integrate.quad(lambda s:func(s), 0., p.length)[0]\n\ndef SolvePanelStrengths(panels):\n \"\"\"Create and solve linear system of equations for panel strength\n distributions so that flow is tangent to every panel at panel surface.\n\n panels --> array of panels\n \"\"\"\n n_panel = len(panels)\n #Populate matrix of system of equations for each panel\n size = (n_panel, n_panel)\n A = np.zeros(size)\n #Fill diagonal with term for each panel's contribution to itself\n np.fill_diagonal(A, 0.5)\n #Fill matrix with each panel's contribution to every other panel\n for i, pi in enumerate(panels):\n for j, pj in enumerate(panels):\n if i != j:\n A[i,j] = PanelIntegral(pi, pj, 'normal')\n\n #Populate b vector\n b = -Vinf * np.cos([p.beta for p in panels])\n #solve for strengths\n strengths = np.linalg.solve(A,b)\n #assign to panel objects\n for i, p in enumerate(panels):\n p.strength = strengths[i]\n #Check for closed body\n totalstrength = sum([p.strength * p.length for p in panels])\n if totalstrength<10e-6:\n print('Net Source Strength = ', totalstrength, ' (Closed Body)\\n')\n else:\n print('Net Source Strength = ', totalstrength, ' (Open Body)\\n')\n\n return panels\n\ndef SurfacePressure(panels):\n \"\"\"Calculate velocity tangent to body surface. Caclulate Cp from\n Bernoulli. Plot surface Pressure.\n\n panels --> array of panels\n \"\"\"\n n_panel = len(panels)\n #Populate matrix of system of equations for each panel\n size = (n_panel, n_panel)\n A = np.zeros(size)\n #Fill diagonal with term for each panel's contribution to itself\n np.fill_diagonal(A, 0.)\n #Fill matrix with each panel's contribution to every other panel\n for i, pi in enumerate(panels):\n for j, pj in enumerate(panels):\n if i != j:\n A[i,j] = PanelIntegral(pi, pj, 'tangent')\n\n #Populate b vector\n b = -Vinf * np.sin([p.beta for p in panels])\n #solve system for tangential velocities\n vt = np.dot(A, [p.strength for p in panels]) + b\n #Get surface pressure\n vdummy = np.zeros(len(vt))\n Cp_surf = V2Cp(vt, vdummy)\n #assign to panel objects\n for i, p in enumerate(panels):\n p.vt = vt[i]\n p.Cp_surf = Cp_surf[i]\n\n return panels\n\ndef VelocityField(panels, Vinf, X, Y):\n \"\"\"Returns the velocity field.\n\n Arguments\n ---------\n panels -- array of panels.\n freestream -- farfield conditions.\n X, Y -- mesh grid.\n \"\"\"\n Nx, Ny = X.shape\n u, v = np.empty((Nx, Ny), dtype=float), np.empty((Nx, Ny), dtype=float)\n\n for i in range(Nx):\n for j in range(Ny):\n u[i,j] = (Vinf + 0.5/np.pi*sum([p.strength\n *PointIntegral(X[i,j], Y[i,j], p, 'x') for p in panels]))\n v[i,j] = (Vinf*0 + 0.5/np.pi*sum([p.strength\n *PointIntegral(X[i,j], Y[i,j], p, 'y') for p in panels]))\n return u, v\n\ndef V2Cp(u, v):\n \"\"\"Get pressure coefficient given cartesian velocity components using bernoulli'strength\n u--> x-velocity component\n v--> y-velocity component\n Vinf--> freestream velocity, global variable\n \"\"\"\n #Find Pressure Field\n Vmag = (u**2 + v**2)**(0.5)\n Cp = 1 - (Vmag/Vinf)**2\n return Cp\n\nglobal Vinf\n#INPUTS\nVinf = 1 #Freestream velocity [nd]\ntxt_lbl = 18 #label fontsize\ntxt_ttl = 17 #title fontsize\nmkr = 8\n\ndef main(xgeom, ygeom, n_panel):\n \"\"\" Run simulation for various amounts of panels\n n_panel --> number of panels\n \"\"\"\n\n #MAKE NUMERIC DOMAIN\n L = max(xgeom) - min(xgeom)\n H = max(ygeom) - min(ygeom)\n nmesh = 15\n x = np.linspace(-L, 2*L, nmesh)\n y = np.linspace(-5*H*0, 5*H, nmesh)\n X, Y = np.meshgrid(x, y)\n\n print('Discretizing Geometry...')\n #Discretize geometry into panels\n\n # xgeom, ygeom = makeSymGeom.main(xgeom, ygeom, n_panel-1)\n # xgeom = np.append(xgeom, xgeom[0])\n # ygeom = np.append(ygeom, ygeom[0])\n # print('xgeom ', xgeom)\n # print('ygeom ', ygeom)\n\n # panels = MakePanels(xgeom, ygeom, n_panel, 'given')\n\n panels = MakePanels(xgeom, ygeom, n_panel, 'constantairfoil')\n\n\n\n #Plot panel geometry\n PlotPanels(xgeom, ygeom, panels, 'Delorian', 1)\n #solve for panel strength distributions\n print('Solving system of panels')\n panels = SolvePanelStrengths(panels)\n #Find and plot surface pressure distribution\n print('Calculating surface pressure')\n panels = SurfacePressure(panels)\n\n print('Calculating velocity field')\n u, v = VelocityField(panels, Vinf, X, Y)\n\n print('Plotting velocity field')\n plt.figure()\n plt.plot(xgeom, ygeom, color='black')\n plt.streamplot(X, Y, u, v, density=1, linewidth=1,\n arrowsize=1, arrowstyle='->')\n # plt.xlim(-L, 2*L)\n # plt.ylim(0, 5*H)\n plt.axis('equal')\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n\n X, Y, Z = np.loadtxt('data/delorian_pts_nonvert.csv',\n unpack=True, delimiter=\",\", skiprows=1)\n X, Y = np.loadtxt('data/naca0012.dat',\n unpack=True, skiprows=1)\n N = 81\n\n main(X, Y, N)\n","sub_path":"code/pj5_Airfoils/sourcePanel.py","file_name":"sourcePanel.py","file_ext":"py","file_size_in_byte":15705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"99088501","text":"#!/usr/bin/python\n\n\"\"\"This file is part of asyncoro; see http://asyncoro.sourceforge.net for\ndetails.\n\nThis program can be used to start discoro server processes so discoro scheduler\n(see 'discoro.py') can send computations to these server processes for executing\ndistributed communicating proceses (coroutines). All coroutines in a server\nexecute in the same thread, so multiple CPUs are not used by one server. If CPU\nintensive computations are to be run on systems with multiple processors, then\nthis program should be run with multiple instances (see below for '-c' option to\nthis program).\n\nSee 'discoro_client*.py' files for example use cases.\n\"\"\"\n\n__author__ = \"Giridhar Pemmasani (pgiri@yahoo.com)\"\n__copyright__ = \"Copyright (c) 2014 Giridhar Pemmasani\"\n__license__ = \"MIT\"\n__url__ = \"http://asyncoro.sourceforge.net\"\n\n\ndef _discoro_server_proc():\n # coroutine\n \"\"\"Server process receives computations and runs coroutines for it.\n \"\"\"\n\n import os\n import shutil\n import traceback\n import sys\n import time\n\n try:\n import psutil\n except:\n psutil = None\n\n import asyncoro.disasyncoro as asyncoro\n from asyncoro.disasyncoro import Coro, SysCoro\n from asyncoro.discoro import MinPulseInterval, MaxPulseInterval, \\\n DiscoroNodeInfo, DiscoroNodeAvailInfo\n\n _discoro_coro = asyncoro.AsynCoro.cur_coro()\n _discoro_config = yield _discoro_coro.receive()\n assert _discoro_config['req'] == 'config'\n _discoro_coro.register('discoro_server')\n _discoro_timer_coro = _discoro_config['timer_coro']\n yield asyncoro.AsynCoro.instance().peer(_discoro_timer_coro.location)\n\n if _discoro_config['min_pulse_interval'] > 0:\n MinPulseInterval = _discoro_config['min_pulse_interval']\n if _discoro_config['max_pulse_interval'] > 0:\n MaxPulseInterval = _discoro_config['max_pulse_interval']\n _discoro_msg_timeout = _discoro_config.pop('msg_timeout')\n _discoro_ntotal_coros = _discoro_config.pop('ntotal_coros')\n _discoro_busy_time = _discoro_config.pop('busy_time')\n\n _discoro_name = asyncoro.AsynCoro.instance().name\n asyncoro.AsynCoro.instance().dest_path = os.path.join('discoro', _discoro_name)\n _discoro_dest_path = asyncoro.AsynCoro.instance().dest_path\n _discoro_pid_path = os.path.join(_discoro_dest_path, '..', '%s.pid' % _discoro_name)\n _discoro_pid_path = os.path.normpath(_discoro_pid_path)\n # TODO: is file locking necessary?\n if os.path.exists(_discoro_pid_path):\n with open(_discoro_pid_path, 'r') as _discoro_req:\n _discoro_var = _discoro_req.read()\n _discoro_var = int(_discoro_var)\n if not _discoro_config['phoenix']:\n print('\\n Another discoronode seems to be running;\\n'\n ' make sure server with PID %d quit and remove \"%s\"\\n' %\n (_discoro_var, _discoro_pid_path))\n _discoro_var = os.getpid()\n\n import signal\n try:\n os.kill(_discoro_var, signal.SIGTERM)\n except:\n pass\n else:\n time.sleep(0.1)\n try:\n if os.waitpid(_discoro_var, os.WNOHANG)[0] != _discoro_var:\n asyncoro.logger.warning('Killing process %d failed', _discoro_var)\n except:\n pass\n del signal\n if os.path.isdir(_discoro_dest_path):\n shutil.rmtree(_discoro_dest_path)\n os.makedirs(_discoro_dest_path)\n os.chdir(_discoro_dest_path)\n sys.path.insert(0, _discoro_dest_path)\n with open(_discoro_pid_path, 'w') as _discoro_var:\n _discoro_var.write('%s' % os.getpid())\n\n def _discoro_peer(peer, coro=None):\n yield asyncoro.AsynCoro.instance().peer(peer)\n\n for _discoro_var in _discoro_config.pop('peers', []):\n Coro(_discoro_peer, _discoro_var)\n del _discoro_peer\n\n for _discoro_var in ['req', 'phoenix', 'min_pulse_interval', 'max_pulse_interval']:\n del _discoro_config[_discoro_var]\n\n asyncoro.logger.info('discoro server \"%s\" started at %s; '\n 'computation files will be saved in \"%s\"',\n _discoro_name, _discoro_coro.location, _discoro_dest_path)\n _discoro_req = _discoro_client = _discoro_auth = _discoro_msg = None\n _discoro_scheduler_status = _discoro_scheduler_notify = _discoro_peer_status = None\n _discoro_monitor_coro = _discoro_monitor_proc = _discoro_cur_peer = None\n _discoro_computation = _discoro_func = _discoro_var = None\n _discoro_job_coros = set()\n _discoro_jobs_done = asyncoro.Event()\n _discoro_globals = {}\n _discoro_locals = {}\n _discoro_modules = dict(sys.modules)\n _discoro_globals.update(globals())\n _discoro_locals.update(locals())\n\n def _discoro_peer_status(coro=None):\n coro.set_daemon()\n while 1:\n status = yield coro.receive()\n if (isinstance(status, asyncoro.PeerStatus) and\n status.status == asyncoro.PeerStatus.Offline and\n _discoro_scheduler_status and _discoro_scheduler_status.location == status.location):\n auth = _discoro_computation._auth if _discoro_computation else None\n asyncoro.logger.debug('Scheduler at %s quit%s', status.location,\n '; closing computation %s' % auth if auth else '')\n _discoro_coro.send({'req': 'close', 'auth': auth,\n 'proc_auth': _discoro_config['auth']})\n\n def _discoro_monitor_proc(coro=None):\n coro.set_daemon()\n while 1:\n msg = yield coro.receive()\n if isinstance(msg, asyncoro.MonitorException):\n asyncoro.logger.debug('coro %s done', msg.args[0])\n _discoro_job_coros.discard(msg.args[0])\n if not _discoro_job_coros:\n _discoro_jobs_done.set()\n with _discoro_ntotal_coros.get_lock():\n _discoro_ntotal_coros.value -= 1\n _discoro_busy_time.value = int(time.time())\n else:\n asyncoro.logger.warning('%s: invalid monitor message %s ignored',\n coro.location, type(msg))\n\n _discoro_monitor_coro = SysCoro(_discoro_monitor_proc)\n asyncoro.AsynCoro.instance().peer_status(SysCoro(_discoro_peer_status))\n\n while 1:\n _discoro_msg = yield _discoro_coro.receive()\n if not isinstance(_discoro_msg, dict):\n continue\n _discoro_req = _discoro_msg.get('req', None)\n\n if _discoro_req == 'run':\n _discoro_client = _discoro_msg.get('client', None)\n _discoro_auth = _discoro_msg.get('auth', None)\n _discoro_func = _discoro_msg.get('func', None)\n if (not isinstance(_discoro_client, Coro) or not _discoro_computation or\n _discoro_auth != _discoro_computation._auth):\n asyncoro.logger.warning('invalid run: %s', type(_discoro_func))\n if isinstance(_discoro_client, Coro):\n _discoro_client.send(None)\n continue\n try:\n _discoro_func = asyncoro.unserialize(_discoro_func)\n if _discoro_func.code:\n exec(_discoro_func.code) in globals()\n except:\n asyncoro.logger.debug('invalid computation to run')\n job_coro = (sys.exc_info()[0], getattr(_discoro_func, 'name', _discoro_func),\n traceback.format_exc())\n _discoro_client.send(job_coro)\n else:\n Coro._asyncoro._lock.acquire()\n try:\n job_coro = Coro(globals()[_discoro_func.name],\n *(_discoro_func.args), **(_discoro_func.kwargs))\n except:\n job_coro = (sys.exc_info()[0], getattr(_discoro_func, 'name', _discoro_func),\n traceback.format_exc())\n else:\n _discoro_job_coros.add(job_coro)\n with _discoro_ntotal_coros.get_lock():\n _discoro_ntotal_coros.value += 1\n _discoro_busy_time.value = int(time.time())\n asyncoro.logger.debug('coro %s created', job_coro)\n job_coro.notify(_discoro_monitor_coro)\n job_coro.notify(_discoro_scheduler_notify)\n _discoro_client.send(job_coro)\n Coro._asyncoro._lock.release()\n del job_coro\n elif _discoro_req == 'setup':\n _discoro_client = _discoro_msg.get('client', None)\n _discoro_scheduler_status = _discoro_msg.get('status', None)\n _discoro_scheduler_notify = _discoro_msg.get('notify', None)\n if (not isinstance(_discoro_client, Coro) or\n not isinstance(_discoro_scheduler_status, Coro) or\n not isinstance(_discoro_scheduler_notify, Coro)):\n continue\n if _discoro_computation is not None:\n asyncoro.logger.debug('invalid \"setup\" - busy')\n _discoro_client.send(-1)\n continue\n if _discoro_cur_peer != _discoro_scheduler_status.location:\n # asyncoro.AsynCoro.instance().close_peer(_discoro_cur_peer)\n yield asyncoro.AsynCoro.instance().peer(_discoro_scheduler_status.location)\n _discoro_cur_peer = _discoro_scheduler_status.location\n os.chdir(_discoro_dest_path)\n try:\n _discoro_computation = _discoro_msg['computation']\n exec('import asyncoro.disasyncoro as asyncoro') in globals()\n if _discoro_computation._code:\n exec(_discoro_computation._code) in globals()\n except:\n _discoro_computation = None\n asyncoro.logger.warning('invalid computation')\n asyncoro.logger.debug(traceback.format_exc())\n _discoro_client.send(-1)\n continue\n if (isinstance(_discoro_computation._pulse_interval, int) and\n MinPulseInterval <= _discoro_computation._pulse_interval <= MaxPulseInterval):\n _discoro_computation._pulse_interval = _discoro_computation._pulse_interval\n else:\n _discoro_computation._pulse_interval = MinPulseInterval\n _discoro_timer_coro.send({'scheduler_coro': _discoro_scheduler_status,\n 'auth': _discoro_computation._auth,\n 'interval': _discoro_computation._pulse_interval,\n 'zombie_period': _discoro_computation.zombie_period,\n 'disk_path': _discoro_dest_path})\n _discoro_busy_time.value = int(time.time())\n asyncoro.logger.debug('%s: Computation \"%s\" from %s with zombie period %s',\n _discoro_coro.location, _discoro_computation._auth,\n _discoro_msg['client'].location, _discoro_computation.zombie_period)\n _discoro_client.send(0)\n elif _discoro_req == 'close':\n _discoro_auth = _discoro_msg.get('auth', None)\n if not _discoro_auth:\n _discoro_auth = _discoro_msg.get('proc_auth', None)\n if not _discoro_computation or (_discoro_auth != _discoro_computation._auth and\n _discoro_auth != _discoro_config['auth']):\n continue\n for _discoro_var in _discoro_job_coros:\n _discoro_var.terminate()\n _discoro_jobs_done.clear()\n while _discoro_job_coros:\n asyncoro.logger.debug('%s: Waiting for %s coroutines to terminate '\n 'before closing computation',\n _discoro_coro.location, len(_discoro_job_coros))\n if (yield _discoro_jobs_done.wait(timeout=5)):\n break\n asyncoro.logger.debug('%s: Closing computation \"%s\"',\n _discoro_coro.location, _discoro_computation._auth)\n\n for _discoro_var in list(globals()):\n if _discoro_var not in _discoro_globals:\n globals().pop(_discoro_var, None)\n globals().update(_discoro_globals)\n\n for _discoro_var in sys.modules.keys():\n if _discoro_var not in _discoro_modules:\n sys.modules.pop(_discoro_var, None)\n sys.modules.update(_discoro_modules)\n\n for _discoro_var in os.listdir(_discoro_dest_path):\n _discoro_var = os.path.join(_discoro_dest_path, _discoro_var)\n if os.path.isdir(_discoro_var) and not os.path.islink(_discoro_var):\n shutil.rmtree(_discoro_var, ignore_errors=True)\n else:\n os.remove(_discoro_var)\n if not os.path.isdir(_discoro_dest_path):\n try:\n os.remove(_discoro_dest_path)\n except:\n pass\n os.makedirs(_discoro_dest_path)\n if not os.path.isfile(_discoro_pid_path):\n try:\n if os.path.islink(_discoro_pid_path):\n os.remove(_discoro_pid_path)\n else:\n shutil.rmtree(_discoro_pid_path)\n with open(_discoro_pid_path, 'w') as _discoro_var:\n _discoro_var.write('%s' % os.getpid())\n except:\n asyncoro.logger.warning('PID file \"%s\" is invalid', _discoro_pid_path)\n if _discoro_auth != _discoro_computation._auth and _discoro_scheduler_status:\n _discoro_scheduler_status.send({'status': 'ServerClosed',\n 'location': _discoro_coro.location})\n _discoro_timer_coro.send({'scheduler_coro': None, 'interval': None,\n 'disk_path': '', 'auth': _discoro_computation._auth})\n os.chdir(_discoro_dest_path)\n asyncoro.AsynCoro.instance().dest_path = _discoro_dest_path\n _discoro_computation = _discoro_client = None\n _discoro_scheduler_status = _discoro_scheduler_notify = None\n _discoro_var = _discoro_msg.get('client', None)\n if isinstance(_discoro_var, Coro):\n _discoro_var.send(0)\n if _discoro_msg.get('proc_auth', None):\n asyncoro.AsynCoro.instance().close_peer(_discoro_cur_peer)\n _discoro_cur_peer = None\n if _discoro_config['serve'] > 0:\n _discoro_config['serve'] -= 1\n if _discoro_config['serve'] == 0:\n break\n elif _discoro_req == 'node_info':\n if psutil:\n _discoro_var = DiscoroNodeAvailInfo(_discoro_coro.location.addr,\n 100.0 - psutil.cpu_percent(),\n psutil.virtual_memory().available,\n psutil.disk_usage(_discoro_dest_path).free,\n 100.0 - psutil.swap_memory().percent)\n else:\n _discoro_var = None\n # _discoro_name is host name followed by '-' and ID\n _discoro_var = DiscoroNodeInfo(_discoro_name[:_discoro_name.rfind('-')],\n _discoro_coro.location.addr, _discoro_var)\n _discoro_client = _discoro_msg.get('client', None)\n if isinstance(_discoro_client, Coro):\n _discoro_client.send(_discoro_var)\n elif _discoro_req == 'status':\n if _discoro_msg.get('proc_auth', None) != _discoro_config['auth']:\n asyncoro.logger.debug('ignoring info: %s', _discoro_msg.get('auth'))\n continue\n if _discoro_scheduler_status:\n print(' Server \"%s\" @ %s running %d coroutines for %s' %\n (_discoro_name, _discoro_coro.location, len(_discoro_job_coros),\n _discoro_scheduler_status.location))\n else:\n print(' Server \"%s\" @ %s not used by any computation' %\n (_discoro_name, _discoro_coro.location))\n elif _discoro_req == 'quit':\n if _discoro_msg.get('proc_auth', None) != _discoro_config['auth']:\n asyncoro.logger.debug('ignoring quit: %s', _discoro_msg.get('auth'))\n continue\n if _discoro_scheduler_status:\n _discoro_scheduler_status.send({'status': 'ServerClosed',\n 'location': _discoro_coro.location})\n break\n elif _discoro_req == 'terminate':\n if _discoro_msg.get('proc_auth', None) != _discoro_config['auth']:\n asyncoro.logger.debug('ignoring terminate: %s', _discoro_msg.get('auth'))\n continue\n if _discoro_computation:\n msg = {'req': 'close', 'proc_auth': _discoro_config['auth']}\n _discoro_config['serve'] = 1\n _discoro_coro.send(msg)\n else:\n break\n else:\n asyncoro.logger.warning('invalid command \"%s\" ignored', _discoro_req)\n _discoro_client = _discoro_msg.get('client', None)\n if not isinstance(_discoro_client, Coro):\n continue\n _discoro_client.send(-1)\n\n # wait until all computations are done; process only 'close'\n while _discoro_job_coros:\n _discoro_msg = yield _discoro_coro.receive(60)\n if not _discoro_job_coros and not _discoro_msg:\n _discoro_msg = {'req': 'close', 'auth': _discoro_computation._auth}\n if not isinstance(_discoro_msg, dict):\n continue\n _discoro_req = _discoro_msg.get('req', None)\n\n if _discoro_req == 'close' or not _discoro_job_coros:\n _discoro_auth = _discoro_msg.get('auth', None)\n if _discoro_auth != _discoro_computation._auth:\n continue\n asyncoro.logger.debug('%s deleting computation \"%s\"',\n _discoro_coro.location, _discoro_computation._auth)\n\n for _discoro_var in list(globals()):\n if _discoro_var not in _discoro_globals:\n globals().pop(_discoro_var, None)\n globals().update(_discoro_globals)\n\n break\n else:\n asyncoro.logger.warning('invalid command \"%s\" ignored', _discoro_req)\n _discoro_client = _discoro_msg.get('client', None)\n if not isinstance(_discoro_client, Coro):\n continue\n _discoro_client.send(-1)\n\n if _discoro_scheduler_status:\n _discoro_scheduler_status.send({'status': 'ServerClosed',\n 'location': _discoro_coro.location})\n for _discoro_var in os.listdir(_discoro_dest_path):\n _discoro_var = os.path.join(_discoro_dest_path, _discoro_var)\n if os.path.isdir(_discoro_var) and not os.path.islink(_discoro_var):\n shutil.rmtree(_discoro_var, ignore_errors=True)\n else:\n os.remove(_discoro_var)\n if os.path.isfile(_discoro_pid_path):\n os.remove(_discoro_pid_path)\n _discoro_config['mp_queue'].put({'req': 'quit', 'proc_auth': _discoro_config['auth']})\n asyncoro.logger.debug('discoro server \"%s\" @ %s terminated',\n _discoro_name, _discoro_coro.location)\n\n\ndef _discoro_process(_discoro_config, _discoro_server_id, _discoro_auth,\n _discoro_mp_queue, _discoro_ntotal_coros, _discoro_busy_time):\n import os\n import logging\n import asyncoro.disasyncoro as asyncoro\n\n if _discoro_config['loglevel']:\n asyncoro.logger.setLevel(logging.DEBUG)\n else:\n asyncoro.logger.setLevel(logging.INFO)\n del _discoro_config['loglevel']\n\n _discoro_config_msg = {'req': 'config', 'id': _discoro_server_id,\n 'phoenix': _discoro_config.pop('phoenix', False),\n 'serve': _discoro_config.pop('serve', -1),\n 'peers': _discoro_config.pop('peers', []),\n 'msg_timeout': _discoro_config.pop('msg_timeout', asyncoro.MsgTimeout),\n 'min_pulse_interval': _discoro_config.pop('min_pulse_interval'),\n 'max_pulse_interval': _discoro_config.pop('max_pulse_interval'),\n 'auth': _discoro_auth, 'mp_queue': _discoro_mp_queue,\n 'ntotal_coros': _discoro_ntotal_coros,\n 'busy_time': _discoro_busy_time}\n\n _discoro_scheduler = asyncoro.AsynCoro(**_discoro_config)\n _discoro_coro = asyncoro.SysCoro(_discoro_server_proc)\n # delete variables created in main\n for _discoro_var in globals().keys():\n if _discoro_var.startswith('_discoro_'):\n globals().pop(_discoro_var)\n\n del logging, os, _discoro_config, _discoro_var\n\n req_queue, _discoro_mp_queue = _discoro_mp_queue, None\n\n while 1:\n try:\n req = req_queue.get()\n except KeyboardInterrupt:\n req = {'req': 'terminate', 'proc_auth': _discoro_auth}\n req_queue.put(req)\n\n if not isinstance(req, dict) or req.get('proc_auth') != _discoro_auth:\n asyncoro.logger.warning('Ignoring invalid request: \"%s\"', type(req))\n continue\n\n cmd = req.get('req')\n if cmd == 'status' or cmd == 'close':\n _discoro_coro.send(req)\n elif cmd == 'start':\n _discoro_config_msg['timer_coro'] = req.get('timer_coro', None)\n _discoro_coro.send(_discoro_config_msg)\n del _discoro_config_msg\n elif cmd == 'quit' or cmd == 'terminate':\n _discoro_coro.send(req)\n break\n\n _discoro_scheduler.finish()\n exit(0)\n\n\nif __name__ == '__main__':\n\n \"\"\"\n See http://asyncoro.sourceforge.net/discoro.html#node-servers for details on\n options to start this program.\n \"\"\"\n\n import sys\n import time\n import argparse\n import multiprocessing\n import socket\n import os\n import collections\n import hashlib\n import logging\n try:\n import readline\n except:\n pass\n import asyncoro.disasyncoro as asyncoro\n\n try:\n import psutil\n except ImportError:\n print('\\n \\'psutil\\' module is not available; '\n 'CPU, memory, disk status will not be sent!\\n')\n psutil = None\n else:\n psutil.cpu_percent(0.1)\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--cpus', dest='cpus', type=int, default=0,\n help='number of CPUs/discoro instances to run; '\n 'if negative, that many CPUs are not used')\n parser.add_argument('-i', '--ip_addr', dest='node', default=None,\n help='IP address or host name of this node')\n parser.add_argument('--ext_ip_addr', dest='ext_ip_addr', default=None,\n help='External IP address to use (needed in case of NAT firewall/gateway)')\n parser.add_argument('-u', '--udp_port', dest='udp_port', type=int, default=51350,\n help='UDP port number to use')\n parser.add_argument('--tcp_ports', dest='tcp_ports', action='append', default=[],\n help='TCP port numbers to use')\n parser.add_argument('-n', '--name', dest='name', default=None,\n help='(symbolic) name given to AsynCoro schdulers on this node')\n parser.add_argument('--dest_path', dest='dest_path', default=None,\n help='path prefix to where files sent by peers are stored')\n parser.add_argument('--max_file_size', dest='max_file_size', default=None, type=int,\n help='maximum file size of any file transferred')\n parser.add_argument('-s', '--secret', dest='secret', default='',\n help='authentication secret for handshake with peers')\n parser.add_argument('--certfile', dest='certfile', default=None,\n help='file containing SSL certificate')\n parser.add_argument('--keyfile', dest='keyfile', default=None,\n help='file containing SSL key')\n parser.add_argument('--serve', dest='serve', default=-1, type=int,\n help='number of clients to serve before exiting')\n parser.add_argument('--msg_timeout', dest='msg_timeout', default=asyncoro.MsgTimeout, type=int,\n help='timeout for delivering messages')\n parser.add_argument('--min_pulse_interval', dest='min_pulse_interval', default=0, type=int,\n help='minimum pulse interval clients can use in number of seconds')\n parser.add_argument('--max_pulse_interval', dest='max_pulse_interval', default=0, type=int,\n help='maximum pulse interval clients can use in number of seconds')\n parser.add_argument('--daemon', action='store_true', dest='daemon', default=False,\n help='if given, input is not read from terminal')\n parser.add_argument('--phoenix', action='store_true', dest='phoenix', default=False,\n help='if given, server processes from previous run will be killed '\n 'and new server process started')\n parser.add_argument('--discover_peers', action='store_true', dest='discover_peers',\n default=False, help='if given, peers are discovered during startup')\n parser.add_argument('--peer', dest='peers', action='append', default=[],\n help='peer location (in the form node:TCPport) to communicate')\n parser.add_argument('-d', '--debug', action='store_true', dest='loglevel', default=False,\n help='if given, debug messages are printed')\n _discoro_config = vars(parser.parse_args(sys.argv[1:]))\n\n if _discoro_config['msg_timeout'] < 1:\n raise Exception('msg_timeout must be at least 1')\n if _discoro_config['min_pulse_interval']:\n if _discoro_config['min_pulse_interval'] < _discoro_config['msg_timeout']:\n raise Exception('min_pulse_interval must be at least msg_timeout')\n if (_discoro_config['max_pulse_interval'] and _discoro_config['min_pulse_interval'] and\n _discoro_config['max_pulse_interval'] < _discoro_config['min_pulse_interval']):\n raise Exception('max_pulse_interval must be at least min_pulse_interval')\n\n _discoro_cpus = multiprocessing.cpu_count()\n if _discoro_config['cpus'] > 0:\n if _discoro_config['cpus'] > _discoro_cpus:\n raise Exception('CPU count must be <= %s' % _discoro_cpus)\n _discoro_cpus = _discoro_config['cpus']\n elif _discoro_config['cpus'] < 0:\n if -_discoro_config['cpus'] >= _discoro_cpus:\n raise Exception('CPU count must be > -%s' % _discoro_cpus)\n _discoro_cpus += _discoro_config['cpus']\n del _discoro_config['cpus']\n\n _discoro_tcp_ports = set()\n tcp_port = tcp_ports = None\n for tcp_port in _discoro_config.pop('tcp_ports', []):\n tcp_ports = tcp_port.split('-')\n if len(tcp_ports) == 1:\n _discoro_tcp_ports.add(int(tcp_ports[0]))\n elif len(tcp_ports) == 2:\n _discoro_tcp_ports = _discoro_tcp_ports.union(range(int(tcp_ports[0]),\n int(tcp_ports[1]) + 1))\n else:\n raise Exception('Invalid TCP port range \"%s\"' % tcp_ports)\n _discoro_tcp_ports = sorted(_discoro_tcp_ports)\n\n if _discoro_tcp_ports:\n for tcp_port in range(_discoro_tcp_ports[-1] + 1,\n _discoro_tcp_ports[-1] + 1 +\n (_discoro_cpus + 1) - len(_discoro_tcp_ports)):\n _discoro_tcp_ports.append(tcp_port)\n else:\n _discoro_tcp_ports = [0] * (_discoro_cpus + 1)\n del tcp_port, tcp_ports\n\n peers, _discoro_config['peers'] = _discoro_config['peers'], []\n peer = None\n for peer in peers:\n peer = peer.split(':')\n if len(peer) != 2:\n raise Exception('peer %s is not valid' % ':'.join(peer))\n _discoro_config['peers'].append(asyncoro.Location(peer[0], peer[1]))\n del peer, peers\n\n _discoro_name = _discoro_config['name']\n if not _discoro_name:\n _discoro_name = socket.gethostname()\n if not _discoro_name:\n _discoro_name = 'discoro_server'\n\n _discoro_daemon = _discoro_config.pop('daemon', False)\n if not _discoro_daemon:\n try:\n if os.getpgrp() != os.tcgetpgrp(sys.stdin.fileno()):\n _discoro_daemon = True\n except:\n pass\n _discoro_auth = hashlib.sha1(os.urandom(10).encode('hex')).hexdigest()\n\n # delete variables not needed anymore\n del parser\n for _discoro_var in ['argparse', 'socket', 'os']:\n del sys.modules[_discoro_var], globals()[_discoro_var]\n del _discoro_var\n\n _discoro_server_infos = []\n _discoro_ServerInfo = collections.namedtuple('DiscoroServerInfo', ['Proc', 'Queue'])\n _discoro_mp_queue = None\n _discoro_ntotal_coros = multiprocessing.Value('L', 0)\n _discoro_busy_time = multiprocessing.Value('I', 0)\n for _discoro_server_id in range(1, _discoro_cpus + 1):\n _discoro_config['name'] = '%s-%s' % (_discoro_name, _discoro_server_id)\n _discoro_config['tcp_port'] = _discoro_tcp_ports[_discoro_server_id - 1]\n _discoro_mp_queue = multiprocessing.Queue()\n _discoro_server_info = _discoro_ServerInfo(\n multiprocessing.Process(target=_discoro_process,\n args=(dict(_discoro_config), _discoro_server_id, _discoro_auth,\n _discoro_mp_queue, _discoro_ntotal_coros,\n _discoro_busy_time)),\n _discoro_mp_queue)\n _discoro_server_infos.append(_discoro_server_info)\n _discoro_server_info.Proc.start()\n\n def _discoro_timer_proc(msg_timeout, _discoro_ntotal_coros, _discoro_busy_time, coro=None):\n from asyncoro.discoro import DiscoroNodeAvailInfo\n coro.set_daemon()\n async_scheduler = asyncoro.AsynCoro.instance()\n last_pulse = last_proc_check = time.time()\n interval = peer_coro = cur_peer = cur_auth = zombie_period = None\n while 1:\n msg = yield coro.receive(timeout=interval)\n if msg:\n auth = msg.get('auth', None)\n if cur_auth and (auth != cur_auth):\n asyncoro.logger.warning('Timer: invalid computation authentication: %s != %s',\n cur_auth, auth)\n continue\n if peer_coro == msg.get('scheduler_coro', None):\n continue\n peer_coro = msg.get('scheduler_coro', None)\n if not isinstance(peer_coro, asyncoro.Coro):\n asyncoro.logger.debug('Computation is done: %s', _discoro_ntotal_coros.value)\n interval = peer_coro = cur_auth = None\n continue\n cur_auth = auth\n interval = msg.get('interval', None)\n disk_path = msg.get('disk_path', '.')\n zombie_period = msg.get('zombie_period', None)\n if cur_peer != peer_coro.location:\n # async_scheduler.close_peer(cur_peer)\n cur_peer = peer_coro.location\n yield async_scheduler.peer(cur_peer)\n yield coro.sleep(0.5) # wait a bit for peer to be discovered\n last_pulse = time.time()\n if not peer_coro:\n continue\n\n msg = {'location': coro.location, 'ncoros': _discoro_ntotal_coros.value}\n if psutil:\n msg['node_status'] = DiscoroNodeAvailInfo(\n coro.location.addr, 100.0 - psutil.cpu_percent(),\n psutil.virtual_memory().available, psutil.disk_usage(disk_path).free,\n 100.0 - psutil.swap_memory().percent)\n\n now = time.time()\n sent = yield peer_coro.deliver(msg, timeout=msg_timeout)\n if sent == 1:\n last_pulse = now\n elif (now - last_pulse) > (5 * interval) and cur_auth:\n asyncoro.logger.warning('Scheduler is not reachable; closing computation \"%s\"',\n cur_auth)\n for _discoro_server_info in _discoro_server_infos:\n _discoro_server_info.Queue.put({'req': 'close', 'auth': cur_auth,\n 'proc_auth': _discoro_auth})\n async_scheduler.close_peer(cur_peer)\n cur_peer = None\n\n if ((not _discoro_ntotal_coros.value) and cur_auth and zombie_period and\n ((now - _discoro_busy_time.value) > zombie_period)):\n asyncoro.logger.warning('Closing zombie computation \"%s\"', cur_auth)\n for _discoro_server_info in _discoro_server_infos:\n _discoro_server_info.Queue.put({'req': 'close', 'auth': cur_auth,\n 'proc_auth': _discoro_auth})\n async_scheduler.close_peer(cur_peer)\n cur_peer = None\n if (now - last_proc_check) > (3 * interval):\n last_proc_check = now\n for _discoro_server_info in _discoro_server_infos:\n if not _discoro_server_info.Proc.is_alive():\n # TODO: inform scheduler, start new process?\n asyncoro.logger.warning('Process %s is dead?: %s',\n _discoro_server_info.Proc.pid,\n _discoro_server_info.Proc.exitcode)\n\n _discoro_server_id = 0\n _discoro_config['name'] = '%s-%s' % (_discoro_name, _discoro_server_id)\n _discoro_config['tcp_port'] = _discoro_tcp_ports[_discoro_server_id]\n _discoro_config.pop('phoenix', False)\n _discoro_config.pop('serve', -1)\n _discoro_config.pop('peers', [])\n _discoro_msg_timeout = _discoro_config.pop('msg_timeout')\n _discoro_config.pop('min_pulse_interval')\n _discoro_config.pop('max_pulse_interval')\n _discoro_config['discover_peers'] = False\n if _discoro_config['loglevel']:\n asyncoro.logger.setLevel(logging.DEBUG)\n else:\n asyncoro.logger.setLevel(logging.INFO)\n del _discoro_config['loglevel']\n _discoro_scheduler = asyncoro.AsynCoro(**_discoro_config)\n _discoro_timer_coro = asyncoro.Coro(_discoro_timer_proc, _discoro_msg_timeout,\n _discoro_ntotal_coros, _discoro_busy_time)\n for _discoro_server_info in _discoro_server_infos:\n _discoro_server_info.Queue.put({'req': 'start', 'proc_auth': _discoro_auth,\n 'timer_coro': _discoro_timer_coro})\n\n del multiprocessing, collections, _discoro_mp_queue, _discoro_tcp_ports, _discoro_config\n\n if not _discoro_daemon:\n def _discoro_cmd_reader(coro=None):\n coro.set_daemon()\n async_threads = asyncoro.AsyncThreadPool(1)\n while 1:\n yield coro.sleep(0.25)\n try:\n _discoro_cmd = yield async_threads.async_task(\n raw_input,\n '\\nEnter \"status\" to get status\\n'\n ' \"close\" to close current computation (kill any running jobs)\\n'\n ' \"quit\" to stop accepting new jobs and quit when done\\n'\n ' \"terminate\" to kill current jobs and quit: ')\n except GeneratorExit:\n break\n except:\n _discoro_cmd = ''\n else:\n _discoro_cmd = _discoro_cmd.strip().lower()\n if not _discoro_cmd:\n _discoro_cmd = 'status'\n\n print('')\n if _discoro_cmd == 'status' or _discoro_cmd == 'close':\n for _discoro_server_info in _discoro_server_infos:\n _discoro_server_info.Queue.put({'req': _discoro_cmd,\n 'proc_auth': _discoro_auth})\n elif _discoro_cmd in ('quit', 'terminate'):\n for _discoro_server_info in _discoro_server_infos:\n _discoro_server_info.Queue.put({'req': _discoro_cmd,\n 'proc_auth': _discoro_auth})\n else:\n for i, _discoro_server_info in enumerate(_discoro_server_infos, start=1):\n if _discoro_server_info.Proc.is_alive():\n print(' Process %s is still running' % i)\n\n asyncoro.Coro(_discoro_cmd_reader)\n\n while 1:\n try:\n for _discoro_server_info in _discoro_server_infos:\n if _discoro_server_info.Proc.is_alive():\n _discoro_server_info.Proc.join()\n break\n except:\n for i, _discoro_server_info in enumerate(_discoro_server_infos, start=1):\n if _discoro_server_info.Proc.is_alive():\n print('Process %s is still running; terminating it' % i)\n _discoro_server_info.Proc.terminate()\n break\n\n exit(0)\n","sub_path":"py2/asyncoro/discoronode.py","file_name":"discoronode.py","file_ext":"py","file_size_in_byte":37867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"164622683","text":"#!/usr/bin/env python3\n\n#Stopping conditions\nfloatQuit1 = -1.0\nfloatQuit2 = -99.0\nintQuit1 = -1\nintQuit2 = -99\nstrQuit1 = \"quit\"\nstrQuit2 = \"QUIT\"\n\n#booleans that determing which query to ask each run of the while\nfloatQuery = True\nintQuery = True\nstringQuery = True\n\n#while any one of the booleans are true (meaning we are still checking calculating the float or int or string)\n#program exits when all 3 are False, and none of the values are being calculated (meaning user entered the quit value for all 3)\nwhile(floatQuery or intQuery or stringQuery):\n\n\t#check if should prompt for that question\n\tif(floatQuery):\n\t\tfloatVal = input(\"Enter float: \")\n\t\tfloatVal = float(floatVal)\n\tif(intQuery):\n\t\tintVal = input(\"Enter int: \")\n\t\tintVal = int(intVal)\n\tif(stringQuery):\n\t\tstringVal = input(\"Enter string: \")\n\n\tprint(\"\")\n\n\t#as long as the quit values aren't met, calculate values\n\tif(floatVal == floatQuit1 or floatVal == floatQuit2):\n\t\tfloatQuery = False\n\telse:\n\t\tfloatVal = floatVal**(1/10)\n\t\tprint(\"float: \" + str(floatVal))\n\n\tif(intVal == intQuit1 or intVal == intQuit2):\n\t\tintQuery = False\n\telse:\n\t\tintVal = intVal**10\n\t\tprint(\"int: \" + str(intVal))\n\n\tif(stringVal == strQuit1 or stringVal == strQuit2):\n\t\tstringQuery = False\n\telse:\n\t\tstringVal = stringVal + stringVal\n\t\tprint(\"string: \" + stringVal)\n\tprint(\"\")\n","sub_path":"231/Assignment_4/assignment4_2.py","file_name":"assignment4_2.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"117620062","text":"import os\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch.utils.data import TensorDataset, DataLoader\r\nimport pandas as pd\r\nimport ast\r\nimport wandb\r\nfrom os import path\r\nimport math\r\nimport sys\r\n\r\nclass RMSLELoss(torch.nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n self.mse = torch.nn.MSELoss()\r\n \r\n def forward(self, pred, actual):\r\n return self.mse(torch.log(pred.float() + 1), torch.log(actual.float() + 1))\r\n\r\nfrom featureblocks_16khz import FeatureBlock3\r\n\r\nnum_epochs = 1000\r\nframe_length = 16000\r\noverlapping_fraction = 0.1\r\n\r\ndata = torch.Tensor()\r\nfolds = os.listdir('./folded_dataset_16khz/')\r\nexc = folds[9]\r\nmodel_name = 'model_'+exc\r\n\r\n#import pdb; pdb.set_trace()\r\n\r\nfor fold in folds:\r\n if fold != exc:\r\n current_fold = torch.load('./folded_dataset_16khz/'+fold)\r\n data = torch.cat((data,current_fold))\r\n\r\n# Shuffle dataset before we do anything\r\n#data=data[torch.randperm(data.size()[0])]\r\n\r\nX_train = data[:, 0:frame_length].clone()\r\nY_train = data[:,frame_length:].clone()\r\n\r\nY_train = Y_train.type(torch.LongTensor)\r\nY_train_one_hot = F.one_hot(Y_train)\r\n#print(Y_train_one_hot)\r\n\r\n\r\nX_train = X_train.reshape(-1, 16,1000)\r\nprint(\"X_size:{}\".format(X_train.size()))\r\nY_train_one_hot = Y_train_one_hot.reshape(-1,10)\r\nprint(\"Y_size:{}\".format(Y_train_one_hot.size()))\r\naudio_dataset = TensorDataset (X_train, Y_train)\r\naudio_dataloader = DataLoader (audio_dataset, batch_size = 250, shuffle= False)\r\n\r\n\r\n# The trinity of models\r\nmodel = FeatureBlock3().cuda()\r\nloss_function = torch.nn.CrossEntropyLoss()\r\n# This is what controls the gradient descent\r\noptimizer = torch.optim.Adam(model.parameters(),lr=0.001, weight_decay=0.00001)\r\nT_max = 500\r\nscheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_max)\r\niteration = 0\r\n\r\nwandb.init(project='end2end1D')\r\nconfig = wandb.config\r\n\r\nbest_loss = math.inf\r\n# Load model if exists\r\nif path.exists(model_name):\r\n checkpoint = torch.load(model_name, map_location=lambda storage, loc: storage.cuda())\r\n model.load_state_dict(checkpoint['model_state_dict'])\r\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\r\n #scheduler.load_state_dict(checkpoint['scheduler_state_dict'])\r\n best_loss = checkpoint['loss']\r\n print(\"Loaded model from {} with loss {}\".format(model_name, checkpoint['loss']))\r\n\r\nmodel.train()\r\nwandb.watch(model)\r\n\r\ntrain_accu = []\r\ntrain_losses = []\r\n\r\neval_losses=[]\r\neval_accu=[]\r\n\r\n\r\nfor epoch in range(num_epochs):\r\n running_loss=0\r\n correct=0\r\n total=0\r\n\r\n print('Epoch-{0} lr: {1}'.format(epoch, optimizer.param_groups[0]['lr']))\r\n losses = []\r\n for index,(x,y) in enumerate(audio_dataloader):\r\n y_hat = y.cuda()\r\n optimizer.zero_grad()\r\n outputs = model(x.float().cuda())\r\n outputs = outputs.float()\r\n \r\n y_hat = y_hat.squeeze(1)\r\n loss = loss_function(outputs, y_hat)\r\n loss.backward()\r\n optimizer.step()\r\n \r\n running_loss += loss.item()\r\n _, predicted = outputs.max(1)\r\n total += y_hat.size(0)\r\n correct += predicted.eq(y_hat).sum().item()\r\n \r\n print(\"iteration:{} loss:{} \".format(iteration, loss.item()))\r\n losses.append(loss.item())\r\n iteration += 1\r\n \r\n scheduler.step()\r\n wandb.log({\"loss\": loss, \"epoch\": epoch, \"learning_rate\": optimizer.param_groups[0]['lr']})\r\n \r\n # calculate avg loss\r\n avg_loss = sum(losses) / len(losses)\r\n \r\n train_loss=running_loss/len(audio_dataloader)\r\n accu=100.*correct/total\r\n\r\n \r\n train_accu.append(accu)\r\n train_losses.append(train_loss)\r\n print('Train Loss: %.3f | Accuracy: %.3f'%(train_loss,accu))\r\n wandb.log({\"Accuracy\": accu})\r\n\r\n if avg_loss < best_loss:\r\n print(\"Found best loss: {}, saving model...\".format(avg_loss))\r\n best_loss = avg_loss\r\n torch.save(\r\n {\r\n \"loss\": best_loss,\r\n \"accuracy\": accu,\r\n \"model_state_dict\": model.state_dict(),\r\n \"optimizer_state_dict\": optimizer.state_dict(),\r\n \"scheduler_state_dict\": scheduler.state_dict(),\r\n },\r\n \"./{}\".format(model_name)\r\n )\r\n","sub_path":"end2end/.ipynb_checkpoints/train_folded-checkpoint.py","file_name":"train_folded-checkpoint.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"129357956","text":"import random\nimport colorsys\n\nfrom openrazer.client import DeviceManager\nfrom openrazer.client import constants as razer_constants\n\ndef random_color():\n rgb = colorsys.hsv_to_rgb(random.uniform(0, 1), random.uniform(0.5, 1), 1)\n return tuple(map(lambda x: int(256 * x), rgb))\n\n# Create a DeviceManager. This is used to get specific devices\ndevice_manager = DeviceManager()\n\nprint(\"[.] Found {} Razer devices\".format(len(device_manager.devices)))\nprint()\n\n# Disable daemon effect syncing.\n# Without this, the daemon will try to set the lighting effect to every device.\ndevice_manager.sync_effects = False\n\n# Iterate over each device and set the wave effect\nfor device in device_manager.devices:\n color = random_color()\n device.fx.static(*color)\n\n\n","sub_path":"pyscripts/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"175222389","text":"#Realizado por: XyY\r\n#Fecha de creación: 24/5/2019 9:10 pm\r\n#Última actualización: 6/6/2019 4:40 pm\r\n#Versión 3.7.2\r\n\r\n#Importación de librerías\r\nimport pickle\r\n\r\n#Definición de funciones\r\n\r\ndef graba(parchivo,plista):\r\n \"\"\"\r\n Función: Grabar la lista ingresada en un archivo\r\n Entrada: Nombre del archivo (string) y la lista (list)\r\n Salida: Archivo con modificaciones\r\n \"\"\"\r\n try:\r\n f=open(parchivo,\"wb\")\r\n print(\"Se grabará el archivo:\",parchivo)\r\n pickle.dump(plista,f)\r\n print(\"Se cerrará el archivo:\",parchivo)\r\n f.close()\r\n except:\r\n print(\"Error al grabar el archivo:\",parchivo)\r\n return\r\n\r\ndef lee(parchivo):\r\n \"\"\"\r\n Función: Cargar (leer) la información almacenada en el archivo\r\n Entrada: Archivo a solicitar\r\n Salida: Lista con el contenido del archivo (list)\r\n \"\"\"\r\n try:\r\n f=open(parchivo,\"rb\")\r\n print(\"Se leerá el archivo:\",parchivo)\r\n lista=pickle.load(f)\r\n print(\"Se cerrará el archivo:\",parchivo)\r\n f.close()\r\n return lista\r\n except:\r\n print(\"Error al leer el archivo:\",parchivo)\r\n return [] #Modificado para que en caso de que el archivo no exista devuelva una lista vacía\r\n\r\n\r\n \r\n \r\n\r\n\r\n","sub_path":"archivo.py","file_name":"archivo.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"514621770","text":"import sys\nfrom preDefine import defType\nfrom printTofile import printToFile\nfrom printTofile import printNumeric\ndef getMax(a, b):\n if a > b :\n return a\n else:\n return b\ndef getMin(a, b):\n if a < b:\n return a\n else:\n return b\ndef return0(a, b):\n return 0\nfunctionList = {\n 0 : getMax,\n 1 : return0,\n 2 : getMin\n}\nfunctionListForUnsign = {\n 1 : getMin,\n 0 : getMax,\n 2 : return0\n}\n\n#count = 0\ndef doJob():\n count = 0\n\n for sql_k, sql_v in defType.sql_type_max_min.items():\n for c_k, c_v in defType.sql_c_max_min.items():\n for i in range(3):\n print(count, end=',')\n count += 1\n outputData = functionList.get(i, return0)(sql_v[i], c_v[i])\n printToFile(c_k, sql_k, outputData, count, 0)\n\n for sql_k, sql_v in defType.sql_type_max_min_unsigned.items():\n for c_k, c_v in defType.sql_c_max_min.items():\n for i in range(2):\n print(count, end=',')\n count += 1\n outputData = functionListForUnsign.get(i, return0)(sql_v[i], c_v[i + 1])\n printToFile(c_k, sql_k, outputData, count, 1)\n\n num = 0\n for i in range(18):\n num = num * 10 + 9\n precision = i + 1\n count += 1\n print(count, end=',')\n printNumeric(precision, 0, 0, num, count)\n\n\ndef main():\n writeFileHead('testData.h')\n doJob()\n writeFileEnd('testData.h')\n\n\ndef writeFileHead(file):\n FileHeader = '''\\\n#ifndef __TESTDATA__\n#define __TESTDATA__\n#include\n#include\"table.h\"\nTESTDATA_TABLE TESTDATA_MAP[] = {\n '''\n with open(file, 'w') as f:\n f.write(\n FileHeader\n )\n\ndef writeFileEnd(file):\n FileEnd = '''\n};\n#endif\n '''\n with open(file, 'a') as f:\n f.write(\n FileEnd\n )\n\n\n\n\n\nif __name__=='__main__':\n main()\n\n\n\n# def printToFile(c_k, sql_k, outputData, count, isunsigned):\n# with open('testDataL.h', 'a') as f:\n# f.write(\n# '''{\n# %s//const char *sqlValue; ,\n# %s//const char *cValue; ,\n# %d//int CDataType; ,\n# %d//int CDataLen; ,\n# %d//int m_ODBCDataType; ,\n# %s//int m_SQLDataType; ,\n# %d//int m_SQLMaxLength; ,\n# %d//int m_DescUnsigned; ,\n# %d//int Precision; ,\n# %d//int Scale; ,\n# %d//int m_SQLCharset; ,\n# %d//int m_SQLDatetimeCode; ,\n# %d//int m_SQLOctetLength; ,\n# %d//char numeric_sign; /* 1=+ 0=- */ ,\n# %d//char numeric_value[SQL_MAX_NUMERIC_LEN]; ,\n# },\n# '''%(\n# str(outputData) ,\n# str(outputData) ,\n# defType.sql_c_type[c_k] ,\n# defType.sql_c_Len[c_k] ,\n# defType.sql_type[sql_k] ,\n# defType.sql_type_Datatype[sql_k],\n# defType.sql_type_len[sql_k] ,\n# isunsigned ,\n# 0 ,\n# 0 ,\n# 0 ,\n# 0 ,\n# 0 ,\n# 0 ,\n# 0)\n# )'''","sub_path":"pythonfile/createTestData.py","file_name":"createTestData.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"486937611","text":"from django.conf.urls import url\r\nfrom.import views\r\n\r\nurlpatterns = [\r\n # /welcome/\r\n url(r'^$',views.index, name='index'),\r\n#/welcome/index1\r\n url(r'^index1$',views.detail, name='index1'),\r\n\r\n url(r'^r1$', views.fr1, name='r1'),\r\n url(r'^r2$', views.fr2, name='r2'),\r\n url(r'^r3$', views.fr3, name='r3'),\r\n url(r'^r4$', views.fr4, name='r4'),\r\n url(r'^rr2$', views.frr2, name='rr2'),\r\n url(r'^rr3$', views.frr3, name='rr3'),\r\n url(r'^rr4$', views.frr4, name='rr4'),\r\n url(r'^rshow$', views.frshow, name='rshow'),\r\n url(r'^rshow2$', views.frshow2, name='rshow2'),\r\n url(r'^rshow3$', views.frshow3, name='rshow3'),\r\n url(r'^rr2.html' ,views.frr2, name='rr2')\r\n\r\n]\r\n","sub_path":"welcome/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"262089794","text":"# -*- coding: UTF-8 -*-\n\nimport pygame\n\n# Hilfsfunktion, um ein Bild zu laden:\ndef loadImage(filename, tiles, width, height, colorkey=None):\n #pygame.rect.Rect(0, 0, width, height)\n # Pygame das Bild laden lassen.\n images = []\n \n # Das Pixelformat der Surface an den Bildschirm (genauer: die screen-Surface) anpassen.\n # Dabei die passende Funktion verwenden, je nach dem, ob wir ein Bild mit Alpha-Kanal haben oder nicht.\n #print (filename)\n image=pygame.image.load(filename)\n if image.get_alpha() is None:\n #print(\"Alpha None\")\n image = image.convert()\n\n else:\n #print(\"Alpha!\")\n image = image.convert_alpha()\n\n # Colorkey des Bildes setzen, falls nicht None.\n # Bei -1 den Pixel im Bild an Position (0, 0) als Colorkey verwenden.\n #print(filename)\n \n if colorkey is not None:\n if colorkey == \"-1\":\n #print (\"-1\")\n colorkey = image.get_at((0,0))\n image.set_colorkey(colorkey, pygame.RLEACCEL)\n else:\n #print (colorkey)\n colorkey = colorkey.split(\",\")\n image.set_colorkey((int(colorkey[0]),int(colorkey[1]),int(colorkey[2])), pygame.RLEACCEL)\n \n for tile in range(tiles):\n #print (tile*tilesize,0,tilesize,tilesize)\n images.append (image.subsurface(tile*width,0,width,height))\n return images\n\ndef image_replace_color(surface,current_color,new_color):\n images = []\n current_color = current_color.split(\",\")\n for x in surface:\n image_pixel_array = pygame.PixelArray(x)\n image_pixel_array.replace((int(current_color[0]),int(current_color[1]),int(current_color[2])), new_color)\n pygame.pixelcopy.array_to_surface(x , image_pixel_array)\n return surface\n \ndef image_transform_scale (surfaces , scale):\n l = []\n for line in surfaces:\n if scale == 2:\n l.append(pygame.transform.scale2x (line))\n else: \n l.append(pygame.transform.rotozoom(line , 0 ,scale))\n return l\n \n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"355105647","text":"import os\nimport io\nimport pickle\nimport detectron2\nimport json\n# import some common detectron2 utilities\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nimport multiprocessing\n# import some common libraries\nimport numpy as np\nimport cv2\nimport torch\nfrom detectron2.model_zoo import model_zoo\nfrom detectron2.modeling.poolers import ROIPooler\n# Show the image in ipynb\nfrom detectron2.modeling.postprocessing import detector_postprocess\nfrom detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers, FastRCNNOutputs, fast_rcnn_inference_single_image\nimport pandas as pd\nimport glob\nfrom tqdm import tqdm\nfrom os import path\n\ndef process_feature_extraction(predictor, img, pred_thresh=0.5):#step 3\n '''\n #predictor.model.roi_heads.box_predictor.test_topk_per_image = 1000\n #predictor.model.roi_heads.box_predictor.test_nms_thresh = 0.99\n #predictor.model.roi_heads.box_predictor.test_score_thresh = 0.0\n #pred_boxes = [x.pred_boxes for x in instances]#can use prediction boxes\n '''\n torch.cuda.empty_cache()\n with torch.no_grad():#https://detectron2.readthedocs.io/_modules/detectron2/modeling/roi_heads/roi_heads.html : _forward_box()\n features = predictor.model.backbone(img.tensor)#have to unsqueeze\n proposals, _ = predictor.model.proposal_generator(img, features, None)\n results, _ = predictor.model.roi_heads(img, features, proposals, None)\n #instances = predictor.model.roi_heads._forward_box(features, proposals)\n #get proposed boxes + rois + features + predictions\n\n proposal_boxes = [x.proposal_boxes for x in proposals]\n proposal_rois = predictor.model.roi_heads.box_pooler([features[f] for f in predictor.model.roi_heads.in_features], proposal_boxes)\n box_features = predictor.model.roi_heads.box_head(proposal_rois)\n predictions = predictor.model.roi_heads.box_predictor(box_features)#found here: https://detectron2.readthedocs.io/_modules/detectron2/modeling/roi_heads/roi_heads.html\n #WE CAN USE THE PREDICTION CLS TO FIND TOP SCOREING PROPOSAL BOXES!\n #pred_instances, losses = predictor.model.roi_heads.box_predictor.inference(predictions, proposals)#something to do with: NMS threshold for prediction results. found: https://github.com/facebookresearch/detectron2/blob/master/detectron2/modeling/roi_heads/fast_rcnn.py#L460\n pred_df = pd.DataFrame(predictions[0].softmax(-1).tolist())\n pred_classes = pred_df.iloc[:,:-1].apply(np.argmax, axis=1)#get predicted classes\n keep = pred_df[pred_df.iloc[:,:-1].apply(lambda x: (x > pred_thresh)).values].index.tolist()#list of instances we should keep\n #start subsetting\n try:\n keep = keep[:NUM_OBJECTS]\n box_features = box_features[keep]\n except:\n return None\n # proposal_boxes = proposals[0].proposal_boxes[keep]\n # pred_classes = pred_classes[keep]\n # try:\n # probs = pred_df.iloc[keep, :].apply(lambda x: x[np.argmax(x)], axis=1).tolist()\n # except:\n # return None\n\n #['bbox', 'num_boxes', 'objects', 'image_width', 'image_height', 'cls_prob', 'image_id', 'features']\n #img.image_sizes[0]#h, w\n return box_features.to('cpu').detach().numpy()\n # result = {\n # 'bbox': proposal_boxes.tensor.to('cpu').numpy(),\n # 'num_boxes' : len(proposal_boxes),\n # 'objects' : pred_classes.to_numpy,\n # 'cls_prob': np.asarray(probs),#needs to turn into vector!!!!!!!!!!\n # 'features': box_features.to('cpu').detach().numpy()\n # }\n # return result\n\nif __name__ == '__main__':\n mode = 'train'\n batch_size = 80\n # images_path = f'/oscar_images/{mode}'\n images_path = f'/patent1'\n features_file_path = f'/patent1_img_feats.pt'\n NUM_OBJECTS = 50\n base_path = '/ocean/projects/tra190016p/ylix/dacon_old/dacon'\n saved_model_path = '/trained_models'\n num_gpu = 1\n model_name = \"model_final.pth\"\n NMS_THRESH = 0.6\n SCORE_THRESH = 0.4\n params = {'base_path': base_path, # NOTE: base path of the environment.\n 'min_points_threshold': 500, # NOTE: Minimum number of instances of an atom to be considered as a label. Atoms with less than this value are considered \"other\".\n 'n_sample_hard': 500000, \n 'n_sample_per_label': 50000, # NOTE: applies to both train and validation sets. Originally 20000\n 'overwrite': False, # NOTE: determines if we overwrite existing data.\n 'input_format': \"RGB\", # NOTE: Important to set depending on data format!\n 'n_jobs': multiprocessing.cpu_count() - 1,\n 'train_path': '/data/pubchem_smiles_2000000.csv',\n 'val_size': 4000,\n 'saved_model_path': saved_model_path,\n 'num_gpu': num_gpu\n }\n train_params = {'images_per_batch': batch_size,\n 'learning_rate': 0.005,\n 'maximum_iterations': 50000,\n 'checkpoint_save_interval': 10000,\n 'ROI_batch_per_image': 1024,\n 'evaluation_interval': 4000,\n 'num_workers': 8}\n \n unique_labels = json.load(open(base_path + f'/data/labels.json', 'r'))\n unique_labels['other'] = 0\n labels = list(unique_labels.keys())\n\n for mode in [\"train\", \"val\"]:\n dataset_name = f\"smilesdetect_{mode}\"\n if dataset_name in DatasetCatalog.list():\n DatasetCatalog.remove(dataset_name)\n \n DatasetCatalog.register(dataset_name, lambda mode=mode: pickle.load(open(base_path + f'/data/annotations_{mode}.pkl', 'rb')))\n MetadataCatalog.get(dataset_name).set(thing_classes=labels)\n \n cfg = get_cfg()\n cfg.merge_from_file(model_zoo.get_config_file(\n \"COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml\"))\n # Passing the Train and Validation sets\n cfg.DATASETS.TRAIN = (\"smilesdetect_train\",)\n cfg.DATASETS.TEST = (\"smilesdetect_val\",)\n cfg.OUTPUT_DIR = base_path + saved_model_path\n cfg.INPUT.FORMAT = params['input_format']\n # Number of data loading threads\n\n cfg.MODEL.ROI_HEADS.NUM_CLASSES = len(unique_labels)\n cfg.NUM_GPUS = num_gpu\n os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)\n cfg.SOLVER.IMS_PER_BATCH = train_params['images_per_batch']\n cfg.SOLVER.BASE_LR = train_params['learning_rate']\n cfg.SOLVER.MAX_ITER = train_params['maximum_iterations']\n cfg.SOLVER.CHECKPOINT_PERIOD = train_params['checkpoint_save_interval']\n cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = train_params['ROI_batch_per_image']\n cfg.TEST.EVAL_PERIOD = train_params['evaluation_interval']\n cfg.DATALOADER.NUM_WORKERS = train_params['num_workers']\n cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, model_name)\n cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST = NMS_THRESH\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = SCORE_THRESH\n predictor = DefaultPredictor(cfg)\n print(\"Model loaded.\")\n features_dict = {}\n\n images_paths = glob.glob(base_path + f'{images_path}/*.png')\n # extract_features(predictor, images_paths, features_dict)\n # torch.save(features_dict, features_file_path)\n\n # result = extract_features(predictor, [base_path + \"/data/images/test/rem.png\"], features_dict)\n # print(result[\"features\"])\n print(f\"Extracting features for {mode} dataset.\")\n\n for image_name in tqdm(images_paths):\n print(image_name)\n img = cv2.resize(cv2.imread(image_name), (300,300))[:, :, ::-1]\n img = torch.as_tensor(img.astype(\"float32\").transpose(2, 0, 1))\n image_example = [{\"image\": img, \"height\": img.shape[0], \"width\": img.shape[1]}]\n imageList = predictor.model.preprocess_image(image_example)\n #returns features and infos\n features = process_feature_extraction(predictor, imageList)\n if features is not None:\n features_dict[os.path.basename(image_name)] = features\n\n #assert features_dict.keys() == len(images_paths)\n print(f\"There are {len(features_dict.keys())} pictures generated\")\n torch.save(features_dict, base_path + features_file_path)\n","sub_path":"detectron2_extract.py","file_name":"detectron2_extract.py","file_ext":"py","file_size_in_byte":8418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"635813799","text":"#3.a\nfrom random import choice\n\nword = 'Idontwannadie'\nlst = list(word)\n\nfor i in range(len(word)):\n\n choice_char = choice(lst)\n lst.remove(choice_char) \n print(choice_char,' ',end='')\n\nprint()\nanswer = input('Your answer: ').lower()\n\nif answer == word.lower():\n print(\"Hura!\")\nelse:\n print(\":(\")","sub_path":"fundamentals/session_3/homework/serious/serious_3-a.py","file_name":"serious_3-a.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"485765519","text":"# -*- coding: utf-8 -*-\n\"\"\"\nElastic impedance.\n\n:copyright: 2015 Agile Geoscience\n:license: Apache 2.0\n\"\"\"\nimport numpy as np\n\n\ndef elastic_impedance(vp, vs, rho, theta1, normalize=True):\n \"\"\"\n Returns the elastic impedance (as defined by Connolly, 1999)\n for each incidence angle in theta1:\n\n :param vp1: The p-wave velocity or p-wave velocity array.\n :param vs1: The s-wave velocity of s-wave velocity array.\n :param rho1: The density (either scalar or array).\n :param theta1: An array of incident angles to use for reflectivity\n calculation [degrees].\n :param normalized: if True, returns the normalized form from\n Whitcombe et. al (2001).\n \"\"\"\n theta1 = np.radians(theta1)\n\n k = 0.25\n a = 1 + np.tan(theta1)**2\n b = -8 * k * np.sin(theta1)**2\n c = 1 - 4 * k * np.sin(theta1)**2\n\n ei = vp**a * vs**b * rho**c\n\n if normalize:\n n = vp**(1 - a) * vs**(-b) * rho**(1 - c)\n return n * ei\n else:\n return ei\n","sub_path":"bruges/rockphysics/elastic.py","file_name":"elastic.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"459544597","text":"import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nfrom skimage.draw import polygon\nimport PIL\nimport json\nimport base64\nimport os.path\nfrom os.path import splitext\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport re\nos.environ[\"KERAS_BACKEND\"] = \"plaidml.keras.backend\"\n#https://divamgupta.com/image-segmentation/2019/06/06/deep-learning-semantic-segmentation-keras.html\nfrom keras_segmentation.models.segnet import segnet\nfrom keras_segmentation.models.unet import unet\nfrom keras.models import model_from_json\nfrom keras.models import load_model, save_model\n\ncolors = {0 : (0,0,0), \n 1 : (0,0,255), \n 2 : (0,255,0),\n 3 : (255,0,0), \n 4 : (0,255,255), \n }\n\ndim = (256, 256) \n\npath = r'D:\\dev\\dcps\\AutonomesFahren\\data'\ndirimages = \"images_augmented\"\ndirmasks = \"masks_augmented\"\ndirmodels = \"models\"\n\ndirimagesvalid = \"images_valid\"\ndirmasksvalid = \"masks_valid\"\n\ndirimagestest = \"images_test\"\ndirmaskstest = \"masks_test\"\n\ndirpredictions = \"predictions\"\n\nfullpathimages = os.path.join(path, dirimages)\nfullpathmasks = os.path.join(path, dirmasks)\nfullpathpredictions = os.path.join(path, dirpredictions)\n\nfullpathimagesvalid = os.path.join(path, dirimagesvalid)\nfullpathmasksvalid = os.path.join(path, dirmasksvalid)\n\nfullpathimagestest = os.path.join(path, dirimagestest)\nfullpathmaskstest = os.path.join(path, dirmaskstest)\n\nprint(os.path.exists(fullpathimagesvalid))\nprint(os.path.exists(fullpathmasks))\nprint(os.path.exists(fullpathpredictions))\nprint(os.path.exists(os.path.join(path, dirmodels)))\n\nfrom keras.models import Model, load_model\nfrom keras.layers import Input, BatchNormalization, Activation, Dense, Dropout, Flatten, ZeroPadding2D, UpSampling2D\nfrom keras.layers.core import Lambda, RepeatVector, Reshape\nfrom keras.layers.convolutional import Conv2D, Conv2DTranspose\nfrom keras.layers.pooling import MaxPooling2D, GlobalMaxPool2D\nfrom keras.layers.merge import concatenate, add\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\n\ndef my_unet(classes):\n \n dropout = 0.4\n input_img = Input(shape=(dim[0], dim[1], 3))\n \n #contracting\n x = (ZeroPadding2D((1, 1)))(input_img)\n x = (Conv2D(64, (3, 3), padding='valid'))(x)\n x = (BatchNormalization())(x)\n x = (Activation('relu'))(x)\n x = (MaxPooling2D((2, 2)))(x)\n c0 = Dropout(dropout)(x)\n \n x = (ZeroPadding2D((1, 1)))(c0)\n x = (Conv2D(128, (3, 3),padding='valid'))(x)\n x = (BatchNormalization())(x)\n x = (Activation('relu'))(x)\n x = (MaxPooling2D((2, 2)))(x)\n c1 = Dropout(dropout)(x)\n\n x = (ZeroPadding2D((1, 1)))(c1)\n x = (Conv2D(256, (3, 3), padding='valid'))(x)\n x = (BatchNormalization())(x)\n x = (Activation('relu'))(x)\n x = (MaxPooling2D((2, 2)))(x)\n c2 = Dropout(dropout)(x)\n \n x = (ZeroPadding2D((1, 1)))(c2)\n x = (Conv2D(256, (3, 3), padding='valid'))(x)\n x = (BatchNormalization())(x)\n x = (Activation('relu'))(x)\n x = (MaxPooling2D((2, 2)))(x)\n c3 = Dropout(dropout)(x)\n \n x = (ZeroPadding2D((1, 1)))(c3)\n x = (Conv2D(512, (3, 3), padding='valid'))(x)\n c4 = (BatchNormalization())(x)\n\n x = (UpSampling2D((2, 2)))(c4)\n x = (concatenate([x, c2], axis=-1))\n x = Dropout(dropout)(x)\n x = (ZeroPadding2D((1, 1)))(x)\n x = (Conv2D(256, (3, 3), padding='valid', activation='relu'))(x)\n e4 = (BatchNormalization())(x)\n \n x = (UpSampling2D((2, 2)))(e4)\n x = (concatenate([x, c1], axis=-1))\n x = Dropout(dropout)(x)\n x = (ZeroPadding2D((1, 1)))(x)\n x = (Conv2D(256, (3, 3), padding='valid', activation='relu'))(x)\n e3 = (BatchNormalization())(x)\n \n x = (UpSampling2D((2, 2)))(e3)\n x = (concatenate([x, c0], axis=-1))\n x = Dropout(dropout)(x)\n x = (ZeroPadding2D((1, 1)))(x)\n x = (Conv2D(64, (3, 3), padding='valid', activation='relu'))(x)\n x = (BatchNormalization())(x)\n\n x = (UpSampling2D((2, 2)))(x)\n x = Conv2D(classes, (3, 3), padding='same')(x)\n \n x = (Activation('softmax'))(x)\n \n model = Model(input_img, x)\n \n return model\n\nmodel = my_unet(len(colors))\nmodel.compile(loss=\"categorical_crossentropy\",optimizer=\"adadelta\", metrics=['accuracy'])\n\ndef makecolormask(mask):\n ret_mask = np.zeros((mask.shape[0], mask.shape[1], len(colors)), 'uint8')\n \n for col in range(len(colors)):\n ret_mask[:, :, col] = (mask == col).astype(int)\n \n return ret_mask\n\nmodeljsonname=\"model-chkpt.json\"\nmodelweightname=\"model-chkpt.h5\"\n\ncallbacks = [\n EarlyStopping(patience=10, verbose=1),\n ReduceLROnPlateau(factor=0.1, patience=3, min_lr=0.00001, verbose=1),\n ModelCheckpoint(os.path.join(path, dirmodels,modelweightname), verbose=1, save_best_only=True, save_weights_only=True)\n]\n\ndef generatebatchdata(batchsize, fullpathimages, fullpathmasks):\n \n imagenames = os.listdir(fullpathimages)\n imagenames.sort()\n\n masknames = os.listdir(fullpathmasks)\n masknames.sort()\n\n assert(len(imagenames) == len(masknames))\n \n for i in range(len(imagenames)):\n assert(imagenames[i] == masknames[i])\n\n while True:\n batchstart = 0\n batchend = batchsize \n \n while batchstart < len(imagenames):\n \n imagelist = []\n masklist = []\n \n limit = min(batchend, len(imagenames))\n\n for i in range(batchstart, limit):\n if imagenames[i].endswith(\".png\"):\n imagelist.append(cv2.imread(os.path.join(fullpathimages,imagenames[i]),cv2.IMREAD_COLOR ))\n if masknames[i].endswith(\".png\"):\n masklist.append(makecolormask(cv2.imread(os.path.join(fullpathmasks,masknames[i]),cv2.IMREAD_UNCHANGED )))\n\n\n train_data = np.array(imagelist, dtype=np.float32)\n train_mask= np.array(masklist, dtype=np.float32)\n\n train_data /= 255.0\n \n yield (train_data,train_mask) \n\n batchstart += batchsize \n batchend += batchsize\n\ngenerator_train = generatebatchdata(2, fullpathimages, fullpathmasks)\ngenerator_valid = generatebatchdata(2, fullpathimagesvalid, fullpathmasksvalid)\n\nmodel.load_weights(os.path.join(path, dirmodels,\"model-chkpt.h5\"))\n\n#model.fit_generator(generator_train,steps_per_epoch=2500, epochs=10, callbacks=callbacks, validation_data=generator_valid, validation_steps=250)\n\nmodeljsonname=\"roadunet256-my-dropout-huge.json\"\nmodelweightname=\"roadunet256-my-dropout-huge.h5\"\n\nmodel_json = model.to_json()\nwith open(os.path.join(path, dirmodels,modeljsonname), \"w\") as json_file:\n json_file.write(model_json)\n\nmodel.save_weights(os.path.join(path, dirmodels,modelweightname))\n\"\"\"\n#model.load_weights(os.path.join(path, dirmodels,modelweightname))\n\nimagetestlist = []\n\nimagetestnames = os.listdir(fullpathimagestest)\nimagetestnames.sort()\n\nfor imagename in imagetestnames:\n if imagename.endswith(\".png\"):\n imagetestlist.append(cv2.imread(os.path.join(fullpathimagestest,imagename),cv2.IMREAD_COLOR ))\n \ntest_data = np.array(imagetestlist, dtype=np.float32)\ntest_data /= 255.0\n\npredictions_test = model.predict(test_data, batch_size=1, verbose=1)\n\ndef predictedmask(masklist):\n y_list = []\n for mask in masklist:\n assert mask.shape == (dim[0], dim[1], len(colors))\n imgret = np.zeros((dim[0], dim[1]), np.uint8)\n\n ##imgret = np.where(mask[:,:,:] == np.amax(mask[:,:,:]))\n #assert result < len(colors)\n #imgret = result[0][0]\n \n imgret = mask.argmax(axis=2)\n \n #print(imgret)\n \n y_list.append(imgret)\n \n return y_list\n\ndef makemask(mask):\n ret_mask = np.zeros((mask.shape[0], mask.shape[1], 3), 'uint8')\n\n for col in range(len(colors)):\n layer = mask[:, :] == col\n ret_mask[:, :, 0] += ((layer)*(colors[col][0])).astype('uint8')\n ret_mask[:, :, 1] += ((layer)*(colors[col][1])).astype('uint8')\n ret_mask[:, :, 2] += ((layer)*(colors[col][2])).astype('uint8')\n \n return ret_mask\n\nmymasks = predictedmask(predictions_test)\n\"\"\"","sub_path":"implementation/py/train_pics.py","file_name":"train_pics.py","file_ext":"py","file_size_in_byte":8283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"627150109","text":"import tflearn\nimport numpy as np\nfrom tflearn.data_utils import shuffle\nfrom tflearn.data_utils import *\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.estimator import regression\nfrom tflearn.data_preprocessing import ImagePreprocessing\nfrom tflearn.data_augmentation import ImageAugmentation\nimport pickle\nimport target_gen\nfrom PIL import Image\nfrom PIL import ImageEnhance\nfrom PIL import ImageFilter\nimport sys\nnp.set_printoptions(threshold=np.inf)\n# load dataset of auvsi targets\n# or generate them on demand here??\nnum_variations = 2\nnum_training_images = int(26*13)*num_variations\nnum_testing_images = 640\n#images = [None] * num_training_images\n#labels = [None] * num_training_images\nimages_test = [None] * num_testing_images\nlabels_test = [None] * num_testing_images\n\n\nletter_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n\nshape_list = ['Circle', 'Semicircle', 'Quartercircle', 'Triangle', 'Square', 'Rectangle', 'Trapezoid', 'Pentagon', 'Hexagon', 'Heptagon', 'Octagon', 'Star', 'Cross']\n\n\ncounter = 0\n'''\nfor q in range(0, num_variations):\n\tfor i in range(0, 26):\n\t\tfor a in range(0, 13):\n\t\t\ttmp_img, tmp_label = target_gen.generate_image(requested_letter=letter_list[i], \n\t\t\t\trequested_shape=shape_list[a], \n\t\t\t\t#requested_letter_color=\"White\", \n\t\t\t\t#requested_shape_color=\"Black\", \n\t\t\t\treturn_type = \"shape\")\n\t\t\n\t\t\t#for q in range(0, num_variations):\n\t\t\ttmp_img_2 = tmp_img\n\t\t\ttmp_img_2 = tmp_img_2.filter(ImageFilter.SMOOTH_MORE)\n\t\t\ttmp_img_2 = tmp_img_2.convert('L')\n\t\t\ttmp_img_2 = tmp_img_2.filter(ImageFilter.EDGE_ENHANCE_MORE)\n\t\t\timages[counter] = np.reshape(tmp_img_2.getdata(), (64, 64, -1))\n\t\t\tlabels[counter] = np.zeros(13)\n\t\t\tlabels[counter][tmp_label] = 1\n\t\t\t#print(str(labels[counter]))\n\t\t\tls_str = 'letter ' + letter_list[i]\n\t\t\tprint(ls_str + \", shape \" + shape_list[a] + ' variation ' + str(q))\n\n\t\t\tcounter += 1\n\t\t\t#if (q == 0 and i == 0):\n\t\t\t#\ttmp_img_2.show()\n'''\n\n# load images\ndataset_file = 'composites/shapes/'\n\nprint(\"loading image dataset\")\nx, labels = image_preloader(dataset_file, image_shape=(64, 64), mode='folder', categorical_labels=True, normalize=False)\n\nimages = [None] * len(x)\n\nfor i in range(0, len(x)):\n\ttemp = x[i]\n\timages[i] = np.uint8(temp) \n\timages[i] = Image.fromarray(images[i])\n\timages[i] = images[i].convert('L')\n\tenh_c = ImageEnhance.Contrast(images[i])\n\timages[i] = enh_c.enhance(12.0)\n\timages[i] = images[i].filter(ImageFilter.SMOOTH_MORE)\n\timages[i] = images[i].filter(ImageFilter.SMOOTH_MORE)\n\timages[i] = images[i].filter(ImageFilter.EDGE_ENHANCE_MORE)\n\timages[i] = images[i].filter(ImageFilter.SMOOTH_MORE)\n\timages[i] = images[i].filter(ImageFilter.EDGE_ENHANCE_MORE)\n\t#if i % 1000 == 0:\n\t\t#images[i].show()\n\ttmp_arr = np.fromstring(images[i].tobytes(), np.uint8)\n\timages[i] = tmp_arr.reshape(64,64,1)\t\n\t#images[i] = np.reshape(tmp_arr, (64, 64, -1))\n\n\nfor i in range(0, num_testing_images):\n\ttmp_img, tmp_label = target_gen.generate_image(return_type = \"shape\")\n\ttmp_img = tmp_img.convert('L')\n\tenh_c = ImageEnhance.Contrast(tmp_img)\n\ttmp_img = enh_c.enhance(12.0)\n\ttmp_img = tmp_img.filter(ImageFilter.SMOOTH_MORE)\n\ttmp_img = tmp_img.filter(ImageFilter.SMOOTH_MORE)\n\ttmp_img = tmp_img.filter(ImageFilter.EDGE_ENHANCE_MORE)\n\ttmp_img = tmp_img.filter(ImageFilter.SMOOTH_MORE)\n\ttmp_img = tmp_img.filter(ImageFilter.EDGE_ENHANCE_MORE)\n\t#if i == 1:\n\t\t#tmp_img.show()\n\ttmp_arr = np.fromstring(tmp_img.tobytes(), np.uint8)\n\timages_test[i] = tmp_arr.reshape(64,64,1)\n\tlabels_test[i] = np.zeros(13)\n\tlabels_test[i][tmp_label] = 1.\n\tsys.stdout.write(\"Generating image %d/%d\t \\r\" % (i, num_testing_images) )\n\tsys.stdout.flush()\nsys.stdout.write(\"Generating image %d/%d \\n\" % (i+1, num_testing_images) )\nsys.stdout.write(\"Finished generating images\\n\")\n\n# shuffle images\nprint(\"shuffling images\")\nimages, labels = shuffle(images, labels)\nimages_test, labels_test = shuffle(images_test, labels_test)\n\n# create preprocessor to normalize images\nprint(\"creating preprocessor\")\nimg_preprocessor = ImagePreprocessing()\nimg_preprocessor.add_featurewise_zero_center()\nimg_preprocessor.add_featurewise_stdnorm()\n\n# distort images\nprint(\"adding distortion\")\nimg_distortion = ImageAugmentation()\n\n# only flip left/right for shape training\nimg_distortion.add_random_flip_leftright()\nimg_distortion.add_random_blur(sigma_max=1.)\n\n\n\n###\n### network architecture\n###\nprint(\"setting up network\")\nnetwork = input_data(shape=[None, 64, 64, 1], \n\tdata_preprocessing=img_preprocessor,\n\tdata_augmentation=img_distortion)\n\n\n# convolution 2\nnetwork = conv_2d(network, 16, 5, activation='relu')\n# max pooling 2\nnetwork = max_pool_2d(network, 2)\n# convolution 2\nnetwork = conv_2d(network, 16, 5, activation='relu')\n# max pooling 2\nnetwork = max_pool_2d(network, 2)\n# convolution 2\nnetwork = conv_2d(network, 16, 5, activation='relu')\n# max pooling 2\nnetwork = max_pool_2d(network, 2)\n# fully-connected\nnetwork = fully_connected(network,128, activation='relu')\n# fully-connected\nnetwork = fully_connected(network,128, activation='relu')\n\n# dropout\nnetwork = dropout(network, 0.5)\n\n# fully-connected final\nnetwork = fully_connected(network, 13, activation='softmax')\n\n\nnetwork = regression(network, optimizer='adam', loss='categorical_crossentropy', learning_rate=0.0001)\n\n\nmodel = tflearn.DNN(network, tensorboard_verbose=2, checkpoint_path='/media/salvi/E4D81381D81350E2/checkpoints/shape_classifier.tfl.ckpt')\n\n# if previously trained model is available use that\nmodel.load('shape_classifier.tfl')\n\nmodel.fit(images, labels, n_epoch=50, shuffle=True, validation_set=(images_test, labels_test), show_metric=True, batch_size=128, snapshot_epoch=True, run_id='shape_classifier')\n\nmodel.save(\"shape_classifier.tfl\")\nprint(\"Network trained and saved as shape_classifier.tfl\")\n\n","sub_path":"AUVSI-SUAS_Competition_Code/image_classification/shape_trainer.py","file_name":"shape_trainer.py","file_ext":"py","file_size_in_byte":5889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"369989071","text":"\"\"\"This script scrapes the site www.bpmdatabase.com to search for songs and their\r\nrespective beats per minute. The user will enter an input which will be used to search\r\nfor the data.\r\nIve tested this script on my Windows, RasPi and Mac.\r\nMac and Linux apparently do not support lxml. But Windows can.\r\nFor Mac, I had to download pyOpenSSL to solve the sslv3 alert handshake failure.\r\nWindows had no issues.\r\n\"\"\"\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nsearchQuery = str(input('What do you want to search for: '))\r\n\r\nprint('Searching for \"%s\" in bmpdatabase...' %(searchQuery,))\r\nprint('------------------------')\r\n# to make a search query by editing the URL\r\nr = requests.get('https://www.bpmdatabase.com/music/search/', params={'q': searchQuery})\r\n\r\n# Do not get confused between content from requests and contenets from bs4\r\nsoup = BeautifulSoup(r.content)\r\n\r\nsongToScrapeBody = soup.find('tbody')\r\n# obtain a list of \r\n\r\nnumberOfResults = 0\r\n\r\ndef decor(func):\r\n def wrapper():\r\n print('======')\r\n print(func())\r\n print('======')\r\n\r\n return wrapper\r\n\r\n\r\nif songToScrapeBody:\r\n\r\n @decor\r\n def printNoOfResults ():\r\n return '%s results found.' %(numberOfResults,)\r\n\r\n print(\"URL being queried is: {0}\".format(r.url))\r\n\r\n listOfTr = songToScrapeBody.find_all(\"tr\")\r\n # we iterate through the list to get the individual elements.\r\n for eachTr in listOfTr:\r\n\t#for each tr element, we obtain a list of all the td elements inside it.\r\n listOfTd = eachTr.find_all(\"td\")\r\n artist = 'artist'\r\n song = 'song'\r\n bpm = 'bpm'\r\n # we iterate through the list of elements\r\n for eachTd in listOfTd:\r\n if eachTd.get('class') == ['artist']:\r\n artist = eachTd.contents[0].text\r\n elif eachTd.get('class') == ['title']:\r\n song = eachTd.text\r\n elif eachTd.get('class') == ['bpm']:\r\n bpm = eachTd.text\r\n print(\"{0} by {1} has a BPM of {2}\".format(song, artist, bpm))\r\n numberOfResults += 1\r\n printNoOfResults()\r\n\r\nelse:\r\n @decor\r\n def noResults():\r\n return \"Sorry. %s results found.\" % numberOfResults\r\n noResults()\r\n","sub_path":"Python/Web Harvesting/BPMParserWifSearch.py","file_name":"BPMParserWifSearch.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"53193630","text":"#!/usr/bin/env python3\n#\n# This file is part of the minifold project.\n# https://github.com/nokia/minifold\n\n__author__ = \"Marc-Olivier Buob\"\n__maintainer__ = \"Marc-Olivier Buob\"\n__email__ = \"marc-olivier.buob@nokia-bell-labs.com\"\n__copyright__ = \"Copyright (C) 2018, Nokia\"\n__license__ = \"BSD-3\"\n\nfrom html.parser import HTMLParser\nfrom html.entities import name2codepoint\n\nfrom minifold.entries_connector import EntriesConnector\n\nclass HtmlTableParser(HTMLParser):\n def __init__(self, columns :list, output_list :list, keep_entry = None):\n \"\"\"\n Constructor.\n Args:\n columns: list of string mapping the attribute name\n corresponding with the index. If data is fetch\n for columns having a greater index than\n len(columns), columns[-1] is used, and this\n key may store a list of string values instead\n of a single string. This allow to store data\n stored among several columns in a single attribute.\n output_list: reference to an output list where the\n data will be outputed (one dict per row, one\n key/value per column).\n keep_entry: callback which determine whether an\n must entry must be kept or discard. Pass None\n to filter nothing. This is the opportunity to\n discard a header or irrelevant row.\n \"\"\"\n HTMLParser.__init__(self)\n self.fetch_data = False\n self.columns = columns\n self.index = 0\n self.entries = output_list\n self.entry = dict()\n self.value = str()\n self.keep_entry = keep_entry\n\n def attributes(self, object :str) -> set:\n return set(self.columns)\n\n def handle_starttag(self, tag, attrs):\n if tag == \"td\":\n # Enable fetch data\n self.fetch_data = True\n\n def handle_endtag(self, tag):\n if tag == \"td\": # Push key/value\n # Disable fetch data\n self.fetch_data = False\n\n # Push new key/value pair\n key = self.columns[self.index] if self.index < len(self.columns) else self.columns[-1]\n if key in self.entry.keys():\n current_value = self.entry[key]\n if not isinstance(current_value, list):\n self.entry[key] = [current_value]\n if self.value:\n self.entry[key].append(self.value)\n else:\n if self.value:\n self.entry[key] = self.value\n\n # Reset key/value pair\n self.value = str()\n self.index += 1\n elif tag == \"tr\":\n # Push entry\n if self.keep_entry == None or self.keep_entry(self.entry):\n self.entries.append(self.entry)\n\n # Reset entry\n self.index = 0\n self.entry = dict()\n\n def handle_data(self, data):\n data = data.strip()\n if self.fetch_data == True and data:\n self.value += data\n\ndef html_table(filename :str, columns :list, keep_entry = None) -> list:\n entries = list()\n parser = HtmlTableParser(columns, self.m_entries, keep_entry)\n with open(filename, \"r\") as f:\n s = f.read()\n parser.feed(s)\n return entries\n\nclass HtmlTableConnector(EntriesConnector):\n def __init__(self, filename :str, columns :list, keep_entry = None):\n \"\"\"\n Constructor.\n Args:\n filename: Input HTML filename.\n columns: list of string mapping the attribute name\n corresponding with the index. If data is fetch\n for columns having a greater index than\n len(columns), columns[-1] is used, and this\n key may store a list of string values instead\n of a single string. This allow to store data\n stored among several columns in a single attribute.\n output_list: reference to an output list where the\n data will be outputed (one dict per row, one\n key/value per column).\n keep_entry: callback which determine whether an\n must entry must be kept or discard. Pass None\n to filter nothing. This is the opportunity to\n discard a header or irrelevant row.\n \"\"\"\n self.m_entries = list()\n self.m_parser = HtmlTableParser(columns, self.m_entries, keep_entry)\n with open(filename, \"r\") as f:\n s = f.read()\n self.m_parser.feed(s)\n super().__init__(self.m_entries)\n\n\n","sub_path":"src/html_table.py","file_name":"html_table.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"69862399","text":"#!/usr/bin/env python3\n\n# use for samtools or bcftoolfs pipelines\n\nimport sys\nimport gzip\n\nIN = sys.argv[1]\n\nif IN.endswith('gz'):\n f = gzip.open(IN, 'rt')\nelse:\n f = open(IN)\n\nwith f:\n print('CHR\\tPOS\\tDP\\tDP4_1\\tDP4_2\\tDP4_3\\tDP4_4\\tMAF')\n for line in f.readlines():\n line = line.strip()\n if line.startswith('#'):\n continue\n line = line.split('\\t')\n info = line[7].split(';')\n # skip INDELs\n if info[0] == 'INDEL':\n continue\n\n chr = line[0]\n pos = line[1]\n features = {}\n for item in info:\n if item.startswith('DP'):\n item = item.replace('=', ',')\n item = item.split(',')\n features[item[0]] = [int(x) for x in item[1:]]\n maf = (features['DP4'][0]+features['DP4'][1])/sum(features['DP4'])\n maf = 1 - maf if maf > 0.5 else maf\n print('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{:.4f}'.format(chr, pos,\n features['DP'][0],\n features['DP4'][0], features['DP4'][1], features['DP4'][2], features['DP4'][3],\n maf))\n","sub_path":"old/vcf_maf.samtools.py","file_name":"vcf_maf.samtools.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"204672781","text":"#!/usr/bin/python3\n\"\"\" Module that manipulates lists\n\"\"\"\n\n\nclass MyList(list):\n \"\"\" Class that inherits from list\n \"\"\"\n\n def print_sorted(self):\n \"\"\" Prints self sortedly, without modifying the\n original list\n \"\"\"\n\n new_list = self[:]\n new_list.sort()\n print(new_list)\n","sub_path":"0x0A-python-inheritance/1-my_list.py","file_name":"1-my_list.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"541717232","text":"import sys\nsys.path.append('./modules')\nimport httpclient, logging, errors, config_loader, operator as op, json\nimport LocationResponse as loc_res, WeatherResponse as wresp, DistanceResponse as dresp\nfrom flask import Flask, render_template, request\n\nFormat = '%(asctime)-15s:%(name)s:%(levelname)s--> %(message)s'\nlogging.basicConfig (format=Format, filename=\"weather-route-service.log\", level=\"INFO\", filemode=\"a\")\nlog = logging.getLogger(__name__)\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/weatherRoute',methods=['POST','GET'])\ndef main():\n \"\"\"\n This service is used for getting weather along your route.\n\n 1. Gets current location based on wifi.\n 2. Asks for destination e.g SanFrancisco\n 3. Gets weather for current and destination locations.\n 4. Calculates distance between origin and destination.\n 5. Based on how frequency or \n \"\"\"\n try:\n log.info(\"<--------------START----------------->\")\n #destination_city=input(\"Enter destination: \")\n destination_city=request.args.get('destination')\n log.info(\"Destination city is %s \" % destination_city)\n\n # Get current location\n log.info(\"Get current location's latitude and longitude.\")\n configLoader = config_loader.ConfigurationLoader()\n configLoader.set_configsection('Location')\n location = configLoader.getconfig()\n loc_url = location['location.url']\n log.debug(\"Location url: %s\" %loc_url)\n client = httpclient.HttpClient()\n client.set_url(loc_url)\n loc_resp= client.get_request()\n log.info('Location response: %s' % loc_resp)\n location_response = loc_res.LocationResponse()\n location_response.BuildMapping(loc_resp)\n c_loc_city = location_response._city\n c_loc_state = location_response._statecode\n \n #Get distance between current location and destination\n log.info(\"Invoking distance service.\")\n configLoader.set_configsection('Distance')\n distance = configLoader.getconfig()\n dis_url = distance['distance.url']\n log.debug(\"Distance url is %s \" % dis_url)\n places = c_loc_city+\",\"+c_loc_state+\"&\"+destination_city\n log.info(\"Places we need to get distance for is %s \" % places)\n client.set_url(dis_url+\"/\"+places)\n d_resp = client.get_request()\n log.info(\"Distance service response is: %s \" %d_resp)\n dist_resp = dresp.DistanceResponse()\n dist_resp.BuildMapping(d_resp)\n\n # Get Weather for current locaiton\n log.info(\"Get weather for current location.\")\n configLoader.set_configsection('Weather_API')\n weather = configLoader.getconfig()\n weather_url = weather['weather.host']+weather['weather.token']+weather['weather.query']+\"/\"+\\\n c_loc_state+\"/\"+c_loc_city+\".json\"\n log.debug(\"Weather url for current location is: %s \" % weather_url)\n client.set_url(weather_url)\n w_resp=client.get_request()\n log.info(\"Weather response: %s\" %w_resp)\n weather_resp=wresp.WeatherResponse()\n weather_resp.BuildMapping(w_resp)\n log.info(\"Weather for %s is %s \" %(c_loc_city,weather_resp._temperature_string))\n\n \n log.info(\"<--------------END----------------->\")\n return render_template('index.html',location_city=c_loc_city,\n origin=dist_resp._origin,destination=dist_resp._destination,\n distance=dist_resp._distance,duration=dist_resp._duration,\n location=weather_resp._city,temp_string=weather_resp._temperature_string,\n feels_like_string=weather_resp._feels_like_string,wind_speed=weather_resp._wind)\n except errors.Error as err:\n log.error(err.message,err.expression)\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"326732417","text":"from django.urls import path\n\nfrom .views import *\n\nurlpatterns = [\n path('', objects_list, name='objects_list_url'),\n path('object/create/', ObjectCreate.as_view(), name='object_create_url'),\n path('object//', ObjectDetail.as_view(), name='object_detail_url'),\n path('object//update/', ObjectUpdate.as_view(), name='object_update_url'),\n path('object//delete/', ObjectDelete.as_view(), name='object_delete_url'),\n path('tags/', tags_list, name='tags_list_url'),\n path('tag/create/', TagCreate.as_view(), name='tag_create_url'),\n path('tag//', TagDetail.as_view(), name='tag_detail_url'),\n path('tag//update/', TagUpdate.as_view(), name='tag_update_url'),\n]\n","sub_path":"objects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"130675192","text":"from machine import Pin\nimport utime\n\nsensor = Pin(16, Pin.IN, Pin.PULL_UP)\nwhile True:\n print(sensor.value())\n if sensor.value() == 0:\n print(\"The sensor found something\")\n else:\n print(\"The sensor did not find anything\")\n utime.sleep(1)\n","sub_path":"HW-511/HW-511-reader-debug.py","file_name":"HW-511-reader-debug.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"460001258","text":"import logging\nimport re\nimport sys\nimport traceback\nimport urllib.parse\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom threading import RLock\nfrom threading import Timer\n\nimport m3u8\nimport pytz\nimport requests\nimport tzlocal\n\nfrom .configuration import SmoothStreamsProxyConfiguration\nfrom .epg import SmoothStreamsProxyEpg\nfrom .password_manager import SmoothStreamsProxyPasswordManager\nfrom .shelf import SmoothStreamsProxyShelf\nfrom .utilities import SmoothStreamsProxyUtility\n\nlogger = logging.getLogger(__name__)\n\n\nclass SmoothStreamsProxy():\n _nimble_session_id_map = {}\n _nimble_session_id_map_lock = RLock()\n _refresh_session_timer = None\n _serviceable_clients = {}\n _serviceable_clients_lock = RLock()\n _session = {}\n _session_lock = RLock()\n\n @classmethod\n def _add_client_to_serviceable_clients(cls, client_uuid, client_ip_address):\n with cls._serviceable_clients_lock:\n cls._serviceable_clients[client_uuid] = {}\n cls._serviceable_clients[client_uuid]['ip_address'] = client_ip_address\n\n @classmethod\n def _clear_nimble_session_id_map(cls):\n with cls._nimble_session_id_map_lock:\n cls._nimble_session_id_map = {}\n\n @classmethod\n def _do_retrieve_authorization_hash(cls):\n try:\n if datetime.now(pytz.utc) < (cls._get_session_parameter('expires_on') - timedelta(minutes=30)):\n return False\n else:\n logger.info('Authorization hash\\n'\n 'Status => Expired\\n'\n 'Action => Retrieve it')\n\n return True\n except KeyError:\n logger.debug('Authorization hash\\n'\n 'Status => Never retrieved\\n'\n 'Action => Retrieve it')\n\n return True\n\n @classmethod\n def _get_session_parameter(cls, parameter_name):\n with cls._session_lock:\n return cls._session[parameter_name]\n\n @classmethod\n def _get_target_nimble_session_id(cls, hijacked_nimble_session_id):\n with cls._nimble_session_id_map_lock:\n return cls._nimble_session_id_map.get(hijacked_nimble_session_id, None)\n\n @classmethod\n def _hijack_nimble_session_id(cls, hijacked_nimble_session_id, hijacking_nimble_session_id):\n with cls._nimble_session_id_map_lock:\n cls._nimble_session_id_map[hijacked_nimble_session_id] = hijacking_nimble_session_id\n\n @classmethod\n def _process_authorization_hash(cls, hash_response):\n smooth_streams_proxy_session = {}\n\n if 'code' in hash_response:\n if hash_response['code'] == '0':\n logger.error('Failed to retrieved authorization token\\n'\n 'Error => {0}'.format(hash_response['error']))\n elif hash_response['code'] == '1':\n smooth_streams_proxy_session['hash'] = hash_response['hash']\n smooth_streams_proxy_session['expires_on'] = \\\n datetime.now(pytz.utc) + timedelta(seconds=(hash_response['valid'] * 60))\n\n logger.info('Retrieved authorization token\\n'\n 'Hash => {0}\\n'\n 'Expires On => {1}'.format(smooth_streams_proxy_session['hash'],\n smooth_streams_proxy_session['expires_on'].astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S')[:-3]))\n else:\n logger.error('Failed to retrieved authorization token\\n'\n 'Error => JSON response contains no [\\'code\\'] field')\n\n return smooth_streams_proxy_session\n\n @classmethod\n def _refresh_serviceable_clients(cls, client_uuid, client_ip_address):\n with cls._serviceable_clients_lock:\n if client_uuid not in cls._serviceable_clients:\n logger.debug('Adding client to serviceable clients\\n'\n 'Client IP address => {0}\\n'\n 'Client ID => {1}'.format(client_ip_address, client_uuid))\n\n cls._add_client_to_serviceable_clients(client_uuid, client_ip_address)\n else:\n cls._set_serviceable_client_parameter(client_uuid, 'last_request_date_time', datetime.now(pytz.utc))\n\n @classmethod\n def _retrieve_authorization_hash(cls):\n http_session = requests.Session()\n\n if SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVICE') == 'viewmmasr':\n url = 'https://www.mma-tv.net/loginForm.php'\n else:\n url = 'https://auth.smoothstreams.tv/hash_api.php'\n\n smooth_streams_username = SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_USERNAME')\n smooth_streams_password = SmoothStreamsProxyPasswordManager.decrypt_password(\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_PASSWORD')).decode()\n smooth_streams_site = SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVICE')\n\n logger.debug(\n 'Retrieving authorization hash\\n'\n 'URL => {0}\\n'\n ' Parameters\\n'\n ' username => {0}\\n'\n ' password => {1}\\n'\n ' site => {2}'.format(url,\n smooth_streams_username,\n smooth_streams_password,\n smooth_streams_site))\n\n response = SmoothStreamsProxyUtility.make_http_request(\n http_session.get,\n url,\n params={\n 'username': smooth_streams_username,\n 'password': smooth_streams_password,\n 'site': smooth_streams_site\n },\n headers=http_session.headers,\n cookies=http_session.cookies.get_dict())\n\n response_status_code = response.status_code\n if response_status_code != requests.codes.OK and response_status_code != requests.codes.NOT_FOUND:\n logger.error(SmoothStreamsProxyUtility.assemble_response_from_log_message(response))\n\n response.raise_for_status()\n\n # noinspection PyUnresolvedReferences\n logger.trace(SmoothStreamsProxyUtility.assemble_response_from_log_message(response,\n is_content_json=True,\n do_print_content=True))\n\n smooth_streams_proxy_session = cls._process_authorization_hash(response.json())\n\n if response_status_code != requests.codes.OK:\n response.raise_for_status()\n\n if smooth_streams_proxy_session:\n smooth_streams_proxy_session['http_session'] = http_session\n\n return smooth_streams_proxy_session\n\n @classmethod\n def _set_serviceable_client_parameter(cls, client_uuid, parameter_name, parameter_value):\n with cls._serviceable_clients_lock:\n cls._serviceable_clients[client_uuid][parameter_name] = parameter_value\n\n @classmethod\n def _set_session_parameter(cls, parameter_name, parameter_value):\n with cls._session_lock:\n cls._session[parameter_name] = parameter_value\n\n @classmethod\n def _timed_refresh_session(cls):\n logger.debug('Authorization hash refresh timer triggered')\n\n cls.refresh_session(force_refresh=True)\n\n @classmethod\n def cancel_refresh_session_timer(cls):\n if cls._refresh_session_timer:\n cls._refresh_session_timer.cancel()\n\n @classmethod\n def download_chunks_m3u8(cls,\n client_ip_address,\n requested_path,\n channel_number,\n client_uuid,\n nimble_session_id,\n token=None):\n cls._refresh_serviceable_clients(client_uuid, client_ip_address)\n\n smooth_streams_hash = cls._get_session_parameter('hash')\n smooth_streams_session = cls._get_session_parameter('http_session')\n\n target_url = 'https://{0}.smoothstreams.tv/{1}/ch{2}q1.stream{3}'.format(\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVER'),\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVICE'),\n channel_number,\n re.sub(r'(/.*)?(/.*\\.m3u8)', r'\\2', requested_path))\n\n logger.debug(\n 'Proxying request\\n'\n 'Source IP => {0}\\n'\n 'Requested path => {1}\\n'\n ' Parameters\\n'\n ' channel_number => {2}\\n'\n ' client_uuid => {3}\\n'\n 'Target path => {4}\\n'\n ' Parameters\\n'\n ' nimblesessionid => {5}\\n'\n ' wmsAuthSign => {6}'.format(\n client_ip_address,\n requested_path,\n channel_number,\n client_uuid,\n target_url,\n nimble_session_id,\n smooth_streams_hash))\n\n response = SmoothStreamsProxyUtility.make_http_request(smooth_streams_session.get,\n target_url,\n params={\n 'nimblesessionid': nimble_session_id,\n 'wmsAuthSign': smooth_streams_hash\n },\n headers=smooth_streams_session.headers,\n cookies=smooth_streams_session.cookies.get_dict())\n\n if response.status_code == requests.codes.OK:\n # noinspection PyUnresolvedReferences\n logger.trace(SmoothStreamsProxyUtility.assemble_response_from_log_message(response,\n is_content_text=True,\n do_print_content=True))\n\n return response.text.replace('.ts?', '.ts?channel_number={0}&client_uuid={1}&{2}'.format(\n channel_number,\n client_uuid,\n 'token={0}&'.format(token) if token else ''))\n else:\n logger.error(SmoothStreamsProxyUtility.assemble_response_from_log_message(response))\n\n response.raise_for_status()\n\n @classmethod\n def download_playlist_m3u8(cls,\n client_ip_address,\n requested_path,\n channel_number,\n client_uuid,\n protocol,\n token=None):\n cls._refresh_serviceable_clients(client_uuid, client_ip_address)\n cls.refresh_session()\n\n if protocol == 'hls':\n smooth_streams_hash = cls._get_session_parameter('hash')\n smooth_streams_session = cls._get_session_parameter('http_session')\n\n target_url = 'https://{0}.smoothstreams.tv/{1}/ch{2}q1.stream{3}'.format(\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVER'),\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVICE'),\n channel_number,\n re.sub(r'(/.*)?(/.*\\.m3u8)', r'\\2', requested_path))\n\n logger.debug(\n 'Proxying request\\n'\n 'Source IP => {0}\\n'\n 'Requested path => {1}\\n'\n ' Parameters\\n'\n ' channel_number => {2}\\n'\n ' client_uuid => {3}\\n'\n ' protocol => {4}\\n'\n 'Target path => {5}\\n'\n ' Parameters\\n'\n ' wmsAuthSign => {6}'.format(\n client_ip_address,\n requested_path,\n channel_number,\n client_uuid,\n protocol,\n target_url,\n smooth_streams_hash))\n\n response = SmoothStreamsProxyUtility.make_http_request(smooth_streams_session.get,\n target_url,\n params={\n 'wmsAuthSign': smooth_streams_hash\n },\n headers=smooth_streams_session.headers,\n cookies=smooth_streams_session.cookies.get_dict())\n\n if response.status_code == requests.codes.OK:\n # noinspection PyUnresolvedReferences\n logger.trace(SmoothStreamsProxyUtility.assemble_response_from_log_message(response,\n is_content_text=True,\n do_print_content=True))\n\n return response.text.replace('chunks.m3u8?',\n 'chunks.m3u8?channel_number={0}&client_uuid={1}&{2}'.format(\n channel_number,\n client_uuid,\n 'token={0}&'.format(token) if token else ''))\n else:\n logger.error(SmoothStreamsProxyUtility.assemble_response_from_log_message(response))\n\n response.raise_for_status()\n elif protocol == 'rtmp':\n smooth_streams_hash = cls._get_session_parameter('hash')\n\n return '#EXTM3U\\n' \\\n '#EXTINF:-1 ,{0}\\n' \\\n 'rtmp://{1}.smoothstreams.tv:3635/{2}/ch{3}q1.stream?' \\\n 'wmsAuthSign={4}'.format(SmoothStreamsProxyEpg.get_channel_name(int(channel_number)),\n SmoothStreamsProxyConfiguration.get_configuration_parameter(\n 'SMOOTH_STREAMS_SERVER'),\n SmoothStreamsProxyConfiguration.get_configuration_parameter(\n 'SMOOTH_STREAMS_SERVICE'),\n channel_number,\n smooth_streams_hash)\n\n @classmethod\n def download_ts_file(cls, client_ip_address, requested_path, channel_number, client_uuid, nimble_session_id):\n cls._refresh_serviceable_clients(client_uuid, client_ip_address)\n\n smooth_streams_hash = cls._get_session_parameter('hash')\n smooth_streams_session = cls._get_session_parameter('http_session')\n\n target_url = 'https://{0}.smoothstreams.tv/{1}/ch{2}q1.stream{3}'.format(\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVER'),\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVICE'),\n channel_number,\n re.sub(r'(/.*)?(/.*\\.ts)', r'\\2', requested_path))\n\n logger.debug(\n 'Proxying request\\n'\n 'Source IP => {0}\\n'\n 'Requested path => {1}\\n'\n ' Parameters\\n'\n ' channel_number => {2}\\n'\n ' client_uuid => {3}\\n'\n 'Target path => {4}\\n'\n ' Parameters\\n'\n ' nimblesessionid => {5}\\n'\n ' wmsAuthSign => {6}'.format(\n client_ip_address,\n requested_path,\n channel_number,\n client_uuid,\n target_url,\n nimble_session_id,\n smooth_streams_hash))\n\n response = SmoothStreamsProxyUtility.make_http_request(smooth_streams_session.get,\n target_url,\n params={\n 'nimblesessionid': nimble_session_id,\n 'wmsAuthSign': smooth_streams_hash\n },\n headers=smooth_streams_session.headers,\n cookies=smooth_streams_session.cookies.get_dict())\n\n if response.status_code == requests.codes.OK:\n # noinspection PyUnresolvedReferences\n logger.trace(SmoothStreamsProxyUtility.assemble_response_from_log_message(response,\n is_content_binary=True))\n\n return response.content\n else:\n logger.error(SmoothStreamsProxyUtility.assemble_response_from_log_message(response))\n\n response.raise_for_status()\n\n @classmethod\n def generate_channel_playlist_url(cls,\n is_server_secure,\n server_hostname,\n server_port,\n channel_number,\n client_uuid,\n protocol,\n token):\n return '{0}://{1}:{2}/live/playlist.m3u8?channel_number={3:02}&client_uuid={4}&protocol={5}{6}'.format(\n 'https' if is_server_secure else 'http',\n server_hostname,\n server_port,\n channel_number,\n client_uuid,\n protocol,\n '&token={0}'.format(token) if token else '')\n\n @classmethod\n def generate_live_playlist_m3u8(cls, is_server_secure, client_ip_address, client_uuid, protocol, type_, token):\n try:\n playlist_m3u8 = []\n\n client_ip_address_type = SmoothStreamsProxyUtility.determine_ip_address_type(client_ip_address)\n server_hostname = SmoothStreamsProxyConfiguration.get_configuration_parameter(\n 'SERVER_HOSTNAME_{0}'.format(client_ip_address_type.value))\n server_port = SmoothStreamsProxyConfiguration.get_configuration_parameter(\n 'SERVER_HTTP{0}_PORT'.format('S' if is_server_secure else ''))\n\n smooth_streams_hash = cls._get_session_parameter('hash')\n did_retrieve_fresh_smooth_streams_authorization_hash = False\n\n epg_channels = SmoothStreamsProxyEpg.get_channel_number_to_channel()\n for channel_number in sorted(epg_channels):\n epg_channel = epg_channels[channel_number]\n\n epg_channel_icon = epg_channel.icon_url.format(\n 's' if is_server_secure else '',\n server_hostname,\n server_port,\n '?token={0}'.format(token) if token else '').replace(' ', '%20')\n epg_channel_id = epg_channel.id\n epg_channel_name = epg_channel.name\n epg_channel_number = epg_channel.number\n\n playlist_m3u8.append(\n '#EXTINF:-1 group-title=\"{0}\" '\n 'tvg-id=\"{1}\" '\n 'tvg-name=\"{2}\" '\n 'tvg-logo=\"{3}\" '\n 'channel-id=\"{4}\",{2}\\n'.format(\n 'Live TV',\n epg_channel_id,\n epg_channel_name,\n epg_channel_icon,\n epg_channel_number))\n\n if type_ == 'dynamic':\n playlist_m3u8.append('{0}\\n'.format(cls.generate_channel_playlist_url(is_server_secure,\n server_hostname,\n server_port,\n epg_channel_number,\n client_uuid,\n protocol,\n token)))\n elif type_ == 'static':\n if not did_retrieve_fresh_smooth_streams_authorization_hash:\n try:\n smooth_streams_proxy_session = cls._retrieve_authorization_hash()\n smooth_streams_hash = smooth_streams_proxy_session['hash']\n except (KeyError, requests.exceptions.HTTPError):\n logger.error('Failed to retrieve fresh authorization token\\n'\n 'Falling back to main hash')\n\n did_retrieve_fresh_smooth_streams_authorization_hash = True\n\n playlist_m3u8.append(\n '{0}://{1}.smoothstreams.tv:{2}/{3}/ch{4:02}q1.stream?wmsAuthSign={5}\\n'.format(\n 'https' if protocol == 'hls' else 'rtmp',\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVER'),\n '443' if protocol == 'hls' else '3635',\n SmoothStreamsProxyConfiguration.get_configuration_parameter('SMOOTH_STREAMS_SERVICE'),\n epg_channel_number,\n smooth_streams_hash))\n\n playlist_m3u8 = '#EXTM3U x-tvg-url=\"{0}://{1}:{2}/live/epg.xml\"\\n{3}'.format(\n 'https' if is_server_secure else 'http',\n server_hostname,\n server_port,\n ''.join(playlist_m3u8))\n\n logger.debug('Generated live playlist.m3u8')\n\n return playlist_m3u8\n except (KeyError, ValueError):\n (type_, value_, traceback_) = sys.exc_info()\n logger.error('\\n'.join(traceback.format_exception(type_, value_, traceback_)))\n\n @classmethod\n def get_serviceable_client_parameter(cls, client_uuid, parameter_name):\n with cls._serviceable_clients_lock:\n return cls._serviceable_clients[client_uuid][parameter_name]\n\n @classmethod\n def initialize_from_shelf(cls):\n try:\n cls._session = SmoothStreamsProxyShelf.get_shelved_setting('session')\n except KeyError:\n pass\n\n @classmethod\n def map_nimble_session_id(cls,\n client_ip_address,\n channel_number,\n client_uuid,\n nimble_session_id,\n smooth_streams_hash):\n if smooth_streams_hash != cls._get_session_parameter('hash'):\n target_nimble_session_id = cls._get_target_nimble_session_id(nimble_session_id)\n\n if not target_nimble_session_id:\n logger.debug('Authorization hash {0} in request from {1}/{2} expired'.format(smooth_streams_hash,\n client_ip_address,\n client_uuid))\n\n try:\n response_text = cls.download_playlist_m3u8(client_ip_address,\n '/playlist.m3u8',\n channel_number,\n client_uuid,\n 'hls')\n\n m3u8_obj = m3u8.loads(response_text)\n\n requested_path_with_query_string = '/{0}'.format(m3u8_obj.data['playlists'][0]['uri'])\n requested_url_components = urllib.parse.urlparse(requested_path_with_query_string)\n requested_query_string_parameters = dict(urllib.parse.parse_qsl(requested_url_components.query))\n\n target_nimble_session_id = requested_query_string_parameters.get('nimblesessionid',\n nimble_session_id)\n\n logger.debug('Hijacking session\\n'\n 'Expired nimble session ID => {0}\\n'\n 'Target nimble session ID => {1}'.format(nimble_session_id, target_nimble_session_id))\n cls._hijack_nimble_session_id(nimble_session_id, target_nimble_session_id)\n except requests.exceptions.HTTPError:\n target_nimble_session_id = nimble_session_id\n\n (type_, value_, traceback_) = sys.exc_info()\n logger.error('\\n'.join(traceback.format_exception(type_, value_, traceback_)))\n else:\n target_nimble_session_id = nimble_session_id\n\n return target_nimble_session_id\n\n @classmethod\n def refresh_session(cls, force_refresh=False):\n with cls._session_lock:\n do_start_timer = False\n\n if force_refresh or cls._do_retrieve_authorization_hash():\n do_start_timer = True\n\n cls._clear_nimble_session_id_map()\n\n smooth_streams_proxy_session = cls._retrieve_authorization_hash()\n\n if smooth_streams_proxy_session:\n cls._session = smooth_streams_proxy_session\n SmoothStreamsProxyShelf.persist_to_shelf('session', cls._session)\n\n if cls._refresh_session_timer:\n cls._refresh_session_timer.cancel()\n elif not cls._refresh_session_timer:\n do_start_timer = True\n\n if do_start_timer:\n interval = (cls._get_session_parameter('expires_on') - datetime.now(pytz.utc)).total_seconds() - 1800\n cls._refresh_session_timer = Timer(interval, cls._timed_refresh_session)\n cls._refresh_session_timer.start()\n\n logger.debug('Starting authorization hash refresh timer\\n'\n 'Interval => {0} seconds'.format(interval))\n\n @classmethod\n def set_serviceable_client_parameter(cls, client_uuid, parameter_name, parameter_value):\n with cls._serviceable_clients_lock:\n cls._serviceable_clients[client_uuid][parameter_name] = parameter_value\n","sub_path":"smooth_streams_proxy/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":27176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"196327432","text":"# -*- coding:utf-8 -*-\r\n\r\n\"\"\"guba_stock_overview_spider\"\"\"\r\n\r\nimport re\r\nimport json\r\nfrom scrapy import log\r\nfrom scrapy.http import Request\r\nfrom scrapy.conf import settings\r\nfrom scrapy.spider import Spider\r\nfrom BeautifulSoup import BeautifulSoup\r\nfrom guba.items import GubaStocksItem\r\n\r\nHOST_URL = \"http://guba.eastmoney.com/\"\r\nOVERVIEW_URL = \"http://guba.eastmoney.com/remenba.aspx?type=1\"\r\n\r\n\r\nclass GubaStockOverviewSpider(Spider):\r\n \"\"\"usage: scrapy crawl guba_stock_overview_spider --loglevel=INFO\r\n \"\"\"\r\n name = 'guba_stock_overview_spider'\r\n\r\n def start_requests(self):\r\n request = Request(OVERVIEW_URL)\r\n yield request\r\n\r\n def parse(self, response):\r\n results = []\r\n resp = response.body\r\n soup = BeautifulSoup(resp)\r\n \r\n board_list = []\r\n ngbggul_ul = soup.find('ul', {'class': 'ngbggul'})\r\n\r\n if ngbggul_ul:\r\n for li in ngbggul_ul.findAll('li'):\r\n board_list.append(li.string)\r\n \r\n ngbggulbody_div = soup.find('div', {'class':'ngbggulbody'})\r\n if ngbggulbody_div:\r\n for idx, ngbglist_div in enumerate(ngbggulbody_div.findAll('div', {'class': 'ngbglistdiv'})):\r\n if idx >= 4:\r\n continue\r\n stock_type = board_list[idx]\r\n for a in ngbglist_div.findAll('a'):\r\n stock_url = a.get('href')\r\n if 'http://' not in stock_url:\r\n stock_url = HOST_URL + stock_url\r\n stock_id = re.search(r'\\,(.*?)\\.', stock_url).group(1)\r\n \r\n stock_name_list = a.string.split(')')\r\n\r\n if len(stock_name_list) == 2:\r\n stock_name = stock_name_list[1]\r\n else:\r\n stock_name = stock_name_list[0]\r\n\r\n stock_dict = {'stock_url': stock_url, 'stock_type': stock_type, \\\r\n 'stock_id': stock_id, 'stock_name': stock_name}\r\n \r\n item = GubaStocksItem()\r\n for key in GubaStocksItem.RESP_ITER_KEYS:\r\n item[key] = stock_dict[key]\r\n \r\n results.append(item)\r\n\r\n return results\r\n","sub_path":"guba/spiders/guba_stock_overview_spider.py","file_name":"guba_stock_overview_spider.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"144747781","text":"import movie_trailers\nimport media\n\n# Variable movies with its characteristics\ngoodfelas = media.Movie(\"GoodFelas\", \"1990\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/ca/thumb/1/15/G\\\n\t\t\t\t\t\t\t\t\t\t\t\toodfellas2.jpg/220px-Goodfellas2.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=RWZ78ICQcSk\")\n\nheat = media.Movie(\"Heat\", \"1995\",\n\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/6/6c/Heatposter.jp\\\n\t\t\t\t\t\t\t\t\tg\",\n\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=3UB16UIpgjI\")\n\ninside_job = media.Movie(\"Inside Job\", \"2010\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/a/a1/InsideJ\\\n\t\t\t\t\t\t\t\t\t\t\t\tob2010Poster.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=PH22Z91T2VA\")\n\nmatch_point = media.Movie(\"Match Point\", \"2005\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/0/0a/Match\\\n\t\t\t\t\t\t\t\t\t\t\t\t\tPointPoster.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=Nib7a7w8Yi0\")\n\npulp_fiction = media.Movie(\"Pulp Fiction\", \"1994\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/8/82/Pulp_\\\n\t\t\t\t\t\t\t\t\t\t\t\t\tFiction_cover.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=vzeec59Acnk\")\n\nreservoir_dogs = media.Movie(\"Reservoir Dogs\", \"1992\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/f/f6/Res\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tervoir_dogs_ver1.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=vayksn4Y93A\")\n\nschindlers_list = media.Movie(\"Schindler's List\", \"1993\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/3/38/S\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tchindler%27s_List_movie.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=JdRGC-w9syA\")\n\nse7en = media.Movie(\"Se7en\", \"1995\",\n\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/thumb/6/68/Seven\\\n\t\t\t\t\t\t\t\t\t\t_%28movie%29_poster.jpg/220px-Seven_%28movie%29_poster.jpg\",\n\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=znmZoVkCjpI\")\n\nthe_matrix = media.Movie(\"The Matrix\", \"1999\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/c/c1/The_Mat\\\n\t\t\t\t\t\t\t\t\t\t\t\trix_Poster.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=ItH3RpObRHQ\")\n\nthe_godfather = media.Movie(\"The Godfather\", \"1972\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/1/1c/God\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfather_ver1.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=YYKxj8qiLTg\")\n\nthe_shawshank = media.Movie(\"The Shawshank Redemption\", \"1994\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/8/81/ShawshankRedemptionMoviePoster.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=TaYNFrecwpQ\")\n\nthe_sting = media.Movie(\"The Sting\", \"1973\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"https://upload.wikimedia.org/wikipedia/en/9/9c/Stingre\\\n\t\t\t\t\t\t\t\t\t\t\t\tdfordnewman.jpg\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"https://www.youtube.com/watch?v=LN2hBOIXhBs\")\n\n# List of all movies\nmovies = [goodfelas, heat, inside_job, match_point, pulp_fiction,\n\t\t\t\t\treservoir_dogs,\tschindlers_list, se7en, the_matrix, the_godfather,\n\t\t\t\t\tthe_shawshank, the_sting]\n\n# Generate the html code with the movies list\nmovie_trailers.open_movies_page(movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"579967197","text":"from collections import deque\nfrom typing import List\n\nfrom leetcode.utils.tree_node import TreeNode\n\n\nclass Solution:\n def binaryTreePaths(self, root: TreeNode) -> List[str]:\n if root is None:\n return []\n result = []\n queue = deque()\n queue.append((root, f'{root.val}'))\n while queue:\n node, path = queue.popleft()\n if node.left is None and node.right is None:\n result.append(path)\n continue\n if node.left is not None:\n queue.append((node.left, f'{path}->{node.left.val}'))\n if node.right is not None:\n queue.append((node.right, f'{path}->{node.right.val}'))\n return result\n\n","sub_path":"leetcode/solutions/problem_0257.py","file_name":"problem_0257.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"174884768","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# nezoter.py,\n# Érettségi feladat: 2014. október, Nézőtér\n# Feladatkiírások: http://www.oktatas.hu/kozneveles/erettsegi/feladatsorok\n# Program: Koós Antal, 2016\n\n# --- 1. feladat ---\n# print(\"\\n1. feladat\")\n# Így tároljuk az adatokat:\n# nézőtér=[ sor1,sor2,... ]; sor=[ szék1,szék2,...]; szék=[foglaltság,kategória]\nnézőtér = []\nwith open(\"foglaltsag.txt\") as ffog, open(\"kategoria.txt\") as fkat:\n for fog_sor in ffog:\n fog_sor = fog_sor.strip()\n kat_sor = next(fkat).strip()\n nézőtér.append([[fog_sor[i], kat_sor[i]] for i in range(len(fog_sor))])\n\n# for sor in nézőtér:\n# print(sor)\n\n# --- 2. feladat ---\nprint(\"\\n2. feladat\")\nmegadott_sor = int(input(\"Adja meg egy sor számát! \"))\nmegadott_szék = int(input(\"Adja meg egy szék számát! \"))\n\nszék = nézőtér[megadott_sor - 1][megadott_szék - 1]\nprint(\"{}. sor {}. szék: {}\".format(megadott_sor, megadott_szék, \"foglalt\" if szék[0] == \"x\" else \"szabad\"))\n\n# --- 3. feladat ---\nprint(\"\\n3. feladat\")\nszékek_száma = 0\nfoglaltak = 0\nfor sor in nézőtér:\n székek_száma += len(sor)\n for szék in sor:\n if szék[0] == \"x\":\n foglaltak += 1\n\nprint(\"Az előadásra eddig {} jegyet adtak el, ez a nézőtér {}%-a.\".format(foglaltak,\n round(foglaltak / székek_száma * 100)))\n\n# --- 4. feladat ---\nprint(\"\\n4. feladat\")\nkatstat = dict() # {kategória:darab} statisztika az eladott jegyek kategóriáira\nfor sor in nézőtér:\n for szék in sor:\n if szék[0] == \"x\":\n kategória = szék[1]\n katstat[kategória] = katstat.get(kategória, 0) + 1\n\nlegtöbb = max(katstat.values())\nfor kategória, darab in katstat.items(): # több kategóriában is eladhattak ugyanolyan sok jegyet\n if darab == legtöbb:\n print(\"A legtöbb jegyet a(z) {}. árkategóriában értékesítették.\".format(kategória))\n\n# --- 5. feladat ---\nprint(\"\\n5. feladat\")\nárak = (5000, 4000, 3000, 2000, 1500)\nbevétel = 0\nfor kategória, darab in katstat.items():\n bevétel += árak[int(kategória) - 1] * darab\n\nprint(\"A színház bevétele:\", bevétel, \"Ft\")\n\n# --- 6. feladat ---\nprint(\"\\n6. feladat\")\negyedüliek = 0\n\nfor sor in nézőtér:\n üres_szakasz = 0\n for szék in sor:\n if szék[0] == \"o\":\n üres_szakasz += 1\n else: # \"x\": lezárja az üresek sorozatát\n if üres_szakasz == 1:\n egyedüliek += 1\n üres_szakasz = 0\n if üres_szakasz == 1: # a sor végén is vizsgálni kell\n egyedüliek += 1\n\nprint(\"Az egyedülálló helyek száma:\", egyedüliek)\n\n# --- 7. feladat ---\n# print(\"\\n7. feladat\")\nwith open(\"szabad.txt\", \"w\") as ff:\n for sor in nézőtér:\n for szék in sor:\n ff.write(szék[1] if szék[0] == \"o\" else \"x\")\n ff.write(\"\\n\")\n\n# ---------------------------------------------------------------------------\n# További feladatok: http://sites.google.com/site/eutlantis/erettsegi\n# Ajánlott olvasmány: www.interkonyv.hu/konyvek/koos_antal_python_a_gepben\n","sub_path":"14nezoter/nezoter.py","file_name":"nezoter.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"626198014","text":"#!/usr/bin/env python\nimport signal\nimport subprocess\nimport sys\nimport time\nfrom subprocess import check_output\n\n\ndef find_stream(currentStream):\n \"\"\"Return data to find proper stream to watch.\"\"\"\n liveList = subprocess.Popen(\n ['/bin/sh', 'live.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, err = liveList.communicate()\n output = output.strip().splitlines()\n\n rankedDictionary = {}\n rank = 1\n try:\n with open('rankedstreams.txt') as f:\n for line in f:\n key = line.strip()\n if key[0] == \"#\":\n continue\n rankedDictionary[key] = [rank, 0]\n rank += 1\n except Exception as ex:\n print(ex)\n\n for line in output:\n if line.split()[0] in rankedDictionary:\n rankedDictionary[line.split()[0]][1] = 1\n\n streamChoice = rank\n for key in rankedDictionary:\n if(rankedDictionary[key][1] == 1 and rankedDictionary[key][0] < streamChoice):\n streamChoice = rankedDictionary[key][0]\n for key in rankedDictionary:\n if(rankedDictionary[key][0] == streamChoice):\n streamChoiceName = key\n break\n return rankedDictionary, streamChoice, streamChoiceName, output\n\n\ndef get_pid(name):\n \"\"\"Return pid of window name.\"\"\"\n return map(int, check_output([\"pidof\", name]).split())\n\n\ndef signal_handler(sig, frame):\n \"\"\"Signal handler.\"\"\"\n try:\n videoprocess.kill()\n chatprocess.kill()\n except Exception as ex:\n print(\"Video process and/or chat process could not be killed, already \"\n \"dead?\")\n\n print(\"Stream viewer exited\")\n sys.exit()\n\n\ndef open_videowindow(streamChoiceName, chatMode):\n \"\"\"Open video window.\"\"\"\n if chatMode == \"chat\":\n videoprocess = subprocess.Popen(['streamlink', '--player', 'omxplayer '\n '--win 0,0,1400,1080 --aspect-mode letterbox --timeout 20 '\n '--audio_queue 10 --video_queue 10', '--player-fifo',\n '--hls-segment-threads', '3', '--stream-sorting-excludes', '>=1080p',\n 'twitch.tv/%s' % streamChoiceName, 'best'], stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n else:\n videoprocess = subprocess.Popen(['streamlink', '--player', 'omxplayer '\n '--win 0,0,1920,1080 --aspect-mode letterbox --timeout 20 '\n '--audio_queue 10 --video_queue 10', '--player-fifo',\n '--hls-segment-threads', '3', '--stream-sorting-excludes', '>=1080p',\n 'twitch.tv/%s' % streamChoiceName, 'best'], stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n return videoprocess\n\n\ndef open_chatwindow(streamChoiceName):\n \"\"\"Open chat window.\"\"\"\n windowMade = False\n while not windowMade:\n start_time = time.time()\n chatprocess = subprocess.Popen(['java', '-jar', './Chatty.jar',\n '-channel', streamChoiceName, '-single', '-connect'],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n windowFound = False\n while not windowFound:\n chatWindowProcess = subprocess.Popen(['xdotool', 'search',\n '--onlyvisible', '--name', streamChoiceName],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, err = chatWindowProcess.communicate()\n try:\n chatWID = output.strip().splitlines()[0]\n except IndexError:\n if time.time() - start_time >= 30:\n break\n else:\n continue\n windowFound = True\n windowMade = True\n\n chatWindowProcess = subprocess.Popen(['xdotool', 'windowactivate', chatWID],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, err = chatWindowProcess.communicate()\n chatWindowProcess = subprocess.Popen(['xdotool', 'key', 'F10'],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, err = chatWindowProcess.communicate()\n chatWindowProcess = subprocess.Popen(['xdotool', 'key', 'shift+F10'],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, err = chatWindowProcess.communicate()\n chatWindowProcess = subprocess.Popen(['xdotool', 'windowsize', chatWID, '472',\n '966'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, err = chatWindowProcess.communicate()\n chatWindowProcess = subprocess.Popen(['xdotool', 'windowmove', chatWID,\n '1351', '17'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n return chatprocess, chatWindowProcess\n\n\nsignal.signal(signal.SIGINT, signal_handler)\n\n\ndef main():\n \"\"\"Find and display a stream to the user.\"\"\"\n currentStream = None\n try:\n sys.argv[1]\n except (NameError, IndexError):\n chatMode = \"chat\"\n else:\n if sys.argv[1] == \"--no_chat\":\n chatMode = \"nochat\"\n else:\n print(\"Usage: \" + sys.argv[0] + \" [--no_chat]\")\n exit(1)\n while True:\n rankedDictionary, streamChoice, streamChoiceName, output = find_stream(\n currentStream)\n\n if currentStream is None:\n videoprocess = open_videowindow(streamChoiceName, chatMode)\n if chatMode == \"chat\":\n chatprocess, chatWindowProcess = open_chatwindow(\n streamChoiceName)\n currentStream = streamChoiceName\n\n elif currentStream is not None and not any(currentStream in line for line\n in output):\n videoprocess.kill()\n if chatMode == \"chat\":\n chatprocess.kill()\n currentStream = None\n\n elif rankedDictionary[currentStream][0] > rankedDictionary[streamChoiceName][0]:\n videoprocess.kill()\n if chatMode == \"chat\":\n chatprocess.kill()\n videoprocess = open_videowindow(streamChoiceName, chatMode)\n if chatMode == \"chat\":\n chatprocess, chatWindowProcess = open_chatwindow(\n streamChoiceName)\n\n time.sleep(30)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"raspberry-stream.py","file_name":"raspberry-stream.py","file_ext":"py","file_size_in_byte":6689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"485046053","text":"# 最大的矩形 100分\ndef st201312_3():\n n = int(input())\n nums = list(map(int, input().split()))\n # n=6\n # nums=[3, 1, 6, 5, 2, 3]\n result=[]\n for i in range(n):\n high=nums[i]\n temp = 0\n for a in range(i,-1,-1):\n if nums[a]>=high:\n temp+=1\n else:\n break\n for a in range(i,n):\n if nums[a]>=high:\n temp+=1\n else:\n break\n result.append(temp*high-high)\n # print(result)\n print(max(result))\n\nif __name__ == '__main__':\n st201312_3()","sub_path":"st201312-3.py","file_name":"st201312-3.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"261671181","text":"import random\n\nimport requests\nfrom django.core.cache import cache\n\nfrom common import keys\nfrom swiper import config\nfrom worker import celery_app # 异步任务\n\n# 随机生成验证码\ndef gen_vcode(size=4): # size :多长\n '''1000-9999'''\n start = 10 ** (size - 1)\n stop = 10 ** size - 1\n vcode = random.randint(start, stop)\n return vcode\n\n\n# 发送验证码,去请求官方接口\n@celery_app.task\ndef send_vcode(phone):\n params = config.YZX_PARAMS.copy() # copy 不改变原配置参数\n params['mobile'] = phone\n vcode = gen_vcode()\n params['param'] = vcode\n\n # 生成的验证码存入缓存 过期时间600s (可以保存每个异步任务请求生成的验证码)\n cache.set(keys.VCODE_KEY % phone, str(vcode), timeout=600)\n resp = requests.post(config.YZX_URL, json=params)\n if resp.status_code == 200: # http请求是否成功\n # ok\n result = resp.json() # 接收云之讯返回的json数据转字典\n if result['code'] == '000000':\n return 'OK'\n else:\n return result['msg']\n else:\n return '发送短信有误'","sub_path":"swiper/lib/sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"82398296","text":"import requests\nimport threading\nimport parsel\nimport random\nimport time\n\n# UA池\nuser_agents = [\n\t\t'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60',\n\t\t'Opera/8.0 (Windows NT 5.1; U; en)',\n\t\t'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',\n\t\t'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50',\n\t\t'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',\n\t\t'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10',\n\t\t'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2 ',\n\t\t'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',\n\t\t'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n\t\t'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',\n\t\t'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36',\n\t\t'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',\n\t\t'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',\n\t\t'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',\n\t\t'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',\n\t\t'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0',\n\t\t'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0) ',\n\t]\n\n# 写入所有代理\nproxyList = open('proxy.txt')\n# 写入可用代理ip\nvalidList= open('valid.txt')\n\n# 控制线程\nlock = threading.Lock()\n\ndef getProxy():\n starttime = time.time()\n # 爬取云代理ip\n # http://www.ip3366.net/free\n getCloudProxy()\n\n # 爬取98代理\n # https: // www.89ip.cn / index_10.html\n get89Proxy()\n\n # 爬取快代理\n # https://www.kuaidaili.com/free/inha/1/\n # https://www.kuaidaili.com/free/intr/1/\n getQuickProxy()\n\n endtime = time.time()\n print(f\"爬取代理花费{endtime-starttime}s\")\n\ndef getCloudProxy():\n print(\"爬取云代理IP中--------\")\n num = 0\n import time\n # 打开我们创建的txt文件\n proxyFile = open('proxy.txt', 'a')\n for page in range(1, 8):\n for stype in range(1, 3):\n time.sleep(random.randint(1, 3))\n print(f\"正在抓取{stype}的第{page}页数据\")\n # 数据地址\n url = f'http://www.ip3366.net/free/?stype={stype}&page={page}'\n # 设置随机请求头\n headers = {\n 'User-Agent': random.choice(user_agents)}\n # 发送请求\n response = requests.get(url=url, headers=headers)\n # 自适应编码\n response.encoding = response.apparent_encoding\n html_data = response.text\n # 解析数据\n selector = parsel.Selector(html_data)\n trs = selector.xpath('//table/tbody/tr')\n for tr in trs:\n ip = tr.xpath('./td[1]/text()').get() # ip\n port = tr.xpath('./td[2]/text()').get() # 端口\n protocol = tr.xpath('./td[4]/text()').get() # 协议\n\n # 将获取到的数据按照规定格式写入txt文本中1\n proxyFile.write('%s|%s|%s\\n' % (ip, port, protocol))\n num += 1\n print(f\"爬取云代理IP{num}条\")\n\ndef getQuickProxy():\n print(\"爬取快代理中------\")\n num = 0\n import time\n # 打开我们创建的txt文件\n proxyFile = open('proxy.txt', 'a')\n for page in range(1, 3):\n for type in ['inha', 'intr']:\n\n time.sleep(random.randint(1, 3))\n print(f\"正在抓取类型{type}第{page}页数据\")\n # 数据地址\n url = f'https://www.kuaidaili.com/free/{type}/{page}/'\n # 设置随机请求头\n headers = {\n 'User-Agent': random.choice(user_agents)\n }\n # 发送请求\n response = requests.get(url=url, headers=headers)\n # 自适应编码\n response.encoding = response.apparent_encoding\n html_data = response.text\n # 解析数据\n selector = parsel.Selector(html_data)\n trs = selector.xpath('//table/tbody/tr')\n for tr in trs:\n ip = tr.xpath('./td[1]/text()').get().strip() # ip\n port = tr.xpath('./td[2]/text()').get().strip() # 端口\n protocol = tr.xpath('./td[4]/text()').get().strip() #协议\n # 将获取到的数据按照规定格式写入txt文本中1\n proxyFile.write('%s|%s|%s\\n' % (ip, port, protocol))\n num += 1\n print(f\"爬取快代理IP{num}条\")\n\n\ndef get89Proxy():\n print(\"爬取89代理IP中--------\")\n num = 0\n import time\n # 打开我们创建的txt文件\n proxyFile = open('proxy.txt', 'a')\n for page in range(1, 156):\n time.sleep(random.randint(1, 3))\n print(f\"正在抓取第{page}页数据\")\n # 数据地址\n url = f'https://www.89ip.cn/index_{page}.html'\n # 设置随机请求头\n headers = {\n 'User-Agent': random.choice(user_agents)\n }\n # 发送请求\n response = requests.get(url=url, headers=headers)\n # 自适应编码\n response.encoding = response.apparent_encoding\n html_data = response.text\n # 解析数据\n selector = parsel.Selector(html_data)\n trs = selector.xpath('//table/tbody/tr')\n for tr in trs:\n ip = tr.xpath('./td[1]/text()').get().strip() # ip\n port = tr.xpath('./td[2]/text()').get().strip() # 端口\n protocol = 'HTTP' # 默认协议HTTP\n # 将获取到的数据按照规定格式写入txt文本中1\n proxyFile.write('%s|%s|%s\\n' % (ip, port, protocol))\n num += 1\n print(f\"爬取89代理IP{num}条\")\ndef verifyProxyList():\n '''\n 验证ip有效性并存入valid.txt\n :return:\n '''\n\n valid = open('valid.txt', 'a')\n while True:\n lock.acquire()\n # 读取存放ip的文件\n ipinfo = proxyList.readline().strip()\n lock.release()\n # 读到最后一行\n if len(ipinfo) == 0:\n break\n line = ipinfo.strip().split('|')\n ip = line[0]\n port = line[1]\n realip = ip + ':' + port\n # print(realip)\n # 得到验证码\n code = verifyProxy(realip)\n # 验证通过\n if code == 200:\n lock.acquire()\n print(\"---Success:\" + ip + \":\" + port)\n valid.write(ipinfo + \"\\n\")\n lock.release()\n else:\n pass\n # print(\"---Failure:\" + ip + \":\" + port)\ndef verifyProxy(ip):\n '''\n 验证代理的有效性\n '''\n # 设置随机请求头\n headers = {\n 'User-Agent': random.choice(user_agents)\n }\n url = \"http://www.baidu.com\"\n # 填写代理地址\n proxy = {'http': ip}\n try:\n code = requests.get(url=url, proxies=proxy, timeout=2, headers = headers).status_code\n print(code)\n return code\n except Exception as e:\n return e\n\n\ndef useProxy():\n lock.acquire()\n\n ips = []\n # 获取可用ip池\n # 获取IP列表\n valid = open('/Users/shangyuhu/PycharmProjects/recruitProject/ProxyIP/valid.txt')\n while True:\n # 读取存放ip的文件\n ipinfo = valid.readline().strip()\n # 读到最后一行\n if len(ipinfo) == 0:\n break\n line = ipinfo.strip().split('|')\n ip = line[0]\n port = line[1]\n realip = ip + ':' + port\n ips.append(realip)\n print(ips)\n # 要抓取的目标网站地址\n targetUrl = \"https://news.qq.com/\"\n for i in range(10):\n # 随机使用ip爬虫\n proxyip = random.choice(ips)\n # print(proxyip)\n try:\n response = requests.get(url=targetUrl, proxies={\"http\": proxyip, \"https\": proxyip},\n verify=False, timeout=15)\n except Exception as e:\n continue\n # 自适应编码\n response.encoding = response.apparent_encoding\n html_data = response.text\n print(html_data)\n # 用完了\n lock.release()\n\n\nif __name__ == '__main__':\n # 清空代理列表和有效代理列表\n proxy = open('proxy.txt', 'w')\n proxy.write(\"\")\n proxy.close()\n valid = open('valid.txt', 'w')\n valid.write(\"\")\n valid.close()\n # 获取代理IP\n getProxy()\n\n starttime = time.time()\n # 验证ip有效性\n all_thread = []\n for i in range(30):\n t = threading.Thread(target=verifyProxyList)\n all_thread.append(t)\n t.start()\n\n for t in all_thread:\n t.join()\n\n endtime = time.time()\n print(f\"验证代理IP花费时间{endtime-starttime}s\")\n\n useProxy()\n proxy.close()\n valid.close()\n","sub_path":"getProxyIP/getProxyIP.py","file_name":"getProxyIP.py","file_ext":"py","file_size_in_byte":9345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"636006064","text":"#calander for 1 month\r\nstarting_day=int(input(\"enter starting day(1-7):\"))\r\nnum_of_days=int(input(\"enter no days:\"))\r\nprint(\"sun Mon Tue Wed Thu Fri Sat\")\r\nprint(\"-------------------------------\")\r\nfor i in range(starting_day-1): #for space in begining of month\r\n print(end=\" \")\r\ni=starting_day-1\r\nfor j in range(1,num_of_days+1):\r\n if(i>6): #prints in next line after saturday\r\n print()\r\n i=1\r\n else:\r\n i=i+1\r\n print(j,\" \",end=\" \")","sub_path":"calander.py","file_name":"calander.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"257619076","text":"from __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom six.moves import xrange\n\nimport tensor_utils_5_channels as utils\n\nFLAGS = tf.flags.FLAGS\ntf.flags.DEFINE_integer(\"batch_size\", \"5\", \"batch size for training\")\ntf.flags.DEFINE_string(\"logs_dir\", \"../logs-vgg19/\", \"path to logs directory\")\ntf.flags.DEFINE_string(\"data_dir\", \"../ISPRS_semantic_labeling_Vaihingen\", \"path to dataset\")\ntf.flags.DEFINE_float(\"learning_rate\", \"1e-4\", \"Learning rate for Adam Optimizer\")\ntf.flags.DEFINE_string(\"model_dir\", \"../pretrained_models/imagenet-vgg-verydeep-19.mat\",\n \"Path to vgg model mat\")\ntf.flags.DEFINE_bool('debug', \"False\", \"Debug mode: True/ False\")\ntf.flags.DEFINE_string('mode', \"train\", \"Mode train/ test/ visualize\")\n\nMODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat'\n\nMAX_ITERATION = int(1e7 + 1)\nNUM_OF_CLASSES = 6\nIMAGE_SIZE = 224\nVALIDATE_IMAGES = [\"top_mosaic_09cm_area7.png\",\"top_mosaic_09cm_area17.png\",\"top_mosaic_09cm_area23.png\",\"top_mosaic_09cm_area37.png\"]\ntf_records_filename = 'Vaihingen.tfrecords'\n\ndef vgg_net(weights, image):\n layers = (\n 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',\n\n 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',\n\n 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',\n 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',\n\n 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',\n 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',\n\n 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',\n 'relu5_3', 'conv5_4', 'relu5_4'\n )\n\n net = {}\n current = image\n for i, name in enumerate(layers):\n kind = name[:4]\n if kind == 'conv':\n kernels, bias = weights[i][0][0][0][0]\n if name == 'conv1_1':\n append_channels= np.random.normal(loc=0,scale=0.02,size=(3,3,12,64))\n kernels = np.concatenate((kernels, append_channels), axis=2)\n kernels = utils.get_variable(np.transpose(kernels, (0, 1, 2, 3)), name=name + \"_w\")\n else:\n kernels = utils.get_variable(np.transpose(kernels, (0, 1, 2, 3)), name=name + \"_w\")\n bias = utils.get_variable(bias.reshape(-1), name=name + \"_b\")\n current = utils.conv2d_basic(current, kernels, bias)\n elif kind == 'relu':\n current = tf.nn.relu(current, name=name)\n\n elif kind == 'pool':\n current = utils.avg_pool_2x2(current)\n net[name] = current\n\n return net\n\n\ndef inference(image, keep_prob):\n print(\"setting up vgg initialized conv layers ...\")\n model_data = utils.get_model_data(FLAGS.model_dir)\n\n mean = model_data['normalization'][0][0][0]\n mean_pixel = np.mean(mean, axis=(0, 1))\n mean_pixel = np.append(mean_pixel, [30.6986130799, 284.97018,106.314329243,124.171918054,109.260369903,182.615729022,\n 75.1762766769,84.3529895303,100.699252985,66.8837693324,98.6030061849,133.955897217])\n weights = np.squeeze(model_data['layers'])\n\n processed_image = utils.process_image(image, mean_pixel)\n\n with tf.variable_scope(\"inference\"):\n image_net = vgg_net(weights, processed_image)\n conv_final_layer = image_net[\"conv5_3\"]\n\n pool5 = utils.max_pool_2x2(conv_final_layer)\n\n W6 = utils.weight_variable([7, 7, 512, 4096], name=\"W6\")\n b6 = utils.bias_variable([4096], name=\"b6\")\n conv6 = utils.conv2d_basic(pool5, W6, b6)\n relu6 = tf.nn.relu(conv6, name=\"relu6\")\n\n relu_dropout6 = tf.nn.dropout(relu6, keep_prob=keep_prob)\n\n W7 = utils.weight_variable([1, 1, 4096, 4096], name=\"W7\")\n b7 = utils.bias_variable([4096], name=\"b7\")\n conv7 = utils.conv2d_basic(relu_dropout6, W7, b7)\n relu7 = tf.nn.relu(conv7, name=\"relu7\")\n\n relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob)\n\n W8 = utils.weight_variable([1, 1, 4096, NUM_OF_CLASSES], name=\"W8\")\n b8 = utils.bias_variable([NUM_OF_CLASSES], name=\"b8\")\n conv8 = utils.conv2d_basic(relu_dropout7, W8, b8)\n\n deconv_shape1 = image_net[\"pool4\"].get_shape()\n W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, NUM_OF_CLASSES], name=\"W_t1\")\n b_t1 = utils.bias_variable([deconv_shape1[3].value], name=\"b_t1\")\n conv_t1 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1, output_shape=tf.shape(image_net[\"pool4\"]))\n fuse_1 = tf.add(conv_t1, image_net[\"pool4\"], name=\"fuse_1\")\n\n deconv_shape2 = image_net[\"pool3\"].get_shape()\n W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name=\"W_t2\")\n b_t2 = utils.bias_variable([deconv_shape2[3].value], name=\"b_t2\")\n conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net[\"pool3\"]))\n fuse_2 = tf.add(conv_t2, image_net[\"pool3\"], name=\"fuse_2\")\n\n shape = tf.shape(image)\n deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], NUM_OF_CLASSES])\n W_t3 = utils.weight_variable([16, 16, NUM_OF_CLASSES, deconv_shape2[3].value], name=\"W_t3\")\n b_t3 = utils.bias_variable([NUM_OF_CLASSES], name=\"b_t3\")\n conv_t3 = utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)\n\n annotation_pred = tf.argmax(conv_t3, axis=3, name=\"prediction\")\n\n return tf.expand_dims(annotation_pred, dim=3), conv_t3\n\n\ndef train(loss_val, var_list):\n optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)\n grads = optimizer.compute_gradients(loss_val, var_list=var_list)\n return optimizer.apply_gradients(grads)\n\ndef read_and_decode(filename_queue):\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n features = tf.parse_single_example(\n serialized_example,\n features={\n 'image_raw': tf.FixedLenFeature([], tf.string),\n 'annotation_raw': tf.FixedLenFeature([], tf.string)\n })\n image = tf.decode_raw(features['image_raw'], tf.float16)\n annotation = tf.decode_raw(features['annotation_raw'], tf.uint8)\n image = tf.reshape(image, [224, 224, 15])\n annotation = tf.reshape(annotation, [224, 224, 1])\n min_after_deque = 1000\n batch_size = 5\n num_thread = 20\n capacity = min_after_deque + (num_thread + 1) * batch_size\n images, annotations = tf.train.shuffle_batch([image, annotation], batch_size=batch_size, num_threads=num_thread,\n min_after_dequeue=min_after_deque, capacity=capacity)\n return images, annotations\n\ndef main(argv=None):\n filename_queue = tf.train.string_input_producer([tf_records_filename])\n image, annotation = read_and_decode(filename_queue)\n image = tf.cast(image, dtype=tf.float32)\n annotation = tf.cast(annotation, dtype=tf.int32)\n keep_probability = tf.placeholder(tf.float32, name=\"keep_probabilty\")\n\n pred_annotation, logits = inference(image, keep_probability)\n annotation_64 = tf.cast(annotation, dtype=tf.int64)\n\n # calculate accuracy for batch.\n cal_acc = tf.equal(pred_annotation, annotation_64)\n cal_acc = tf.cast(cal_acc, dtype=tf.int8)\n acc = tf.count_nonzero(cal_acc) / (FLAGS.batch_size * IMAGE_SIZE * IMAGE_SIZE)\n loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,\n labels=tf.squeeze(annotation,\n squeeze_dims=[3]),\n name=\"entropy\")))\n loss_summary=tf.summary.scalar(\"entropy\", loss)\n acc_summary=tf.summary.scalar(\"accuracy\", acc)\n\n trainable_var = tf.trainable_variables()\n\n train_op = train(loss, trainable_var)\n\n sess = tf.Session()\n\n print(\"Setting up Saver...\")\n saver = tf.train.Saver()\n\n train_writer = tf.summary.FileWriter(FLAGS.logs_dir + '/train', sess.graph)\n\n sess.run(tf.global_variables_initializer())\n ckpt = tf.train.get_checkpoint_state(FLAGS.logs_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n print(\"Model restored...\")\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord,sess=sess)\n for itr in xrange(MAX_ITERATION):\n feed_dict = {keep_probability: 0.75}\n sess.run(train_op, feed_dict=feed_dict)\n if itr % 50 == 0:\n train_loss, train_acc, summary_loss, summary_acc = sess.run([loss, acc, loss_summary, acc_summary], feed_dict=feed_dict)\n print(\"Step: %d, Train_loss: %g, Train_acc: %g\" % (itr, train_loss, train_acc))\n train_writer.add_summary(summary_loss, itr)\n train_writer.add_summary(summary_acc, itr)\n if itr % 500 == 0:\n saver.save(sess, FLAGS.logs_dir + \"model.ckpt\", itr)\n coord.request_stop()\n coord.join(threads)\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"fully_convnets_15_channels.py","file_name":"fully_convnets_15_channels.py","file_ext":"py","file_size_in_byte":9073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"21133147","text":"import pynput\n\nmouse_drag = pynput.mouse.Controller()\nmouse_button = pynput.mouse.Button\n\ndef mouse_move():\n\tdefault = mouse_drag.position #현재 마우스 커서의 위치를 변수에 대입한다\n\tprint(default) \n\n\tmouse_drag.position=(100,700) #해당 좌표로 마우스커서 이동\n\n\tmouse_drag.press(mouse_button.left) #마우스 왼쪽 버튼을 누른 상태로 유지한다\n\tmouse_drag.release(mouse_button.left) #마우스 왼쪽 버튼을 뗀 상태로 유지한다\n\n\t# mouse_drag.press(mouse_button.right) #마우스 왼쪽 버튼을 누른 상태로 유지한다\n\t# mouse_drag.release(mouse_button.right) #마우스 왼쪽 버튼을 뗀 상태로 유지한다\n\nif __name__ == \"__main__\":\n\tmouse_move()","sub_path":"mouse.py","file_name":"mouse.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"523770013","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\n\n\n# TEMPLATE TAGGING\napp_name = 'Mylearning'\n\n\nurlpatterns = [\n\n path('', views.Mylearning, name='Mylearning'),\n path('InterviewQuestion/', views.InterviewQuestion, name='InterviewQuestion'),\n path('InterviewQA/', views.InterviewQuestionAnswer.as_view(), name='InterviewQuestionAnswer'),\n path(r'reg/', views.StudentReg, name='StudentReg'),\n\n]\n","sub_path":"Mylearning/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"499730055","text":"# Imports\n\nimport numpy as np\n\n# --------------------------------------------------------------------------- #\n\nimport matplotlib.pyplot as plt\n\n# --------------------------------------------------------------------------- #\n\nimport pandas as pd\n\nimport las2\n\n# --------------------------------------------------------------------------- #\n\nimport os # importar_pasta\n\n# --------------------------------------------------------------------------- #\n\nclass plotagem:\n \n def __init__(self, n, eixoy=True, comprimento=6, altura=5, dpi=70, titulo = '', titulo_fonte = 16,\n cor_fundo = 'white',transparencia_fundo = 0.5,\n cor_plot_fundo = 'white',transparencia_plot_fundo = 1.0):\n \n self.ax = [0]*n\n self.fig, (self.ax) = plt.subplots(1,n,sharey=eixoy,figsize=(comprimento, altura),\n dpi=dpi)\n self.fig.suptitle(titulo, fontsize=titulo_fonte)\n \n self.fig.patch.set_facecolor(cor_fundo)\n self.fig.patch.set_alpha(transparencia_fundo)\n \n self.cor_plot_fundo = cor_plot_fundo\n self.transparencia_plot_fundo = transparencia_plot_fundo\n \n def plot_s(self,indice,X,Y,\n cor='b',estilo_linha = '-',\n descricao_x = 'x',descricao_y = 'y',fonte_descricao = 16,\n titulo = 'titulo',fonte_titulo = 15\n ):\n \n \"\"\"plot simples\"\"\"\n \n self.ax[indice].plot(X,Y,c = cor,ls = estilo_linha)\n self.ax[indice].grid()\n self.ax[indice].set_ylim(max(Y),min(Y))\n self.ax[indice].set_title(titulo, fontsize=fonte_titulo)\n if indice == 0:\n self.ax[indice].set_ylabel(descricao_y, fontsize=fonte_descricao)\n self.ax[indice].set_xlabel(descricao_x, fontsize=fonte_descricao)\n \n self.ax[indice].patch.set_facecolor(self.cor_plot_fundo)\n self.ax[indice].patch.set_alpha(self.transparencia_plot_fundo)\n \n def plot_m(self,indice,XX,Y,cores = False,estilo_linha = '-',\n descricao_x = 'x',descricao_y = 'y',fonte_descricao = 16,\n titulo = 'titulo',fonte_titulo = 15):\n \n \"\"\"plot multiplo\"\"\"\n \n if cores:\n crs = cores.copy()\n else:\n crs = ['b']*len(XX)\n \n for i in range(len(XX)):\n self.ax[indice].plot(XX[i],Y,c = crs[i],ls = estilo_linha)\n \n if indice == 0:\n self.ax[indice].set_ylabel(descricao_y, fontsize=fonte_descricao)\n self.ax[indice].set_xlabel(descricao_x, fontsize=fonte_descricao)\n self.ax[indice].set_title(titulo, fontsize=fonte_titulo)\n self.ax[indice].set_xticklabels([])\n \n self.ax[indice].patch.set_facecolor(self.cor_plot_fundo)\n self.ax[indice].patch.set_alpha(self.transparencia_plot_fundo)\n \n def plog_s(self,indice,X,Y,\n cor='b',estilo_linha = '-',\n descricao_x = 'x',descricao_y = 'y',fonte_descricao = 16,\n titulo = 'titulo',fonte_titulo = 15\n ):\n \n \"\"\"plot simples\"\"\"\n \n self.ax[indice].semilogx(X,Y,c = cor,ls = estilo_linha)\n self.ax[indice].grid()\n self.ax[indice].set_ylim(max(Y),min(Y))\n self.ax[indice].set_title(titulo, fontsize=fonte_titulo)\n if indice == 0:\n self.ax[indice].set_ylabel(descricao_y, fontsize=fonte_descricao)\n self.ax[indice].set_xlabel(descricao_x, fontsize=fonte_descricao)\n \n self.ax[indice].patch.set_facecolor(self.cor_plot_fundo)\n self.ax[indice].patch.set_alpha(self.transparencia_plot_fundo)\n \n def plot_l(self,indice,litologia,Y,relacao_cor,curva_limite,minimo = False,maximo = False,\n descricao_x = '',descricao_y = 'y',fonte_descricao = 16,\n titulo = 'titulo',fonte_titulo = 15, legend=False):\n \n \"\"\"plot litologia\"\"\"\n\n codigos = []\n for i in relacao_cor:\n codigos.append(i)\n \n if minimo:\n minimo = minimo\n else:\n minimo = min(curva_limite)\n \n if maximo:\n maximo = maximo\n else:\n maximo = max(curva_limite)\n \n num_cores = len(codigos)\n \n matriz_litologias = np.array([[minimo]*len(curva_limite)]*num_cores)\n \n for j in range(num_cores):\n for i in range(len(matriz_litologias[j])):\n if litologia[i] == codigos[j] and ~np.isnan(curva_limite[i]):\n matriz_litologias[j][i] = curva_limite[i]\n \n # =============================== #\n \n for i in range(num_cores):\n self.ax[indice].plot(matriz_litologias[i],Y,c = relacao_cor[codigos[i]][0],lw = 0.1)\n self.ax[indice].fill_betweenx(Y, matriz_litologias[i], facecolor=relacao_cor[codigos[i]][0], label=relacao_cor[codigos[i]][1])\n self.ax[indice].set_ylim(max(Y),min(Y))\n self.ax[indice].set_xlim(minimo,maximo)\n if indice == 0:\n self.ax[indice].set_ylabel(descricao_y, fontsize=fonte_descricao)\n self.ax[indice].set_xlabel(descricao_x, fontsize=fonte_descricao)\n self.ax[indice].set_xticks([])\n self.ax[indice].set_title(titulo, fontsize=fonte_titulo)\n \n self.ax[indice].patch.set_facecolor(self.cor_plot_fundo)\n self.ax[indice].patch.set_alpha(self.transparencia_plot_fundo)\n \n if legend==True:\n self.fig.legend(loc='lower center', fancybox=True, shadow=True, ncol=(3))\n \n def mostrar(self):\n plt.show()\n \n def salvar(self,caminho,transparencia = True):\n self.fig.savefig(caminho, transparent=transparencia)\n \n# --------------------------------------------------------------------------- #\n# ###\n# --------------------------------------------------------------------------- #\n\nclass gerenciamento():\n \n def __init__(self):\n \n self.projetos = {}\n \n # ============================================ #\n \n def importar_pasta(caminho_geral,nomes = False,ext = '.las'):\n\n #------------------------------------------------------------------#\n # vai conter o caminho até os arquivos em geral\n arquivos = []\n # r=root, d=directories, f = files\n for r, d, f in os.walk(caminho_geral):\n for file in f:\n if ext in file:\n arquivos.append(os.path.join(r, file))\n\n #------------------------------------------------------------------#\n # arquivos = caminho geral ate os arquivos\n # names = nomes dos poços\n\n if nomes:\n\n names = []\n for i in arquivos:\n n1 = i.replace(caminho_geral+'/', '')\n names.append(n1.replace(ext,''))\n\n return [arquivos,names]\n\n else:\n\n return arquivos\n \n # ============================================ #\n \n def importar_las(caminho,apelidos=False):\n\n campo = {}\n\n dado_lido = las2.read(caminho)\n\n nomes = [a['mnemonic'] for a in dado_lido['curve']]\n unidades = [a['unit'] for a in dado_lido['curve']]\n dado = {}\n for i in range(len(nomes)):\n dado[nomes[i]] = dado_lido['data'][i]\n\n # ------------------------------------ #\n\n if apelidos:\n dado_final = {}\n for i in dado:\n for j in apelidos:\n for k in apelidos[j]:\n\n if i == k:\n #print(i,'apelidado de',j)\n dado_final[j] = dado[i]\n\n return dado_final\n\n # ------------------------------------ #\n\n else:\n return dado\n \n # ============================================ #\n \n \n def importar_csv(caminho,profundidades,mnemonico):\n\n dado = pd.read_csv(caminho)\n\n print(\"cabecalho =\",dado.columns.values)\n\n dado_final = {}\n\n for i in list(dado.columns.values):\n for j in mnemonico:\n for k in mnemonico[j]:\n\n if i == k:\n print(i,'apelidado de',j)\n dado_final[j] = list(dado[i])\n\n lito = dado_final['codigo']\n ptop = dado_final['topo']\n pbot = dado_final['base']\n\n lito_2 = [0.0]*len(profundidades)\n\n for j in range(len(ptop)):\n for i in range(len(profundidades)):\n if profundidades[i] >= ptop[j] and profundidades[i] < pbot[j]:\n lito_2[i] = lito[j]\n\n return lito_2\n \n # ============================================ #\n \n def importar_dados(caminhos,pocos=False):\n \n # ------------------------------------ #\n \n campo = {}\n for j in range(len(caminhos)):\n\n dado_lido = las2.read(caminhos[j])\n\n nomes = [a['mnemonic'] for a in dado_lido['curve']]\n unidades = [a['unit'] for a in dado_lido['curve']]\n dado = {}\n for i in range(len(nomes)):\n dado[nomes[i]] = dado_lido['data'][i]\n\n campo[caminhos[j]] = [dado,nomes,unidades]\n \n return [nomes,campo]\n \n # ============================================ #\n \n def cropar(profundidade,curvas,topo=0,base=20000,nulos=False):\n\n novas_curvas = []\n for j in range(len(curvas)):\n curva = []\n profundiade_cropada = []\n for i in range(len(profundidade)):\n if profundidade[i] >= topo and profundidade[i] < base:\n curva.append(curvas[j][i])\n profundiade_cropada.append(profundidade[i])\n novas_curvas.append(curva)\n\n novas_curvas_final = []\n novas_curvas_final.append(profundiade_cropada)\n for i in range(len(curvas)):\n novas_curvas_final.append(novas_curvas[i])\n\n return novas_curvas_final\n \n # ============================================ #\n \n def cropar_limpo(profundidade,curvas,topo=0,base=20000,nulos=False):\n\n #nulos_idx = [True]*len(profundidade)\n\n novas_curvas = []\n for j in range(len(curvas)):\n curva = []\n profundiade_cropada = []\n for i in range(len(profundidade)):\n if profundidade[i] >= topo and profundidade[i] < base:\n curva.append(curvas[j][i])\n profundiade_cropada.append(profundidade[i])\n novas_curvas.append(curva)\n\n novas_curvas_final = []\n novas_curvas_final.append(profundiade_cropada)\n for i in range(len(curvas)):\n novas_curvas_final.append(novas_curvas[i])\n\n a = np.array(novas_curvas_final).T\n\n b = a[~np.isnan(a).any(axis=1)]\n if nulos:\n b = b[~np.isin(b,nulos).any(axis=1)]\n\n return list(b.T)\n\n # ============================================ #\n \n def cropar_limpo_2(profundidade,curvas,topo=0,base=20000,nulos=False):\n\n p2 = []\n for j in curvas:\n curva = []\n for i in range(len(curvas[j])):\n if profundidade[i] >= topo and profundidade[i] < base:\n curva.append (curvas[j][i])\n\n p2.append(curva)\n\n a = np.array(p2).T\n b = a[~np.isnan(a).any(axis=1)]\n if nulos:\n b = b[~np.isin(b,nulos).any(axis=1)]\n\n c = b.T\n\n log_limpo = {}\n i = 0\n for key in curvas:\n log_limpo[key] = c[i]\n i += 1\n\n return log_limpo\n \n # ============================================ #\n \n# --------------------------------------------------------------------------- #\n# ###\n# --------------------------------------------------------------------------- #\n\nclass visual:\n \n # ============================================ #\n \n def confusao(lit_1,lit_2,label_1 = False,label_2 = False,log=False,tipo=\"numerico\"):\n\n # ::::::::::::::::::::::::::::::::::::::::::::::: #\n # Definição de variáveis\n\n s_1 = sorted(list(set(lit_1))) # lista dos elementos de lit_1\n s_2 = sorted(list(set(lit_2))) # lista dos elementos de lit_2\n\n if log:\n print(s_1)\n print(s_2)\n\n # ::::::::::::::::::::::::::::::::::::::::::::::: #\n # salvando as labels (loop dos elementos)\n\n nms_1 = []\n for i in range(len(s_1)):\n if label_1:\n nms_1.append(label_1[int(s_1[i])])\n else:\n nms_1.append(int(s_1[i]))\n\n # ________________________ #\n\n nms_2 = []\n for i in range(len(s_2)):\n if label_1:\n if label_2:\n nms_2.append(label_2[int(s_2[i])])\n else:\n nms_2.append(label_1[int(s_2[i])])\n else:\n nms_2.append(int(s_2[i]))\n\n # ::::::::::::::::::::::::::::::::::::::::::::::: #\n # Calculando o erro geral para apresentação\n\n err = []\n for i in range(len(lit_1)):\n if lit_1[i] == lit_2[i]:\n err.append(1)\n else:\n err.append(0)\n\n if log:\n print('acerto = ',sum(err),'de',len(err),'equivalente a',(sum(err)/len(err))*100.0,'%')\n\n # ::::::::::::::::::::::::::::::::::::::::::::::: #\n # calculo dos valores (por dicionário)\n\n CM = {}\n M1 = []\n for j in range(len(s_1)):\n CM[int(s_1[j])] = {}\n M0 = []\n for i in range(len(s_2)):\n values = []\n for jj in range(len(lit_1)):\n if lit_1[jj] == int(s_1[j]):\n if lit_2[jj] == int(s_2[i]):\n values.append(1)\n else:\n values.append(0)\n\n sv = sum(values)\n CM[int(s_1[j])][s_2[i]] = sv\n M0.append(sv)\n M1.append(M0)\n\n # ::::::::::::::::::::::::::::::::::::::::::::::: #\n # calculando proporções\n\n linhas = np.shape(M1)[0]\n colunas = np.shape(M1)[1]\n tamanho = len(lit_1)\n\n if tipo == \"numerico\": # numeros de elementos contados (padrão)\n M1 = np.array(M1)\n MF = M1.copy()\n\n # ________________________ #\n\n if tipo == \"proporcao\": # proporcao em funcao do total\n M1 = np.array(M1,float)\n MF = M1.copy()\n\n for j in range(linhas):\n for i in range(colunas):\n MF[j,i] = (M1[j,i])/(tamanho)\n\n # ________________________ #\n\n if tipo == \"proporcao_linha\": # proporcao em funcao da linha\n M1 = np.array(M1,float)\n MF = M1.copy()\n\n for j in range(linhas):\n soma = sum(M1[j])\n for i in range(colunas):\n MF[j,i] = (M1[j,i])/(soma)\n\n # ________________________ #\n\n if tipo == \"proporcao_coluna\": # proporcao em funcao da coluna\n M1 = np.array(M1,float)\n MF = M1.copy()\n\n for i in range(colunas):\n soma = sum(MF[:,i])\n for j in range(linhas):\n MF[j,i] = (M1[j,i])/(soma)\n\n # ::::::::::::::::::::::::::::::::::::::::::::::: #\n # Tabela e gráficos\n\n the_table = plt.table(cellText=MF,\n colWidths=[0.1] * len(lit_2),\n rowLabels=nms_1,\n colLabels=nms_2,\n loc='center')\n\n the_table.auto_set_font_size(False)\n the_table.set_fontsize(24)\n the_table.scale(4, 4)\n\n plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)\n plt.tick_params(axis='y', which='both', right=False, left=False, labelleft=False)\n\n for pos in ['right','top','bottom','left']:\n plt.gca().spines[pos].set_visible(False)\n plt.show()\n \n # ============================================ #\n \n \n","sub_path":"ArtigoI/modules/appynho.py","file_name":"appynho.py","file_ext":"py","file_size_in_byte":16163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"319409929","text":"from os import listdir, unlink\nfrom os.path import join\nfrom json import load, dump\nfrom PyQt5.QtWidgets import QDialog\nfrom PyQt5.QtCore import Qt\nfrom placer import __basedir__\nfrom placer.ui.config import Ui_ConfigDialog\nfrom placer.edit import EditConfigDialog\n\n\nclass SettingsDialog(QDialog):\n def __init__(self, config, parent):\n super().__init__(parent)\n self._config = config\n self.Ui = Ui_ConfigDialog()\n self.Ui.setupUi(self)\n self.Ui.configComboBox.currentTextChanged.connect(self.update)\n self.Ui.editPushButton.clicked.connect(lambda: self.editConfig(\n name=self.Ui.configComboBox.currentText()))\n self.Ui.addToolButton.clicked.connect(self.editConfig)\n self.Ui.exitCheckBox.setChecked(\n self._config[\"Placer\"].getboolean(\"saveOnExit\"))\n self.Ui.focusCheckBox.setChecked(\n self._config[\"Placer\"].getboolean(\"refreshOnFocus\"))\n self.Ui.prettyCheckBox.setChecked(\n self._config[\"Placer\"].getboolean(\"prettyPrint\"))\n self.Ui.emptyDataCheckBox.setChecked(\n self._config[\"Placer\"].getboolean(\"emptyData\"))\n self.Ui.apiLineEdit.setText(self._config[\"Updates\"][\"nexusApi\"])\n self.refresh(self._config[\"Placer\"][\"config\"])\n self.show()\n\n def refresh(self, config):\n self.Ui.configComboBox.clear()\n for conf in listdir(__basedir__):\n if conf.endswith(\".json\"):\n self.Ui.configComboBox.addItem(conf)\n if config:\n if self.Ui.configComboBox.findText(config, Qt.MatchExactly) != -1:\n self.Ui.configComboBox.setCurrentIndex(\n self.Ui.configComboBox.findText(config, Qt.MatchExactly))\n else:\n self.Ui.configComboBox.setCurrentIndex(0)\n\n def editConfig(self, *, name=\"\"):\n if name in listdir(__basedir__):\n with open(join(__basedir__, name)) as f:\n config = load(f)\n else:\n config = {}\n if name.endswith(\".json\"):\n name = name[:-5]\n config.setdefault(\"game\", \"\")\n config.setdefault(\"data\", \"\")\n config.setdefault(\"mods\", \"\")\n config.setdefault(\"plugins\", \"\")\n config.setdefault(\"prefix\", \"\")\n config.setdefault(\"ModOrder\", {})\n config.setdefault(\"LoadOrder\", {})\n dialog = EditConfigDialog(name, config, self)\n if dialog.exec_():\n oldName = name + \".json\"\n name, config = dialog.getConfig()\n if not name.endswith(\".json\"):\n name = name + \".json\"\n with open(join(__basedir__, name), \"w\") as f:\n dump(config, f)\n if oldName != name:\n if oldName in listdir(__basedir__):\n unlink(oldName)\n self.refresh(name)\n\n def update(self, text):\n if text:\n self.Ui.editPushButton.setEnabled(True)\n self.Ui.buttonBox.setEnabled(True)\n else:\n self.Ui.editPushButton.setEnabled(False)\n self.Ui.buttonBox.setEnabled(False)\n\n def getConfig(self):\n self._config[\"Placer\"][\"config\"] = self.Ui.configComboBox.currentText()\n self._config[\"Placer\"][\"saveOnExit\"] = str(bool(\n self.Ui.exitCheckBox.isChecked()))\n self._config[\"Placer\"][\"refreshOnFocus\"] = str(bool(\n self.Ui.focusCheckBox.isChecked()))\n self._config[\"Placer\"][\"prettyPrint\"] = str(bool(\n self.Ui.prettyCheckBox.isChecked()))\n self._config[\"Placer\"][\"emptyData\"] = str(bool(\n self.Ui.emptyDataCheckBox.isChecked()))\n self._config[\"Updates\"][\"nexusApi\"] = self.Ui.apiLineEdit.text()\n return self._config\n","sub_path":"placer/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"179332863","text":"# pipenv install twilio in terminal\n# C:\\Users\\Gopi\\.virtualenvs\\PyText-PePtKPDH\nfrom twilio.rest import Client\n#put in config.py\naccount_sid = \"use account sid\"\nauth_token = \"use token\"\nclient = Client(account_sid, auth_token)\n\ncall = client.messages.create(\n to=\"phone nbr\",\n from_=\"phone nbr\",\n body=\"Test Message from gopi using twilio api for python\"\n)\n# call has different attributes\n# call.date_updated\n# call.date_created\n# if not delivered , may be do not disturb is enabled for that number\n","sub_path":"PyText/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"553722162","text":"\"\"\"test_TopLoad.py\n\"\"\"\n\nimport sys\nimport os\nimport pytest\nmyPath = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.join(myPath, '/../mesh/'))\n\n\ndef test_extract_top_plane_nodes():\n from TopLoad import extract_top_plane_nodes\n\n nodefile = '%s/nodes.dyn' % myPath\n planeNodeIDs = extract_top_plane_nodes(nodefile=nodefile,\n top_face=[0, 0, 0, 0, 0, 1])\n\n assert planeNodeIDs[0][0] == 1211\n assert planeNodeIDs[-1][-1] == 1331\n\n\ndef test_writeNodeLoads_disp(tmpdir):\n from TopLoad import writeNodeLoads\n f = tmpdir.join(\"topload.dyn\")\n writeNodeLoads(loadfile=f.strpath, planeNodeIDs=[[1, 2, 3], [4, 5, 6]],\n loadtype='disp', direction=2, amplitude=-1.0, lcid=1)\n lines = f.readlines()\n assert lines[0] == \"*BOUNDARY_PRESCRIBED_MOTION_NODE\\n\"\n assert lines[1] == \"1,3,2,1,-1.000000\\n\"\n assert lines[-1] == \"*END\\n\"\n\n\ndef test_writeNodeLoads_force(tmpdir):\n from TopLoad import writeNodeLoads\n f = tmpdir.join(\"topload.dyn\")\n writeNodeLoads(loadfile=f.strpath, planeNodeIDs=[[1, 2, 3], [4, 5, 6]],\n loadtype='force', direction=2, amplitude=-1.0, lcid=1)\n lines = f.readlines()\n assert lines[0] == \"*LOAD_NODE_POINT\\n\"\n assert lines[1] == \"1,3,1,-1.000000\\n\"\n assert lines[-1] == \"*END\\n\"\n\n\ndef test_read_cli():\n from TopLoad import read_cli\n import sys\n\n sys.argv = ['TopLoad.py', '--amplitude', '-5.0']\n opts = read_cli()\n assert opts.amplitude == -5.0\n","sub_path":"tests/test_TopLoad.py","file_name":"test_TopLoad.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"422799711","text":"\"\"\"\r\nCSCI 630(Foundation of Intelligent Systems)\r\nLab 1\r\n@author: Shubham Patil (sbp5931)\r\n\"\"\"\r\n\r\nfrom PIL import Image\r\nfrom collections import defaultdict\r\nfrom heapq import heappush, heappop\r\nimport math\r\nimport time\r\nfrom collections import deque\r\n\r\nclass Orienteering:\r\n __slots__ = [\"elevation\", \"terrain\", \"terrain_speed\", \"course\",\r\n \"output_points\", \"season\", \"winter\", \"fall\", \"spring\"]\r\n\r\n def __init__(self, elevation_file, color_file, course_file, season=\"summer\"):\r\n self.terrain_speed = {(248, 148, 18, 255): 9, (255, 192, 0, 255): 5.5, (255, 255, 255, 255): 6.5,\r\n (2, 208, 60, 255): 5, (2, 136, 40, 255): 3, (5, 73, 24, 255): 0.5,\r\n (0, 0, 255, 255): 0.2, (71, 51, 3, 255): 10, (0, 0, 0, 255): 9.5, (205, 0, 101, 255): 0,\r\n (255, 255, 0, 255): 6.5, (121, 76, 19, 255): 2, (0, 191, 255, 255): 4}\r\n self.elevation = {}\r\n self.read_elevation(elevation_file)\r\n self.terrain = []\r\n self.read_terrain(color_file)\r\n self.course = []\r\n self.read_course(course_file)\r\n self.output_points = set()\r\n self.season = season\r\n if season == \"winter\":\r\n self.winter = set()\r\n self.find_boundary((0, 0, 255, 255), (0, 191, 255, 255))\r\n self.make_winter()\r\n if season == \"fall\":\r\n self.fall = set()\r\n self.find_boundary((255, 255, 255, 255), (255, 255, 0, 255))\r\n self.make_fall()\r\n if season == \"spring\":\r\n self.spring = set()\r\n self.find_boundary((0, 0, 255, 255), (121, 76, 19, 255))\r\n self.make_spring()\r\n self.find_path()\r\n self.create_output()\r\n\r\n def find_boundary(self, old_color, new_color):\r\n for i in range(len(self.terrain)):\r\n x = i % 395\r\n y = i // 395\r\n node = (x, y)\r\n current = self.terrain[self.terrain_index(node)]\r\n if current == old_color:\r\n neighbors = [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]\r\n for neighbor in neighbors:\r\n i, j = neighbor\r\n cond1 = 0 <= i < 395\r\n cond2 = 0 <= j < 500\r\n if cond1 and cond2:\r\n neighbor_value = self.terrain[self.terrain_index(neighbor)]\r\n if neighbor_value != current:\r\n if self.season == \"winter\":\r\n self.winter.add(neighbor)\r\n self.terrain[self.terrain_index(neighbor)] = new_color\r\n if self.season == \"fall\":\r\n self.fall.add(neighbor)\r\n if self.season == \"spring\":\r\n self.spring.add(neighbor)\r\n\r\n def make_winter(self):\r\n queue = deque(list(self.winter))\r\n visited = defaultdict(lambda: 0)\r\n depth = defaultdict(lambda: math.inf)\r\n for x in queue:\r\n depth[x] = 1\r\n visited[x] = 1\r\n while queue:\r\n current = queue.popleft()\r\n self.winter.add(current)\r\n self.terrain[self.terrain_index(current)] = (0, 191, 255, 255)\r\n if depth[current] > 7:\r\n break\r\n for neighbor in self.get_neighbors(current):\r\n neighbor_value = self.terrain[self.terrain_index(neighbor)]\r\n if neighbor_value == (0, 0, 255, 255):\r\n if visited[neighbor] == 0:\r\n visited[neighbor] = 1\r\n depth[neighbor] = depth[current] + 1\r\n queue.append(neighbor)\r\n\r\n def make_spring(self):\r\n queue = deque(list(self.spring))\r\n visited = defaultdict(lambda: 0)\r\n depth = defaultdict(lambda: math.inf)\r\n delta_height = defaultdict(lambda: math.inf)\r\n for x in queue:\r\n depth[x] = 0\r\n visited[x] = 0\r\n delta_height[x] = 0\r\n while queue:\r\n current = queue.popleft()\r\n self.terrain[self.terrain_index(current)] = (121, 76, 19, 255)\r\n if depth[current] > 15:\r\n break\r\n for neighbor in self.get_neighbors(current):\r\n neighbor_value = self.terrain[self.terrain_index(neighbor)]\r\n current_elevation = self.elevation[self.elevation_ind(current)]\r\n neighbor_elevation = self.elevation[self.elevation_ind(neighbor)]\r\n elevation_difference = (neighbor_elevation - current_elevation)\r\n delta_height[neighbor] = delta_height[current] + elevation_difference\r\n if neighbor_value != (0, 0, 255, 255):\r\n if delta_height[neighbor] > 1:\r\n break\r\n else:\r\n if visited[neighbor] == 0:\r\n visited[neighbor] = 1\r\n depth[neighbor] = depth[current] + 1\r\n queue.append(neighbor)\r\n\r\n def make_fall(self):\r\n for point in self.fall:\r\n for neighbor in self.get_neighbors(point):\r\n neighbor_value = self.terrain[self.terrain_index(neighbor)]\r\n cond1 = (neighbor_value == (71, 51, 3, 255))\r\n cond2 = (neighbor_value == (0, 0, 0, 255))\r\n if cond1 or cond2:\r\n self.terrain[self.terrain_index(neighbor)] = (255, 255, 0, 255)\r\n\r\n def elevation_ind(self, point):\r\n x, y = point\r\n t = (y, x)\r\n return t\r\n\r\n def read_elevation(self, filename):\r\n with open(filename) as elevation:\r\n i = 0\r\n for line in elevation:\r\n line = line.strip()\r\n k = line.split()\r\n for j in range(395):\r\n t = (i, j)\r\n self.elevation[t] = float(k[j])\r\n i = i+1\r\n\r\n def read_terrain(self, filename):\r\n im = Image.open(filename)\r\n self.terrain = list(im.getdata())\r\n\r\n def terrain_index(self, point):\r\n x, y = point\r\n return y * 395 + x\r\n\r\n def speed(self, point):\r\n x, y = point\r\n return self.terrain_speed[self.terrain[self.terrain_index((x, y))]]\r\n\r\n def read_course(self, filename):\r\n with open(filename) as course:\r\n for line in course:\r\n line = line.strip()\r\n x, y = line.split()\r\n x, y = int(x), int(y)\r\n checkpoint = (x, y)\r\n self.course.append(tuple(checkpoint))\r\n\r\n def get_neighbors(self, point):\r\n x, y = point\r\n neighbors = []\r\n for i in (x - 1, x, x + 1):\r\n for j in (y - 1, y, y + 1):\r\n cond1 = not(i == x and j == y)\r\n cond2 = 0 <= i < 395\r\n cond3 = 0 <= j < 500\r\n if cond1 and cond2 and cond3:\r\n neighbors.append((i, j))\r\n return neighbors\r\n\r\n def cost(self, current, neighbor):\r\n x = 10.29\r\n y = 7.55\r\n x1, y1 = current\r\n x2, y2 = neighbor\r\n xy_cost = math.sqrt(((y2-y1)*y)**2 + ((x2-x1)*x)**2)\r\n neighbor_speed = self.speed(neighbor)\r\n current_elevation = self.elevation[(y1, x1)]\r\n neighbor_elevation = self.elevation[(y2, x2)]\r\n elevation_difference = abs(neighbor_elevation - current_elevation)\r\n if not(x1 == x2 and y1 == y2):\r\n if neighbor_speed == 0:\r\n return float(\"inf\")\r\n xyz_distance = math.sqrt(xy_cost**2 + elevation_difference**2)\r\n return xyz_distance/neighbor_speed\r\n else:\r\n return 0\r\n\r\n def heuristic(self, current, target):\r\n x = 10.29\r\n y = 7.55\r\n x1, y1 = current\r\n x2, y2 = target\r\n speed = 10\r\n euclidean_distance = math.sqrt(((y2-y1)*y)**2 + ((x2-x1)*x)**2)\r\n if not(x1 == x2 and y1 == y2):\r\n return euclidean_distance/speed\r\n else:\r\n return 0\r\n\r\n def find_path(self):\r\n cost = 0\r\n for i in range(len(self.course)-1):\r\n start = self.course[i]\r\n goal = self.course[i+1]\r\n cost += self.a_star(start, goal)\r\n print(\"Total cost for \"+self.season+\" is \"+str(cost)+\" seconds\")\r\n\r\n def create_output(self):\r\n image = Image.new(\"RGBA\", (395, 500), \"white\")\r\n im = image.load()\r\n for i in range(len(self.terrain)):\r\n x = i % 395\r\n y = i // 395\r\n node = (x, y)\r\n if node not in self.output_points:\r\n im[node] = self.terrain[i]\r\n for point in self.output_points:\r\n im[point] = (255, 0, 0, 255)\r\n for point in self.course:\r\n im[point] = (138, 43, 226, 255)\r\n image.save(self.season+\".png\")\r\n\r\n def is_in(self, node, list_of_list):\r\n for i in list_of_list:\r\n if i[1] == node:\r\n return True\r\n return False\r\n\r\n def a_star(self, start, goal):\r\n open = []\r\n closed = set()\r\n predecessor = {}\r\n g = defaultdict(lambda: math.inf)\r\n g[start] = 0\r\n f = defaultdict(lambda: math.inf)\r\n f[start] = self.heuristic(start, goal)\r\n heappush(open, [f[start], start])\r\n while open:\r\n current = heappop(open)[1]\r\n if current == goal:\r\n path = [current]\r\n return_value = g[current]\r\n self.output_points.add(current)\r\n while current in predecessor.keys():\r\n current = predecessor[current]\r\n path.append(current)\r\n self.output_points.add(current)\r\n return return_value\r\n closed.add(current)\r\n for neighbor in self.get_neighbors(current):\r\n if self.speed(neighbor) != 0:\r\n if neighbor in closed:\r\n continue\r\n if self.is_in(neighbor, open):\r\n new_g = g[current] + self.cost(current, neighbor)\r\n if new_g < g[neighbor]:\r\n predecessor[neighbor] = current\r\n g[neighbor] = new_g\r\n f[neighbor] = g[neighbor] + self.heuristic(neighbor, goal)\r\n heappush(open, [f[neighbor], neighbor])\r\n else:\r\n predecessor[neighbor] = current\r\n g[neighbor] = g[current] + self.cost(current, neighbor)\r\n f[neighbor] = g[neighbor] + self.heuristic(neighbor, goal)\r\n heappush(open, [f[neighbor], neighbor])\r\n return False\r\n\r\n\r\nif __name__ == '__main__':\r\n p0 = time.time()\r\n for season in [\"summer\", \"fall\", \"winter\", \"spring\"]:\r\n t0 = time.time()\r\n obj = Orienteering(\"mpp.txt\", \"terrain.png\", \"red.txt\", season)\r\n t1 = time.time()\r\n print(\"Execution time for \"+season+\" is \"+str(t1-t0)+\"\\n\")\r\n p1 = time.time()\r\n print(\"Total time:\", (p1-p0))\r\n","sub_path":"orienteering.py","file_name":"orienteering.py","file_ext":"py","file_size_in_byte":11266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"199608204","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 14 08:01:06 2014\r\n\r\n@author: velimir\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport re\r\n\r\nclass WlReader:\r\n\r\n def __init__(self):\r\n self.kanali = {'SO2':'1-SO2-ppb',\r\n 'CO':'30-CO-ppm',}\r\n \"\"\"\r\n key:regex pattern to match it\r\n \r\n pretpostavka je da je naziv kompaktan i da sadrži:\r\n ime plina i mjernu jedinicu\r\n\r\n\tpattern je \r\n\t[0-9]+-xxx-yyy\r\n\r\n \"\"\"\r\n self.regexKanali={'SO2-ug/m3':r'\\b\\S*so2\\S*ug/m3\\b',\r\n 'NO-ug/m3':r'\\b\\S*no\\S*ug/m3\\b',\r\n 'NOx-ug/m3':r'\\b\\S*nox\\S*ug/m3\\b',\r\n 'NO2-ug/m3':r'\\b\\S*no2\\S*ug/m3\\b',\r\n 'CO-mg/m3':r'\\b\\S*co\\S*mg/m3\\b',\r\n 'O3-ug/m3':r'\\b\\S*o3\\S*ug/m3\\b',\r\n 'PM1-ug/m3':r'\\b\\S*pm1\\S*ug/m3\\b',\r\n 'PM2.5-ug/m3':r'\\b\\S*(pm2\\.5)\\S*ug/m3\\b',\r\n 'PM10-ug/m3':r'\\b\\S*pm10\\S*ug/m3\\b'}\r\n\r\n def set_kanali_za_citanje(self, mapa):\r\n self.kanali = mapa\r\n \r\n def dodaj_kanal(self,kljuc,kanal):\r\n if kljuc not in self.kanali.keys():\r\n self.kanali[kljuc]=kanal\r\n else:\r\n raise KeyError('Unable to create new key, it already exists')\r\n \r\n def brisi_kanal(self,dkey):\r\n del self.kanali[dkey]\r\n\r\n def citaj(self, path):\r\n \"\"\"reads from CSV file into data frame (path is location of file)\"\"\"\r\n df = pd.read_csv(\r\n path,\r\n na_values='-999.00',\r\n index_col=0,\r\n parse_dates=[[0,1]],\r\n dayfirst=True,\r\n header=0,\r\n sep=',',\r\n encoding='latin-1')\r\n\r\n\r\n if self.kanali=={}:\r\n raise KeyError('Neko sranje sa kanalima')\r\n \r\n frejmovi={}\r\n for k in self.kanali:\r\n v=self.kanali[k]\r\n i=df.columns.get_loc(v)\r\n frejmovi[k] = df.iloc[:,i:i+2]\r\n frejmovi[k][u'flag']=pd.Series(0,index=frejmovi[k].index)\r\n tmp=frejmovi[k].columns.values\r\n tmp[0]=u'koncentracija'\r\n tmp[1]=u'status'\r\n frejmovi[k].columns=tmp\r\n \r\n #regex dio\r\n for column in df.columns:\r\n for key in self.regexKanali:\r\n match=re.search(self.regexKanali[key],column,re.IGNORECASE)\r\n if match:\r\n v=column\r\n i=df.columns.get_loc(v)\r\n frejmovi[key] = df.iloc[:,i:i+2]\r\n frejmovi[key][u'flag']=pd.Series(0,index=frejmovi[key].index)\r\n tmp=frejmovi[key].columns.values\r\n tmp[0]=u'koncentracija'\r\n tmp[1]=u'status'\r\n frejmovi[key].columns=tmp\r\n return frejmovi\r\n \r\n \r\nif __name__ == \"__main__\":\r\n data = WlReader().citaj('pj.csv')\r\n","sub_path":"citac.py","file_name":"citac.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"462000016","text":"# Complete the diagonalDifference function below.\ndef diagonalDifference(arr):\n numrows = len(arr) \n numcols = len(arr[0]) \n i = 0\n j = 0\n firstsum = 0\n secondsum = 0\n for i in range(0,numrows):\n print(arr[i][j])\n firstsum += arr[i][j]\n j += 1\n \n i = 0\n j = numcols-1\n #for i in range(numrows-1, 0, -1):\n for i in range(0,numrows):\n print(arr[i][j])\n secondsum += arr[i][j]\n j -= 1\n \n return abs(firstsum-secondsum)\n","sub_path":"Warm Up - Algorithms/Diagonal_Difference.py","file_name":"Diagonal_Difference.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"100223298","text":"#!/usr/bin/python\n\nimport sys, os, argparse, json, urllib\nfrom datetime import datetime\n\n# Define properties\naddress = 'Downtown'\ncity = ''\ncountry = ''\npostalCode = ''\npath = os.path.dirname(os.path.realpath(__file__))\noutput = 'gpxFile'\nlatitude = 0\nlongitude = 0\n\n# Do the process expected\ndef main():\n\tglobal address\n\tglobal city\n\tglobal country\n\tglobal output\n\tglobal path\n\tglobal postalCode\n\t# Get all args\n\targs = options().parse_args()\n\t# Set vars\n\taddress = args.address\n\tcity = args.city\n\tcountry = args.country\n\toutput = args.output\n\tpath = args.path\n\t# Directory exists ?\n\tif os.path.exists(path):\n\t\t# Be sure the path is correct\n\t\tif(path[-1:] != '/'):\n\t\t\tpath = path + '/'\n\t\tpostalCode = args.postalCode\n\t\t# Get coordinate of the location informed\n\t\tprint('Getting location...')\n\t\tcoordinates = getCoordinates()\n\t\tif coordinates == 1:\n\t\t\tprint('Location OK')\n\t\t\tprint('Generating GPX...')\n\t\t\t# Generate the file\n\t\t\tgenerateGPX()\n\t\t\tprint('Congrats GPX generated !')\n\t\telse:\n\t\t\tprint('Location Unknown !')\n\telse:\n\t\tprint('Directory does not exists !')\n\n# Adds all options needed\ndef options():\n\tparser = argparse.ArgumentParser(description='How to use GPX-Generator')\n\tparser.add_argument(\"-a\", \"--address\", type=str, dest=\"address\", help=\"Address\", default=address)\n\tparser.add_argument(\"-ci\", \"--city\", type=str, dest=\"city\", help=\"City\", required=True)\n\tparser.add_argument(\"-co\", \"--country\", type=str, dest=\"country\", help=\"Country\", required=True)\n\tparser.add_argument(\"-o\", \"--output\", type=str, dest=\"output\", help=\"Output file name\", default=output)\n\tparser.add_argument(\"-p\", \"--path\", type=str, dest=\"path\", help=\"Path to save the output file\", default=path)\n\tparser.add_argument(\"-pc\", \"--postalcode\", type=str, dest=\"postalCode\", help=\"Postal Code\", default='0')\n\treturn parser\n\n# Function to get coordinates in terms of address informed\ndef getCoordinates():\n\tglobal latitude\n\tglobal longitude\n\turl = 'http://maps.google.com/maps/api/geocode/json?address='+address+','+postalCode+','+city+','+country+'&sensor=false'\n\trequest = urllib.urlopen(url)\n\tdata = json.loads(request.read())\n\tif(data['status'] == 'OK'):\n\t\tlatitude=data['results'][0]['geometry']['location']['lat']\n\t\tlongitude=data['results'][0]['geometry']['location']['lng']\n\t\treturn 1\n\treturn 0;\n\n# Function that will generate the GPX file\ndef generateGPX():\n\tcontent ='\\n\\\n\\n\\\n\t\\n\\\n\t\t\\n\\\n\t\t'+output+'\\n\\\n\t\t\\n\\\n\t\t\t\\n\\\n\t\t\t\t\\n\\\n\t\t\t\t\t'+address+'\\n\\\n\t\t\t\t\t'+city+'\\n\\\n\t\t\t\t\t'+country[:2].upper()+'\\n\\\n\t\t\t\t\t'+postalCode+'\\n\\\n\t\t\t\t\\n\\\n\t\t\t\\n\\\n\t\t\\n\\\n\t\\n\\\n'\n\t# Create the gpx file\n\tfo = open(path+output+'.gpx', \"wb\")\n\tfo.write(content);\n\tfo.close()\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"External/gpx-generator.py","file_name":"gpx-generator.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"218119886","text":"from __future__ import division\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\nimport numpy as np\nimport urllib\nimport scipy\nimport os\n\nimport pysmac\nimport pysmac.analyzer\nimport pysmac.utils\n\nimport sklearn.ensemble\nimport sklearn.datasets\nimport sklearn.cross_validation\nfrom sklearn import metrics\nfrom sknn.mlp import Classifier, Layer\nfrom time import time\n\n# Function to calculate the median\ndef median(data):\n data = sorted(data)\n n = len(data)\n if n%2 == 1:\n return data[n//2]\n else:\n i = n//2\n return (data[i - 1] + data[i])/2\n\nstart = time()\nn_iter = 100 ## Number of evaluations (SMAC)\nn_validations = 25 ## Number of Monte-Carlo Cross-Validations for each model's accuracy evaluated\n\n# Dataset 4\n\nurl4 = \"http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv\"\ndataset4 = np.loadtxt(urllib.urlopen(url4), delimiter=\";\", skiprows = 1)\nX = dataset4[:,0:11]\nY = dataset4[:,11]\nY[Y<6] = 0\nY[Y>0] = 1\n\n# We fit the MLP with the hyperparameters given and return the model's median accuracy from 25 trials\ndef mlp(number_layers, number_neurons_1, number_neurons_2, number_neurons_3, number_neurons_4, dropout_rate):\n\n\tlayers = []\n\tnumber_neurons = []\n\n\tnumber_neurons.append(number_neurons_1)\n\tnumber_neurons.append(number_neurons_2)\n\tnumber_neurons.append(number_neurons_3)\n\tnumber_neurons.append(number_neurons_4)\n\n\tfor i in np.arange(number_layers):\n\t\tlayers.append(Layer(\"Sigmoid\", units=number_neurons[i], dropout = dropout_rate))\n\n\tlayers.append(Layer(\"Softmax\", units=2))\n\n\tscores = []\n\n\tfor i in np.arange(n_validations):\n\n\t\tX_train, X_test, Y_train, Y_test = sklearn.cross_validation.train_test_split(X,Y, test_size=0.3, random_state=1)\n\t\n\t\tpredictor = Classifier(\n\t layers=layers,\n\t learning_rate=0.001,\n\t n_iter=25)\n\n\t\tpredictor.fit(X_train, Y_train)\n\n\t\tscores.append(metrics.accuracy_score(Y_test, predictor.predict(X_test)))\n\t\n\treturn -median(scores)\n\n# We create the optimizer object\nopt = pysmac.SMAC_optimizer( working_directory = './results/dataset4/smac_warm/' % os.environ, persistent_files=True, debug = False)\n\n# Warmstart for Dataset #4 (optimum parameters from Dataset #9)\nparameter_definition=dict(\\\n\t\tnumber_layers = (\"integer\", [1,4], 2),\n\t\tnumber_neurons_1 =(\"integer\", [10,1000], 65, 'log'),\n\t\tnumber_neurons_2 =(\"integer\", [10,1000], 10, 'log'),\n\t\tnumber_neurons_3 =(\"integer\", [10,1000], 94, 'log'),\n\t\tnumber_neurons_4 =(\"integer\", [10,1000], 15, 'log'),\n\t\tdropout_rate =(\"real\", [0,1], 0.002883948210729126),\n\t\t)\n\n# We set some parameters for the optimizer\nvalue, parameters = opt.minimize(mlp,\n\t\t\t\t\tn_iter, parameter_definition,\t# number of evaluations\n\t\t\t\t\tnum_runs = 2,\t\t\t\t\t# number of independent SMAC runs\n\t\t\t\t\tseed = 2,\t\t\t\t\t\t# random seed\n\t\t\t\t\tnum_procs = 2,\t\t\t\t\t# two cores\n\t\t\t\t\tmem_limit_function_mb=1000,\t\t# Memory limit\n\t\t\t\t\tt_limit_function_s = 10000\t # Time limit in seconds\n\t\t\t\t\t)\n\n# We print the best configuration found and its accuracy\nprint(('The highest accuracy found: %f'%(-value)))\nprint(('Parameter setting %s'%parameters))\nprint(\"Bayesian Optimization took %.2f seconds for %d evaluations\" % ((time() - start), n_iter))\n\n\n\n\n\n","sub_path":"smac_warmstart_mlp_4.py","file_name":"smac_warmstart_mlp_4.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"14157407","text":"from sklearn import datasets, metrics, svm\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.linear_model import SGDClassifier\r\n\r\niris = datasets.load_iris()\r\ndigits = datasets.load_digits()\r\n\r\ndigits.data\r\ndigits.target\r\ndigits.images[0]\r\n\r\n#Tutorial\r\nClf = svm.SVC(gamma = 0.001, C=100.)\r\nClf.fit(digits.data[:-1], digits.target[:-1])\r\nexpectedClf = digits.target[-1:]\r\npredictClf = Clf.predict(digits.data[-1:])\r\n\r\nprint(\"Classificação SVC(Tutorial) : \\n %s:\\n%s\\n\" % (Clf, metrics.classification_report(expectedClf, predictClf)))\r\n#Tutorial - fim\r\n\r\n#Primeiro algoritmo\r\nKnc = KNeighborsClassifier(n_neighbors = 1)\r\nKnc.fit(digits.data[:-500], digits.target[:-500])\r\nexpectedKnc = digits.target[-500:]\r\npredictKnc = Knc.predict(digits.data[-500:])\r\n\r\nprint(\"Classificação Kneighbors: \\n %s:\\n%s\\n\" % (Knc, metrics.classification_report(expectedKnc, predictKnc)))\r\n#Primeiro algoritmo - fim\r\n\r\n#Segundo algoritmo\r\nSgd = SGDClassifier(loss=\"hinge\", penalty=\"l2\", max_iter=5) \r\nSgd.fit(digits.data[:-500], digits.target[:-500])\r\nexpectedSgd = digits.target[-500:]\r\npredictSgd = Sgd.predict(digits.data[-500:]) \r\n\r\nprint(\"Classificação SGD: \\n %s:\\n%s\\n\" % (Sgd, metrics.classification_report(expectedSgd, predictSgd)))\r\n \r\n#Segundo algoritmo - fim","sub_path":"Parte1.py","file_name":"Parte1.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"262172188","text":"\n\n\nfrom random import randint\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\n\n\n__author__ = 'hamid'\n\n\n\n\n\ndef search_base(request):\n movie_names=[]\n movie_descriptions=[]\n movie_images=[]\n movie_yearProduction=[]\n celeb_names=[]\n celeb_descriptions=[]\n celeb_images=[]\n\n random=randint(0,2)\n print('random: '+str(random))\n if random==0:\n movie_names.append('پرویز پرستویی')\n movie_names.append('ثریا قاسمی')\n celeb_names.append('بادیگارد')\n celeb_names.append('جدایی نادر از سیمین')\n movie_yearProduction.append('۱۳۹۴')\n movie_yearProduction.append('۱۳۸۹')\n celeb_descriptions.append('بازیگر')\n celeb_descriptions.append('بازیگر')\n movie_descriptions.append('کارگردان: ابراهیم حاتمی کیا')\n movie_descriptions.append('کارگردان: اصغر فرهادی')\n celeb_images.append('/media/images/base/0.jpg')\n celeb_images.append('/media/images/base/1.jpg')\n movie_images.append('/media/images/base/2.jpg')\n movie_images.append('/media/images/base/3.jpg')\n else:\n movie_names.append('بادیگارد')\n celeb_names.append('باران کوثری')\n movie_names.append('بارکد')\n celeb_names.append('بهرام رادان')\n celeb_names.append('بابک حمیدیان')\n movie_yearProduction.append('۱۳۹۴')\n movie_yearProduction.append('۱۳۹۴')\n movie_descriptions.append('کارگردان: ابراهیم حاتمی کیا')\n celeb_descriptions.append('بازیگر')\n movie_descriptions.append('کارگردان: مصطفی کیایی')\n celeb_descriptions.append('بازیگر')\n celeb_descriptions.append('بازیگر')\n movie_images.append('/media/images/base/4.jpg')\n celeb_images.append('/media/images/base/0.jpg')\n movie_images.append('/media/images/base/1.jpg')\n celeb_images.append('/media/images/base/2.jpg')\n celeb_images.append('/media/images/base/3.jpg')\n\n return JsonResponse({'celeb_names':celeb_names,'celeb_descriptions':celeb_descriptions,'celeb_images':celeb_images,\n 'movie_names':movie_names,'movie_descriptions':movie_descriptions,'movie_images':movie_images,\n 'movie_yearProduction':movie_yearProduction})\n\n\n\nclass SearchSuggestion:\n name=''\n description=''\n image=''\n\n def __init__(self,name,job,image):\n self.name=name\n self.job=job\n self.image=image\n\n\ndef mostVisited(request):\n mostVisited_names=[]\n mostVisited_names.append('جدایی نادر از سیمین')\n mostVisited_names.append('آژانس شیشه ای')\n mostVisited_names.append('نمی دونم')\n mostVisited_names.append('قیصر')\n mostVisited_names.append('مارمولک')\n return JsonResponse({'mostVisited_names':mostVisited_names})\n\n\n\n\ndef index(request):\n\n news=[]\n last_images=[]\n poll_images=[]\n\n i=0\n while i<4:\n i+=1\n j=0\n item=[]\n while j<4:\n j+=1\n item.append(Item(news_title='news_title_'+str(i)+'_'+str(j)\\\n ,news_link='https://www.google.com/?gws_rd=ssl'))\n\n news.append(News(str(i-1)+'.jpg','main_news_title_'+str(i),'main_news_article_'+str(i),item))\n\n news[0].button_label=\"سینمای ایران\"\n news[1].button_label=\"سینمای جهان\"\n news[2].button_label=\"تلویزیون\"\n news[3].button_label=\"هنرمندان\"\n\n news[3].main_news_title=\"hay\"\n\n\n i=0\n while i<4:\n i+=1\n last_images.append(LastImage(str(i-1)+\".jpg\",\"group title \"+str(i),\"number of images \"+str(randint(1,5))))\n\n\n i=-1\n while i<4:\n i+=1\n poll_images.append('/media/images/index/Poll/'+str(i)+'.jpg')\n\n\n bestReviewImage='/media/images/index/sideBar/bestReview.jpg'\n bestReviewDescription='عباس کیارستمی حرفه ای ترین کارگردان ایرانی است و بیشترین همکاری ها را با کمپانی های خارجی داشته است' \\\n 'طبق افشاگری اخیر خانم ژولیت بینوش او در تازه ترین تجربه اش به چین رفته و فیلمی در این کشور می سازد.'\n\n mostVisited_images=[]\n mostVisited_images.append('/media/images/base/0.jpg')\n mostVisited_images.append('/media/images/base/1.jpg')\n mostVisited_images.append('/media/images/base/2.jpg')\n mostVisited_images.append('/media/images/base/3.jpg')\n mostVisited_images.append('/media/images/base/4.jpg')\n\n mostVisited_names=[]\n mostVisited_names.append('جدایی نادر از سیمین')\n mostVisited_names.append('آژانس شیشه ای')\n mostVisited_names.append('نمی دونم')\n mostVisited_names.append('قیصر')\n mostVisited_names.append('مارمولک')\n\n\n return render(request,'index.html',{'news':news,'last_images':last_images,'poll_images':poll_images,\n 'best_review':bestReviewImage,'best_review_description':bestReviewDescription,\n 'mostVisited_names':mostVisited_names,'mostVisited_images':mostVisited_images})\n\n\n\n\nclass Item:\n news_title=\"\"\n news_link=\"\"\n\n def __init__(self,news_title,news_link):\n self.news_title=news_title\n self.news_link=news_link\n\n\nclass News:\n image_name=\"\"\n button_label=\"\"\n main_news_title=\"\"\n main_news_article=\"\"\n item={}\n\n def __init__(self,image_name,main_news_title,main_news_article,item):\n self.image_name=image_name\n self.main_news_title=main_news_title\n self.main_news_article=main_news_article\n self.item=item\n\n\nclass LastImage:\n\n # title of this group of images.\n title=\"\"\n #number of images in this group.\n images_number=\"\"\n #this image name.\n name=\"\"\n\n def __init__(self,name,title,images_number):\n self.name=name\n self.title=title\n self.images_number=images_number\n\n\n\n\n\n\n\n\n\n\n\n\ndef top100(request):\n movies=[]\n sideBar_mostPoints=[]\n\n\n i=-1\n while(i<9):\n i+=1\n rand=randint(1000,2000)\n point=randint(0,10)\n temp=Movie1(\"اسم\"+str(i),str(i)+\".jpg\",1394-i,rand,point)\n movies.append(temp)\n\n sideBar_mostPoints.append(SideBar_mostGenrePoints('اکشن',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('درام',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('عاشقانه',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('انیمیشن',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('فانتزی',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('علمی تخیلی',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('بیوگرافی',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('تاریخی',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('کوتاه',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('کمدی',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('ترسناک',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('تریلر',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('جنایی',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('موزیکال',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('جنگی',''))\n sideBar_mostPoints.append(SideBar_mostGenrePoints('مستند',''))\n\n\n return render(request,'top100.html',{'movies':movies,'sideBar_mostPoints':sideBar_mostPoints})\n\n\n\nclass Movie1:\n url=\"\"\n name=\"\"\n year=0\n commentNumber=0\n point=0\n\n def __init__(self,name,url,year,commentNumber,point):\n self.name=name\n self.url=url\n self.year=year\n self.commentNumber=commentNumber\n self.point=point\n\n\n\nclass SideBar_mostGenrePoints:\n name=''\n url=''\n\n def __init__(self,name,url):\n self.name=name\n self.url=url\n\n\n\n\n\ndef movie(request):\n\n slider_images=[]\n i=-1\n while(i<4):\n i+=1\n slider_images.append('/media/images/test/slider'+str(i)+'.jpg')\n\n\n\n mainActors=[]\n i=-1\n while(i<3):\n i+=1\n mainActors.append(\"/media/images/movie/actor\"+str(i)+\".jpg\")\n\n\n\n fActors=[]\n i=-1\n while(i<4):\n i+=1\n temp1=FActor(\"/media/images/movie/fActor\"+str(i)+\".jpg\",\"اسم\"+str(i),\"اسم تو فیلم\"+str(i))\n fActors.append(temp1)\n fActors.append(FActor(\"/static/icons/movie/defaultUserImg.jpg\",\"اسم بازیگر\",\"اسم تو فیلم بازیگر\"))\n fActors[0].name=\"چرا من اینو\"\n fActors.append(FActor('/media/images/actor/image0.jpg','مریم','سرباز اول'))\n\n\n\n keywords=[]\n keywords.append(\"خانواده\")\n keywords.append(\"طلاق\")\n keywords.append(\"مهاجرت\")\n keywords.append(\"دروغ\")\n keywords.append(\"پدر\")\n\n\n\n bestDialogue=[]\n bestDialogue.append(\"اون نمی دونه من پسرشم. من که می دونم اون پدرمه\")\n bestDialogue.append(\"چرا من آخه\")\n bestDialogue.append(\"بودن یا نبودن مساله این است.\")\n bestDialogue.append(\"دیالوگ ماندگار\")\n bestDialogue.append(\"دیالوگ ماندگار بعدی\")\n\n\n mov=Movie2(\"جدایی نادر از سیمین\",1389,119,\"درام\",8.9,400,\"اصغر فرهادی\",\"اصغر فرهادی\",2,34\n ,\"این فیلم جدایی نادر از سیمینه دیگه\",mainActors,fActors,keywords,3500000000,bestDialogue)\n\n\n\n circles=[]\n point=mov.point\n i=0\n while(i<10):\n if(i 3:\n return False, []\n if dist(node, cars[car][0]) > 10000:\n return False, []\n if len(cars[car][1]) > 0:\n detours, order = detour(cars[car][0], node, destnode, cars[car][1])\n if (max(detours) > 10000):\n return False, []\n else:\n return True, order\n return True, [0]\n\ndef deepValidate(node, car, destnode, order):\n global nodes, cars\n dist, path = shortpath.getRoad(node, cars[car][0])\n if (dist > 10000):\n return False, [0]\n\n distpick, path = shortpath.getRoad(cars[car][0], node)\n disttmp = distpick\n nodetmp = node\n info = [[] for i in order]\n for sp in order:\n if (sp == len(cars[car][1])):\n dist, path = shortpath.getRoad(nodetmp, destnode)\n disttmp += dist\n dist, path = shortpath.getRoad(node, destnode)\n if (disttmp - distpick - dist > 10000):\n return False, [0]\n info[sp] = [dist, disttmp - distpick]\n else:\n dist, path = shortpath.getRoad(nodetmp, cars[car][1][sp])\n disttmp += dist\n dist, path = shortpath.getRoad(cars[car][0], cars[car][1][sp])\n if (disttmp - dist > 10000):\n return False, [0]\n info[sp] = [dist, disttmp]\n dist, path = shortpath.getRoad(cars[car][0], node)\n return True, [dist, info]\n\ndef search(node, destnode):\n global nodes, cars, gridcars\n grid = 5000\n stepList = [[0, 0], [0, 1], [1, 0], [0, -1], [-1, 0], [1, 1], [1, -1], [-1, -1],\n [-1, 1], [0, 2], [2, 0], [0, -2], [-2, 0], [1, 2], [2, 1], [-1, 2],\n [-2, 1], [1, -2], [2, -1], [-1, -2], [-2, -1], [2, 2], [-2, 2],\n [2, -2], [-2, -2]]\n\n gx = int(nodes[node][0] / 5000)\n gy = int(nodes[node][1] / 5000)\n\n res = []\n for step in stepList:\n px = gx + step[0]\n py = gy + step[1]\n if px < 0 or px >= 38:\n continue\n if py < 0 or py >= 32:\n continue\n for car in gridcars[px * 32 + py]:\n flag, order = validate(node, car, destnode)\n if (flag):\n detourInfo = [0]\n if deepValidateFlag:\n flag, detourInfo = deepValidate(node, car, destnode, order)\n if not flag:\n continue\n res.append([car, order, detourInfo])\n if len(res) == 5:\n break\n if len(res) == 5:\n break\n return res\n\ndef init(ns, cs, gs):\n global nodes, cars, gridcars\n nodes = ns\n cars = cs\n gridcars = gs\n\nif __name__ == \"__main__\":\n res = search(5000, 5001)\n print(res)\n","sub_path":"TAXISearcher/src/getcar.py","file_name":"getcar.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"560570981","text":"# -*- coding: utf-8 -*-\n\nfrom django.db import models\n\nfrom symposion.proposals.models import ProposalBase\n\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass Proposal(ProposalBase):\n \n #AUDIENCE_LEVEL_NOVICE = 1\n #AUDIENCE_LEVEL_EXPERIENCED = 2\n #AUDIENCE_LEVEL_INTERMEDIATE = 3\n \n TOPIC_AREAS = [\n (1, u\"Redes de Atenção à Saúde\"),\n (2, u\"Saúde Mental, Álcool, Crack e outras Drogas\"),\n (3, u\"Vigilância em Saúde\"),\n (4, u\"Experiências Pedagógicas Inovadoras\"),\n (5, u\"Etnia, Raça e Saúde\"),\n (6, u\"Educação Permanente em Saúde\"),\n (7, u\"Educação Popular em Saúde, mobilização, controle e participação social em experiências de formação\"),\n (8, u\"Formação em Residências para o SUS\"),\n ]\n \n audience_level = models.IntegerField(_(u\"Eixo Temático\"),choices=TOPIC_AREAS)\n #topic_area = models.IntegerField(_(u\"Eixo Temático\"),choices=TOPIC_AREAS)\n \n recording_release = models.BooleanField(\n _(u\"Liberação para gravação\"), \n default=True,\n help_text=_(u\"Ao enviar sua proposta, você concorda em dar permissão para os organizadores do congresso para gravar, editar e lançar áudio e/ou vídeo de sua apresentação. Se você não concorda com isso, por favor, desmarque esta caixa.\")\n )\n \n \n class Meta:\n abstract = True\n ProposalBase._meta.get_field(\"title\").verbose_name = u\"Título\"\n \n ProposalBase._meta.get_field('description').verbose_name = u\"Breve Resumo\"\n ProposalBase._meta.get_field('description').help_text = u\"Se a sua apresentação for aceita isso será tornado público e impresso no programa. Deve ser um parágrafo, no máximo 400 caracteres.\"\n \n ProposalBase._meta.get_field('abstract').verbose_name = u\"Resumo Detalhado\"\n ProposalBase._meta.get_field('abstract').help_text = u\"Descrição detalhada e esboço. Isso será tornado público, se sua apresentação for aceita. Edite usando Markdown.\"\n \n ProposalBase._meta.get_field('additional_notes').verbose_name = u\"Observações\"\n ProposalBase._meta.get_field('additional_notes').help_text = u\"Qualquer outra informação que você gostaria que a comissão científica soubesse ao fazer a sua seleção: sua experiência passada como palestrante, as experiências relevantes deste trabalho, etc. Edite usando Markdown.\"\n\n\nclass TalkProposal(Proposal):\n class Meta:\n verbose_name = \"talk proposal\"\n\n\nclass TutorialProposal(Proposal):\n class Meta:\n verbose_name = \"tutorial proposal\"\n","sub_path":"congrefor/proposals/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"490498501","text":"from cooperative_transport.utils import saturation\nimport numpy as np\n\ndef proportional_control(k_p, r, y, u_max, avoid_overturning):\n \"\"\"Implement proportional control law.\n\n Arguments:\n k_p (float): Proportional gain\n r (float): reference signal\n y (float): system output signal\n u_max (float): maximum control effort\n avoid_overturning (bool): if True avoids rotation greater than pi\n \"\"\"\n error = r - y\n if avoid_overturning:\n if abs(error) > np.pi:\n error += -2 * np.pi * np.sign(error)\n\n u = k_p * error\n saturated_u = saturation(u ,u_max)\n return saturated_u\n","sub_path":"src/cooperative_transport/control/proportional_control.py","file_name":"proportional_control.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"642347323","text":"import socket, os, sys, subprocess, time, signal, uuid\nimport urllib.request\nglobal ip_str, discovered_ip, max_range, no_reach\nno_reach = False\nmax_range = 255\ndiscovered_ip = []\nver = str(2.0)\ndef lip():\n ip_string=str(os.popen('ifconfig | grep -E \"([0-9]{1,3}[\\.]){3}[0-9]{1,3}\"').readlines())[15:];result=\"\";i=0\n while ip_string[i]!=\" \":result=result+ip_string[i];i=i+1\n return result\n\nip_str = lip()\nBLUE, RED, WHITE, YELLOW, MAGENTA, GREEN, END = '\\33[94m', '\\033[91m', '\\33[97m', '\\33[93m', '\\033[1;35m', '\\033[1;32m', '\\033[0m'\n\ndef getip():\n\treturn socket.gethostbyname(socket.gethostname())\n\ndef quit():\n os.system('clear')\n exit()\n\ndef line():\n sys.stdout.write(MAGENTA + \"\"\"--------------------------------------------------------------------\"\"\" + '\\n')\n\ndef banner():\n spaces = \" \" * 76\n sys.stdout.write(GREEN + spaces + \"\"\"\n ███▄ ▄███▓ ██▀███ ██████ ▄████▄ ▄▄▄ ███▄ █\n ▓██▒▀█▀ ██▒▓██ ▒ ██▒▒██ ▒ ▒██▀ ▀█ ▒████▄ ██ ▀█ █\n ▓██ ▓██░▓██ ░▄█ ▒░ ▓██▄ ▒▓█ ▄ ▒██ ▀█▄ ▓██ ▀█ ██▒\n ▒██ ▒██ ▒██▀▀█▄ ▒ ██▒▒▓▓▄ ▄██▒░██▄▄▄▄██ ▓██▒ ▐▌██▒\n ▒██▒ ░██▒░██▓ ▒██▒▒██████▒▒▒ ▓███▀ ░ ▓█ ▓██▒▒██░ ▓██░\n ░ ▒░ ░ ░░ ▒▓ ░▒▓░▒ ▒▓▒ ▒ ░░ ░▒ ▒ ░ ▒▒ ▓▒█░░ ▒░ ▒ ▒\n ░ ░ ░ ░▒ ░ ▒░░ ░▒ ░ ░ ░ ▒ ▒ ▒▒ ░░ ░░ ░ ▒░\n ░ ░ ░░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░\n ░ ░ ░ ░ ░ ░ ░ ░\n ░\n \"\"\" + YELLOW + \"\"\"Version \"\"\" + str(ver) + RED + \"\"\" (By b3rt1ng)\"\"\" + '\\n')\n line()\n\ndef get_mac(ip):\n command = \"arp | grep \" + str(ip)\n r = subprocess.check_output([command], shell=True)\n r=str(r) \n r=r[35:]\n r=r[:17]\n return r\n\ndef resolveMac(mac):\n url = \"https://api.macvendors.com/\" + str(mac)\n b_str = urllib.request.urlopen(url).read()\n b_str = str(b_str, 'utf-8')\n return b_str\n\ndef ip_info(ip):\n os.system('clear')\n sys.stdout.write(BLUE + \"\"\"IP: \"\"\" + GREEN + str(ip) + '\\n')\n mac = get_mac(ip)\n sys.stdout.write(BLUE + \"\"\"Mac: \"\"\" + GREEN + str(mac) + '\\n')\n vendor = resolveMac(mac)\n sys.stdout.write(BLUE + \"\"\"Vendor: \"\"\" + GREEN + vendor + '\\n')\n stopper()\n\n\ndef ping(ip):\n try:\n subprocess.check_output([\"ping\", \"-c\", \"1\", ip])\n return True \n except subprocess.CalledProcessError:\n return False\n\ndef version():\n git=str(urllib.request.urlopen(\"https://raw.githubusercontent.com/b3rt1ng/MR_SCAN_V2/master/version\").read())\n git=git[:-3]\n git=git.replace('b', '')\n git=git.replace(\"'\", '')\n return git\ncur=version()\n\ndef ipbase():\n stop = 3\n size = len(ip_str)\n ip_resized = ip_str[:-2]\n return str(ip_resized)\n\n\ndef scan():\n fisrt = 0\n ip = ipbase()\n sub = 0\n full_ip = ip + str(sub)\n while sub <= max_range:\n try:\n full_ip = ip + str(sub)\n if ping(full_ip) is True:\n if fisrt == 0:\n os.system('clear')\n fisrt = fisrt + 1\n discovered_ip.append(full_ip)\n sys.stdout.write(MAGENTA + \"\"\"[\"\"\" + GREEN + \"\"\"+\"\"\" + MAGENTA + \"\"\"] \"\"\"); sys.stdout.write(YELLOW + full_ip); sys.stdout.write(WHITE + ' is reachable' + '\\n')\n else:\n if fisrt == 0:\n os.system('clear')\n fisrt = fisrt + 1\n if no_reach==True:\n sys.stdout.write(MAGENTA + \"\"\"[\"\"\" + RED + \"\"\"-\"\"\" + MAGENTA + \"\"\"] \"\"\"); sys.stdout.write(YELLOW + full_ip); sys.stdout.write(WHITE + ' is not reachable' + '\\n')\n sub = sub + 1\n except:\n os.system('clear')\n sys.stdout.write(MAGENTA + \"\"\"[\"\"\" + RED + \"\"\"!\"\"\" + MAGENTA + \"\"\"]\"\"\" + WHITE + ' interrupted.' + '\\n')\n time.sleep(1)\n sys.stdout.write(MAGENTA + \"\"\"[\"\"\" + RED + \"\"\"?\"\"\" + MAGENTA + \"\"\"]\"\"\" + WHITE + ' returning to main menu.' + '\\n')\n time.sleep(1)\n menu()\n \ndef stopper():\n try:\n sys.stdout.write('\\n' + MAGENTA + \"\"\"[\"\"\" + RED + \"\"\"?\"\"\" + MAGENTA + \"\"\"]\"\"\" + YELLOW + ' Hit CTRL + C to get back on the menu.' + '\\n')\n time.sleep(6200)\n except:\n menu()\n\ndef show_disip():\n i=0\n while i < len(discovered_ip):\n sys.stdout.write(MAGENTA + \"\"\"[\"\"\" + RED + str(i) + MAGENTA + \"\"\"] \"\"\" + YELLOW + str(discovered_ip[i]) + '\\n')\n i = i + 1\n stopper()\n\ndef empty():\n sys.stdout.write(MAGENTA + \"\"\"[\"\"\" + RED + \"\"\"?\"\"\" + MAGENTA + \"\"\"]\"\"\" + YELLOW + ' The list is currently empty.' + '\\n')\n stopper()\n\ndef result():\n os.system('clear')\n if len(discovered_ip)==0:\n empty()\n else:\n show_disip()\n\ndef param():\n os.system('clear')\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"*\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Maximum range: \"\"\" + GREEN)\n print(max_range)\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"*\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Your IP: \"\"\" + GREEN)\n print(ip_str)\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"*\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Show unreachable IP: \"\"\" + GREEN)\n print(no_reach)\n stopper()\n\n\ndef adv_ip():\n os.system('clear')\n print(YELLOW, discovered_ip)\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"*\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Type in an IP: \"\"\" + GREEN)\n IP = input()\n ip_info(IP)\n\ndef menu():\n os.system('clear')\n banner()\n sys.stdout.write('\\n')\n if cur != ver:\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"!\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Another version is avariable on github\"\"\" + '\\n')\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"1\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Start Scan\"\"\" + '\\n')\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"2\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Display discovered IP\"\"\" + '\\n')\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"3\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Advanced IP informations\"\"\" + '\\n')\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"4\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Settings\"\"\" + '\\n')\n sys.stdout.write( RED + \"\"\"[\"\"\" + BLUE + \"\"\"5\"\"\" + RED + \"\"\"]\"\"\" + YELLOW + \"\"\" Exit\"\"\" + '\\n')\n sys.stdout.write('\\n')\n sys.stdout.write( RED + \"\"\"Mr\"\"\" + YELLOW + \"\"\"_\"\"\" + BLUE + \"\"\"Scan\"\"\" + MAGENTA + \"\"\":\"\"\" + GREEN + \"\"\" \"\"\")\n choice = input()\n if choice==\"1\":\n scan()\n elif choice==\"2\":\n result()\n elif choice==\"3\":\n adv_ip()\n elif choice==\"4\":\n param()\n elif choice==\"5\":\n os.system('clear')\n exit()\n\n\n\nmenu()\n","sub_path":"MR_SCAN_V2.py","file_name":"MR_SCAN_V2.py","file_ext":"py","file_size_in_byte":7147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"540625166","text":"# Расчет результатов\n# Создайте функцию, которая подсчитывать расстояние, что проедет человек.\n\n# Функция принимает два параметра: время и скорость. \n\n# При выводе результат используйте функцию lambda для вывода корректной информации:\n\n# выводите строку: \"Вы проедете: 1 километр\", если результат был равен единице\n# выводите строку: \"Вы проедете: цифра километров\", если результат был большим за единицу\n\n# Solution: \n\ndef distance (speed, time = 1):\n dist = time * speed\n return dist\n\ndist = distance(int(input(\"Укажите скорость: \")), int((input(\"Укажите время: \"))))\n\nended = str((lambda a: \"километр.\" if dist == 1 else \"километров.\")(dist))\n\nprint (\"Вы проедете:\", dist, ended)\n","sub_path":"lesson12/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"448957584","text":"import pyautogui as MI\r\nimport groupsFF as group\r\nimport time\r\nimport math\r\nMI.PAUSE = 0.001\r\n\r\n\r\n\r\ndef main():\r\n loops = 0\r\n while(True):\r\n loops = 0\r\n while(loops < 70):\r\n print(loops)\r\n ##Selina\r\n MI.click(1832,482)\r\n time.sleep(0.5)\r\n\r\n ##Shop\r\n MI.click(1106,326)\r\n time.sleep(0.5)\r\n\r\n ##Select Item\r\n MI.click(1258,742)\r\n time.sleep(0.5)\r\n\r\n ##Purchase Item\r\n MI.click(1430,535)\r\n time.sleep(0.5)\r\n\r\n ##Exit\r\n MI.click(1907, 242)\r\n time.sleep(0.5)\r\n\r\n loops = loops + 1\r\n\r\n ##Exit Again\r\n MI.click(1907, 242)\r\n time.sleep(0.5)\r\n \r\n ##Open Inventory\r\n inventory = MI.locateCenterOnScreen('images/skills/inventory.png', confidence = 0.85, region = (1640, 800, 40, 50))\r\n while(not inventory):\r\n inventory = MI.locateCenterOnScreen('images/skills/inventory.png', confidence = 0.85, region = (1640, 800, 40, 50))\r\n\r\n ##Click Inventory\r\n MI.click(inventory)\r\n time.sleep(1)\r\n ##Close Inventory\r\n MI.click(1911,248)\r\n time.sleep(1)\r\n \r\n\r\nmain()","sub_path":"itemPurchase.py","file_name":"itemPurchase.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"404401669","text":"\"\"\"\n\"\"\"\nimport requests\nimport datetime\nfrom locust import events\n\n\nclass DataBuffer:\n \"\"\"\n \"\"\"\n\n def __init__(self, hostname, *args, buffer_limit=20, **kwargs):\n \"\"\"\n Creates and starts a DataBuffer that stores request data\n so that it can be sent in batches to the server.\n Data is uploaded when the buffer_limit is reached,\n or the test completes\n \"\"\"\n print(\"Nile: Initializing Data Buffer\")\n self.hostname = hostname\n self.buffer_limit = buffer_limit\n\n self.data_endpoint = f'http://{hostname}/api/v1/requests'\n self.buffer = list()\n\n events.request_success += self.request_success\n events.request_failure += self.request_failure\n events.quitting += self.on_quitting\n\n def request_success(self, request_type, name,\n response_time, response_length, **kwargs):\n\n self._on_request_data(request_type, name, response_time,\n response_length, True, None)\n\n def request_failure(self, request_type, name, response_time,\n response_length, exception, **kwargs):\n\n self._on_request_data(request_type, name, response_time,\n response_length, False, exception)\n\n def _on_request_data(self, request_type, name, response_time,\n response_length, success, exception, **kwargs):\n\n data = {\n 'request_method': request_type,\n 'name': name,\n 'response_time': response_time,\n 'response_length': response_length,\n 'success': success,\n 'exception': exception}\n\n if 'request_timestamp' in kwargs:\n data['request_timestamp'] = kwargs['request_timestamp']\n else:\n request_time = datetime.datetime.now() \\\n - datetime.timedelta(milliseconds=response_time)\n data['request_timestamp'] = request_time.isoformat()\n\n if 'request_length' in kwargs:\n data['request_length'] = kwargs['request_length']\n else:\n data['request_length'] = None\n\n if 'status_code' in kwargs:\n data['status_code'] = kwargs['status_code']\n else:\n data['status_code'] = None\n\n self.buffer.append(data)\n if len(self.buffer) > self.buffer_limit:\n self._upload_buffer()\n\n def on_quitting(self):\n print('Nile: Handling Test Shutdown')\n self._upload_buffer()\n\n def _upload_buffer(self):\n contents = self.buffer\n self.buffer = list()\n print('Nile: Uploading Buffer with size ' + str(len(contents)))\n requests_endpoint = f'http://{self.hostname}/api/v1/requests'\n\n response = requests.post(requests_endpoint, json=contents)\n if response.status_code != 200:\n raise RuntimeError(f'Could not upload buffer after test \\\n shutdown {response}')\n","sub_path":"nile_lib/nile_test/integration/databuffer.py","file_name":"databuffer.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"646580505","text":"from numpy import sin,cos,array\r\nfrom visual import sphere,color,rate,display,arrow\r\n\r\ndef f(val,t): #vorticity vector\r\n r = val[0]\r\n th = val[1]\r\n z = val[2]\r\n dr = 3*dP*t\r\n dth = 0.01\r\n dz = v_inlet*0.01\r\n return array([dr,dth,dz],dtype=float)\r\n\r\ndef rk4(val,t):\r\n k1 = f(val,t)\r\n k2 = f(val+0.5*k1,t+0.5*h)\r\n k3 = f(val+0.5*k2,t+0.5*h)\r\n k4 = f(val+k3,t+h)\r\n dval = (k1+2*k2+2*k3+k4)/6\r\n val += dval\r\n return array([val,dval],dtype=float)\r\n \r\n#define constants and lists\r\nr = []\r\nth = []\r\nz = []\r\nvr = []\r\nvth = []\r\nvz = []\r\nt = []\r\nvelvec = {}\r\n\r\n#\r\nh = 1e-5\r\ni = 0\r\niterations = 5000\r\n\r\nv_inlet = float(input('Enter a freestream velocity (mph):')) #165 #freestream (mph) typical for airliner takeoff\r\ndP = float(input('Enter a pressure difference:'))#3 #pressure difference induced by wing (atm/atm)\r\n\r\n#initialize and set values\r\nt.append(0.0)\r\nvr.append(0.0)\r\nvth.append(0.01)\r\nvz.append(v_inlet)\r\nval = array([0.1,0.0,0.0],dtype=float)\r\ndval = array([0.0,0.0,0.0],dtype=float)\r\nout = ([val,dval])\r\n\r\n#solve for vortex ryz coordinates over time\r\nwhile(i < iterations):\r\n r.append(val[0])\r\n th.append(val[1])\r\n z.append(val[2])\r\n vr.append(dval[0])\r\n vth.append(dval[1])\r\n vz.append(dval[2])\r\n out = rk4(val,t[i])\r\n val = out[0]\r\n dval = out[1]\r\n t.append(t[i]+h)\r\n i += 1\r\n\r\n#display vortex\r\nscene = display(title='Airfoil Induced Vortex',width=1280, height=1024, center=[0,0,0], background=color.black)\r\nscene.cursor.visible = False\r\nviews = [[1,0,0],[1,-1,-1],[0,0,-1]] #side, iso, z\r\nscene.forward = views[1]\r\nvortex = sphere(pos=[0,0,0],radius=0.01,make_trail=True)\r\nvortex.color = color.blue\r\nvl = sphere(pos=[0,0,0],radius=0.01,make_trail=True)\r\nvl.trail_object.color = (0,0.8,0)\r\n\r\n#scale rate of animation and size of vectors\r\nscaleAnim = 500\r\nscaleVec = 0.05\r\n\r\n#display the position, vortex line, and velocity vectors of the vortex\r\nfor i in range(0,iterations):\r\n rate(scaleAnim)\r\n vortex.pos = [r[i]*cos(th[i]),r[i]*sin(th[i]),z[i]]\r\n vl.pos = [0,0,z[i]]\r\n pos1 = array([r[i]*cos(th[i]),r[i]*sin(th[i]),z[i]])\r\n \r\n #adjust view - ONLY for isometric view (view[1])\r\n if(i < (iterations*3/4)):\r\n scene.center = [0,0,z[i]]\r\n \r\n #show velocity vector every 75 iterations\r\n if(i%75 == 0): \r\n prev = array([r[i-1]*cos(th[i-1]),r[i-1]*sin(th[i-1]),z[i-1]])\r\n vel = (pos1-prev)/(t[i]-t[i-1])\r\n j = i/50\r\n velvec[j] = arrow(pos=pos1, axis=vel*scaleVec*t[i], shaftwidth=5*scaleVec)\r\n velvec[j].color = (0,0.75,1)\r\n \r\n#calculate initial freestream velocity and pressure difference based on final iteration\r\ndPcalc = (r[iterations-1]-r[iterations-2])/(t[iterations-1]-t[iterations-2])/t[iterations-1]/3*h\r\nprint('Initial Freestream Velocity:',(z[iterations-1]-z[iterations-2])*100,'mph')\r\nprint('Initial Pressure Difference:',dPcalc)\r\n","sub_path":"AirfoilVorticesFinal.py","file_name":"AirfoilVorticesFinal.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"282397730","text":"import h5py\nimport pickle\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\n\n\n# Allow user to choose which embedding to use\nprint(\"__BLOG EMBEDDINGS__\")\nprint(\"1: Time\")\nprint(\"2: Age\")\nprint(\"3: Topic (Computer Similarity)\")\nprint(\"4: Topic (Human Similarity)\")\nchoice = input(\"To select an embedding, enter a number 0 through 4: \")\nchoice = int(choice)\nprint()\n\n# Based on which embedding the user chooses, define the necessary settings\nif choice == 1:\n file_str = 'embeddings/embeddings-time-5iter.h5'\n vocab_file_str = 'embeddings/blog_vocab_age.pkl'\n categories = [\n 'APR03', 'MAY03', 'JUN03', 'JUL03', 'AUG03', 'SEP03', 'OCT03', 'NOV03', 'DEC03',\n 'JAN04', 'FEB04', 'MAR04', 'APR04', 'MAY04', 'JUN04', 'JUL04', 'AUG04'\n ]\nelif choice == 2:\n file_str = 'embeddings/embeddings-age-5iter.h5'\n vocab_file_str = 'embeddings/blog_vocab_age.pkl'\n categories = ['13to15', '16to18', '19to21', '22to24', '25to27', '28to30',\n '31to33', '34to36', '37to39', '40to42', '42to47']\nelif choice == 3:\n file_str = 'embeddings/embeddings-topic-human-5iter.h5'\n vocab_file_str = 'embeddings/blog_vocab_topic.pkl'\n categories = ['Accounting', 'Advertising', 'Arts', 'Banking', 'BusinessServices', 'Chemicals',\n 'Communications-Media', 'Consulting', 'Education', 'Engineering', 'Fashion', 'Government', 'Internet',\n 'Law', 'Marketing', 'Non-Profit', 'Publishing', 'Religion', 'Science', 'Student', 'Technology']\nelif choice == 4:\n file_str = 'embeddings/embeddings-topic-ppmi_cosine-5iter.h5'\n vocab_file_str = 'embeddings/blog_vocab_topic.pkl'\n categories = ['Accounting', 'Advertising', 'Arts', 'Banking', 'BusinessServices', 'Chemicals',\n 'Communications-Media', 'Consulting', 'Education', 'Engineering', 'Fashion', 'Government', 'Internet',\n 'Law', 'Marketing', 'Non-Profit', 'Publishing', 'Religion', 'Science', 'Student', 'Technology']\nelse:\n print(\"The input you gave was invalid\")\n\n# Load the dataset\nprint(\"Loading dataset...\")\nfile = h5py.File(file_str, 'r')\n\n# for key in file.keys():\n# print(key)\n\nembedding = file['U']\n\nfile = h5py.File('embeddings/blog_dataset_sample.h5', 'r')\ntopics = file['label'][:, 0]\n\n# print(embedding.shape)\n# print(embedding[:, :, 1])\n\n\n# Utility script to find the nearest neighbors to the word at a given